WebView.java revision c1cba781d37910e61591cffda50633f1db6cc4ea
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 = 1040;
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();
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();
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();
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();
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();
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();
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     */
1815    private void clearTextEntry() {
1816        if (inEditingMode()) {
1817            mWebTextView.remove();
1818        } else {
1819            // The keyboard may be open with the WebView as the served view
1820            hideSoftKeyboard();
1821        }
1822    }
1823
1824    /**
1825     * Return the current scale of the WebView
1826     * @return The current scale.
1827     */
1828    public float getScale() {
1829        return mZoomManager.getScale();
1830    }
1831
1832    /**
1833     * Set the initial scale for the WebView. 0 means default. If
1834     * {@link WebSettings#getUseWideViewPort()} is true, it zooms out all the
1835     * way. Otherwise it starts with 100%. If initial scale is greater than 0,
1836     * WebView starts will this value as initial scale.
1837     *
1838     * @param scaleInPercent The initial scale in percent.
1839     */
1840    public void setInitialScale(int scaleInPercent) {
1841        mZoomManager.setInitialScaleInPercent(scaleInPercent);
1842    }
1843
1844    /**
1845     * Invoke the graphical zoom picker widget for this WebView. This will
1846     * result in the zoom widget appearing on the screen to control the zoom
1847     * level of this WebView.
1848     */
1849    public void invokeZoomPicker() {
1850        if (!getSettings().supportZoom()) {
1851            Log.w(LOGTAG, "This WebView doesn't support zoom.");
1852            return;
1853        }
1854        clearTextEntry();
1855        mZoomManager.invokeZoomPicker();
1856    }
1857
1858    /**
1859     * Return a HitTestResult based on the current cursor node. If a HTML::a tag
1860     * is found and the anchor has a non-javascript url, the HitTestResult type
1861     * is set to SRC_ANCHOR_TYPE and the url is set in the "extra" field. If the
1862     * anchor does not have a url or if it is a javascript url, the type will
1863     * be UNKNOWN_TYPE and the url has to be retrieved through
1864     * {@link #requestFocusNodeHref} asynchronously. If a HTML::img tag is
1865     * found, the HitTestResult type is set to IMAGE_TYPE and the url is set in
1866     * the "extra" field. A type of
1867     * SRC_IMAGE_ANCHOR_TYPE indicates an anchor with a url that has an image as
1868     * a child node. If a phone number is found, the HitTestResult type is set
1869     * to PHONE_TYPE and the phone number is set in the "extra" field of
1870     * HitTestResult. If a map address is found, the HitTestResult type is set
1871     * to GEO_TYPE and the address is set in the "extra" field of HitTestResult.
1872     * If an email address is found, the HitTestResult type is set to EMAIL_TYPE
1873     * and the email is set in the "extra" field of HitTestResult. Otherwise,
1874     * HitTestResult type is set to UNKNOWN_TYPE.
1875     */
1876    public HitTestResult getHitTestResult() {
1877        if (mNativeClass == 0) {
1878            return null;
1879        }
1880
1881        HitTestResult result = new HitTestResult();
1882        if (nativeHasCursorNode()) {
1883            if (nativeCursorIsTextInput()) {
1884                result.setType(HitTestResult.EDIT_TEXT_TYPE);
1885            } else {
1886                String text = nativeCursorText();
1887                if (text != null) {
1888                    if (text.startsWith(SCHEME_TEL)) {
1889                        result.setType(HitTestResult.PHONE_TYPE);
1890                        result.setExtra(text.substring(SCHEME_TEL.length()));
1891                    } else if (text.startsWith(SCHEME_MAILTO)) {
1892                        result.setType(HitTestResult.EMAIL_TYPE);
1893                        result.setExtra(text.substring(SCHEME_MAILTO.length()));
1894                    } else if (text.startsWith(SCHEME_GEO)) {
1895                        result.setType(HitTestResult.GEO_TYPE);
1896                        result.setExtra(URLDecoder.decode(text
1897                                .substring(SCHEME_GEO.length())));
1898                    } else if (nativeCursorIsAnchor()) {
1899                        result.setType(HitTestResult.SRC_ANCHOR_TYPE);
1900                        result.setExtra(text);
1901                    }
1902                }
1903            }
1904        }
1905        int type = result.getType();
1906        if (type == HitTestResult.UNKNOWN_TYPE
1907                || type == HitTestResult.SRC_ANCHOR_TYPE) {
1908            // Now check to see if it is an image.
1909            int contentX = viewToContentX((int) mLastTouchX + mScrollX);
1910            int contentY = viewToContentY((int) mLastTouchY + mScrollY);
1911            String text = nativeImageURI(contentX, contentY);
1912            if (text != null) {
1913                result.setType(type == HitTestResult.UNKNOWN_TYPE ?
1914                        HitTestResult.IMAGE_TYPE :
1915                        HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1916                result.setExtra(text);
1917            }
1918        }
1919        return result;
1920    }
1921
1922    // Called by JNI when the DOM has changed the focus.  Clear the focus so
1923    // that new keys will go to the newly focused field
1924    private void domChangedFocus() {
1925        if (inEditingMode()) {
1926            mPrivateHandler.obtainMessage(DOM_FOCUS_CHANGED).sendToTarget();
1927        }
1928    }
1929    /**
1930     * Request the href of an anchor element due to getFocusNodePath returning
1931     * "href." If hrefMsg is null, this method returns immediately and does not
1932     * dispatch hrefMsg to its target.
1933     *
1934     * @param hrefMsg This message will be dispatched with the result of the
1935     *            request as the data member with "url" as key. The result can
1936     *            be null.
1937     */
1938    // FIXME: API change required to change the name of this function.  We now
1939    // look at the cursor node, and not the focus node.  Also, what is
1940    // getFocusNodePath?
1941    public void requestFocusNodeHref(Message hrefMsg) {
1942        if (hrefMsg == null || mNativeClass == 0) {
1943            return;
1944        }
1945        if (nativeCursorIsAnchor()) {
1946            mWebViewCore.sendMessage(EventHub.REQUEST_CURSOR_HREF,
1947                    nativeCursorFramePointer(), nativeCursorNodePointer(),
1948                    hrefMsg);
1949        }
1950    }
1951
1952    /**
1953     * Request the url of the image last touched by the user. msg will be sent
1954     * to its target with a String representing the url as its object.
1955     *
1956     * @param msg This message will be dispatched with the result of the request
1957     *            as the data member with "url" as key. The result can be null.
1958     */
1959    public void requestImageRef(Message msg) {
1960        if (0 == mNativeClass) return; // client isn't initialized
1961        int contentX = viewToContentX((int) mLastTouchX + mScrollX);
1962        int contentY = viewToContentY((int) mLastTouchY + mScrollY);
1963        String ref = nativeImageURI(contentX, contentY);
1964        Bundle data = msg.getData();
1965        data.putString("url", ref);
1966        msg.setData(data);
1967        msg.sendToTarget();
1968    }
1969
1970    static int pinLoc(int x, int viewMax, int docMax) {
1971//        Log.d(LOGTAG, "-- pinLoc " + x + " " + viewMax + " " + docMax);
1972        if (docMax < viewMax) {   // the doc has room on the sides for "blank"
1973            // pin the short document to the top/left of the screen
1974            x = 0;
1975//            Log.d(LOGTAG, "--- center " + x);
1976        } else if (x < 0) {
1977            x = 0;
1978//            Log.d(LOGTAG, "--- zero");
1979        } else if (x + viewMax > docMax) {
1980            x = docMax - viewMax;
1981//            Log.d(LOGTAG, "--- pin " + x);
1982        }
1983        return x;
1984    }
1985
1986    // Expects x in view coordinates
1987    int pinLocX(int x) {
1988        return pinLoc(x, getViewWidth(), computeHorizontalScrollRange());
1989    }
1990
1991    // Expects y in view coordinates
1992    int pinLocY(int y) {
1993        return pinLoc(y, getViewHeightWithTitle(),
1994                      computeVerticalScrollRange() + getTitleHeight());
1995    }
1996
1997    /**
1998     * A title bar which is embedded in this WebView, and scrolls along with it
1999     * vertically, but not horizontally.
2000     */
2001    private View mTitleBar;
2002
2003    /**
2004     * Since we draw the title bar ourselves, we removed the shadow from the
2005     * browser's activity.  We do want a shadow at the bottom of the title bar,
2006     * or at the top of the screen if the title bar is not visible.  This
2007     * drawable serves that purpose.
2008     */
2009    private Drawable mTitleShadow;
2010
2011    /**
2012     * Add or remove a title bar to be embedded into the WebView, and scroll
2013     * along with it vertically, while remaining in view horizontally. Pass
2014     * null to remove the title bar from the WebView, and return to drawing
2015     * the WebView normally without translating to account for the title bar.
2016     * @hide
2017     */
2018    public void setEmbeddedTitleBar(View v) {
2019        if (mTitleBar == v) return;
2020        if (mTitleBar != null) {
2021            removeView(mTitleBar);
2022        }
2023        if (null != v) {
2024            addView(v, new AbsoluteLayout.LayoutParams(
2025                    ViewGroup.LayoutParams.MATCH_PARENT,
2026                    ViewGroup.LayoutParams.WRAP_CONTENT, 0, 0));
2027            if (mTitleShadow == null) {
2028                mTitleShadow = (Drawable) mContext.getResources().getDrawable(
2029                        com.android.internal.R.drawable.title_bar_shadow);
2030            }
2031        }
2032        mTitleBar = v;
2033    }
2034
2035    /**
2036     * Given a distance in view space, convert it to content space. Note: this
2037     * does not reflect translation, just scaling, so this should not be called
2038     * with coordinates, but should be called for dimensions like width or
2039     * height.
2040     */
2041    private int viewToContentDimension(int d) {
2042        return Math.round(d * mZoomManager.getInvScale());
2043    }
2044
2045    /**
2046     * Given an x coordinate in view space, convert it to content space.  Also
2047     * may be used for absolute heights (such as for the WebTextView's
2048     * textSize, which is unaffected by the height of the title bar).
2049     */
2050    /*package*/ int viewToContentX(int x) {
2051        return viewToContentDimension(x);
2052    }
2053
2054    /**
2055     * Given a y coordinate in view space, convert it to content space.
2056     * Takes into account the height of the title bar if there is one
2057     * embedded into the WebView.
2058     */
2059    /*package*/ int viewToContentY(int y) {
2060        return viewToContentDimension(y - getTitleHeight());
2061    }
2062
2063    /**
2064     * Given a x coordinate in view space, convert it to content space.
2065     * Returns the result as a float.
2066     */
2067    private float viewToContentXf(int x) {
2068        return x * mZoomManager.getInvScale();
2069    }
2070
2071    /**
2072     * Given a y coordinate in view space, convert it to content space.
2073     * Takes into account the height of the title bar if there is one
2074     * embedded into the WebView. Returns the result as a float.
2075     */
2076    private float viewToContentYf(int y) {
2077        return (y - getTitleHeight()) * mZoomManager.getInvScale();
2078    }
2079
2080    /**
2081     * Given a distance in content space, convert it to view space. Note: this
2082     * does not reflect translation, just scaling, so this should not be called
2083     * with coordinates, but should be called for dimensions like width or
2084     * height.
2085     */
2086    /*package*/ int contentToViewDimension(int d) {
2087        return Math.round(d * mZoomManager.getScale());
2088    }
2089
2090    /**
2091     * Given an x coordinate in content space, convert it to view
2092     * space.
2093     */
2094    /*package*/ int contentToViewX(int x) {
2095        return contentToViewDimension(x);
2096    }
2097
2098    /**
2099     * Given a y coordinate in content space, convert it to view
2100     * space.  Takes into account the height of the title bar.
2101     */
2102    /*package*/ int contentToViewY(int y) {
2103        return contentToViewDimension(y) + getTitleHeight();
2104    }
2105
2106    private Rect contentToViewRect(Rect x) {
2107        return new Rect(contentToViewX(x.left), contentToViewY(x.top),
2108                        contentToViewX(x.right), contentToViewY(x.bottom));
2109    }
2110
2111    /*  To invalidate a rectangle in content coordinates, we need to transform
2112        the rect into view coordinates, so we can then call invalidate(...).
2113
2114        Normally, we would just call contentToView[XY](...), which eventually
2115        calls Math.round(coordinate * mActualScale). However, for invalidates,
2116        we need to account for the slop that occurs with antialiasing. To
2117        address that, we are a little more liberal in the size of the rect that
2118        we invalidate.
2119
2120        This liberal calculation calls floor() for the top/left, and ceil() for
2121        the bottom/right coordinates. This catches the possible extra pixels of
2122        antialiasing that we might have missed with just round().
2123     */
2124
2125    // Called by JNI to invalidate the View, given rectangle coordinates in
2126    // content space
2127    private void viewInvalidate(int l, int t, int r, int b) {
2128        final float scale = mZoomManager.getScale();
2129        final int dy = getTitleHeight();
2130        invalidate((int)Math.floor(l * scale),
2131                   (int)Math.floor(t * scale) + dy,
2132                   (int)Math.ceil(r * scale),
2133                   (int)Math.ceil(b * scale) + dy);
2134    }
2135
2136    // Called by JNI to invalidate the View after a delay, given rectangle
2137    // coordinates in content space
2138    private void viewInvalidateDelayed(long delay, int l, int t, int r, int b) {
2139        final float scale = mZoomManager.getScale();
2140        final int dy = getTitleHeight();
2141        postInvalidateDelayed(delay,
2142                              (int)Math.floor(l * scale),
2143                              (int)Math.floor(t * scale) + dy,
2144                              (int)Math.ceil(r * scale),
2145                              (int)Math.ceil(b * scale) + dy);
2146    }
2147
2148    private void invalidateContentRect(Rect r) {
2149        viewInvalidate(r.left, r.top, r.right, r.bottom);
2150    }
2151
2152    // stop the scroll animation, and don't let a subsequent fling add
2153    // to the existing velocity
2154    private void abortAnimation() {
2155        mScroller.abortAnimation();
2156        mLastVelocity = 0;
2157    }
2158
2159    /* call from webcoreview.draw(), so we're still executing in the UI thread
2160    */
2161    private void recordNewContentSize(int w, int h, boolean updateLayout) {
2162
2163        // premature data from webkit, ignore
2164        if ((w | h) == 0) {
2165            return;
2166        }
2167
2168        // don't abort a scroll animation if we didn't change anything
2169        if (mContentWidth != w || mContentHeight != h) {
2170            // record new dimensions
2171            mContentWidth = w;
2172            mContentHeight = h;
2173            // If history Picture is drawn, don't update scroll. They will be
2174            // updated when we get out of that mode.
2175            if (!mDrawHistory) {
2176                // repin our scroll, taking into account the new content size
2177                updateScrollCoordinates(pinLocX(mScrollX), pinLocY(mScrollY));
2178                if (!mScroller.isFinished()) {
2179                    // We are in the middle of a scroll.  Repin the final scroll
2180                    // position.
2181                    mScroller.setFinalX(pinLocX(mScroller.getFinalX()));
2182                    mScroller.setFinalY(pinLocY(mScroller.getFinalY()));
2183                }
2184            }
2185        }
2186        contentSizeChanged(updateLayout);
2187    }
2188
2189    // Used to avoid sending many visible rect messages.
2190    private Rect mLastVisibleRectSent;
2191    private Rect mLastGlobalRect;
2192
2193    Rect sendOurVisibleRect() {
2194        if (mZoomManager.isPreventingWebkitUpdates()) return mLastVisibleRectSent;
2195
2196        Rect rect = new Rect();
2197        calcOurContentVisibleRect(rect);
2198        // Rect.equals() checks for null input.
2199        if (!rect.equals(mLastVisibleRectSent)) {
2200            Point pos = new Point(rect.left, rect.top);
2201            mWebViewCore.sendMessage(EventHub.SET_SCROLL_OFFSET,
2202                    nativeMoveGeneration(), 0, pos);
2203            mLastVisibleRectSent = rect;
2204        }
2205        Rect globalRect = new Rect();
2206        if (getGlobalVisibleRect(globalRect)
2207                && !globalRect.equals(mLastGlobalRect)) {
2208            if (DebugFlags.WEB_VIEW) {
2209                Log.v(LOGTAG, "sendOurVisibleRect=(" + globalRect.left + ","
2210                        + globalRect.top + ",r=" + globalRect.right + ",b="
2211                        + globalRect.bottom);
2212            }
2213            // TODO: the global offset is only used by windowRect()
2214            // in ChromeClientAndroid ; other clients such as touch
2215            // and mouse events could return view + screen relative points.
2216            mWebViewCore.sendMessage(EventHub.SET_GLOBAL_BOUNDS, globalRect);
2217            mLastGlobalRect = globalRect;
2218        }
2219        return rect;
2220    }
2221
2222    // Sets r to be the visible rectangle of our webview in view coordinates
2223    private void calcOurVisibleRect(Rect r) {
2224        Point p = new Point();
2225        getGlobalVisibleRect(r, p);
2226        r.offset(-p.x, -p.y);
2227    }
2228
2229    // Sets r to be our visible rectangle in content coordinates
2230    private void calcOurContentVisibleRect(Rect r) {
2231        calcOurVisibleRect(r);
2232        // pin the rect to the bounds of the content
2233        r.left = Math.max(viewToContentX(r.left), 0);
2234        // viewToContentY will remove the total height of the title bar.  Add
2235        // the visible height back in to account for the fact that if the title
2236        // bar is partially visible, the part of the visible rect which is
2237        // displaying our content is displaced by that amount.
2238        r.top = Math.max(viewToContentY(r.top + getVisibleTitleHeight()), 0);
2239        r.right = Math.min(viewToContentX(r.right), mContentWidth);
2240        r.bottom = Math.min(viewToContentY(r.bottom), mContentHeight);
2241    }
2242
2243    // Sets r to be our visible rectangle in content coordinates. We use this
2244    // method on the native side to compute the position of the fixed layers.
2245    // Uses floating coordinates (necessary to correctly place elements when
2246    // the scale factor is not 1)
2247    private void calcOurContentVisibleRectF(RectF r) {
2248        Rect ri = new Rect(0,0,0,0);
2249        calcOurVisibleRect(ri);
2250        // pin the rect to the bounds of the content
2251        r.left = Math.max(viewToContentXf(ri.left), 0.0f);
2252        // viewToContentY will remove the total height of the title bar.  Add
2253        // the visible height back in to account for the fact that if the title
2254        // bar is partially visible, the part of the visible rect which is
2255        // displaying our content is displaced by that amount.
2256        r.top = Math.max(viewToContentYf(ri.top + getVisibleTitleHeight()), 0.0f);
2257        r.right = Math.min(viewToContentXf(ri.right), (float)mContentWidth);
2258        r.bottom = Math.min(viewToContentYf(ri.bottom), (float)mContentHeight);
2259    }
2260
2261    static class ViewSizeData {
2262        int mWidth;
2263        int mHeight;
2264        int mTextWrapWidth;
2265        int mAnchorX;
2266        int mAnchorY;
2267        float mScale;
2268        boolean mIgnoreHeight;
2269    }
2270
2271    /**
2272     * Compute unzoomed width and height, and if they differ from the last
2273     * values we sent, send them to webkit (to be used as new viewport)
2274     *
2275     * @param force ensures that the message is sent to webkit even if the width
2276     * or height has not changed since the last message
2277     *
2278     * @return true if new values were sent
2279     */
2280    boolean sendViewSizeZoom(boolean force) {
2281        if (mZoomManager.isPreventingWebkitUpdates()) return false;
2282
2283        int viewWidth = getViewWidth();
2284        int newWidth = Math.round(viewWidth * mZoomManager.getInvScale());
2285        int newHeight = Math.round(getViewHeight() * mZoomManager.getInvScale());
2286        /*
2287         * Because the native side may have already done a layout before the
2288         * View system was able to measure us, we have to send a height of 0 to
2289         * remove excess whitespace when we grow our width. This will trigger a
2290         * layout and a change in content size. This content size change will
2291         * mean that contentSizeChanged will either call this method directly or
2292         * indirectly from onSizeChanged.
2293         */
2294        if (newWidth > mLastWidthSent && mWrapContent) {
2295            newHeight = 0;
2296        }
2297        // Avoid sending another message if the dimensions have not changed.
2298        if (newWidth != mLastWidthSent || newHeight != mLastHeightSent || force) {
2299            ViewSizeData data = new ViewSizeData();
2300            data.mWidth = newWidth;
2301            data.mHeight = newHeight;
2302            data.mTextWrapWidth = Math.round(viewWidth / mZoomManager.getTextWrapScale());
2303            data.mScale = mZoomManager.getScale();
2304            data.mIgnoreHeight = mZoomManager.isFixedLengthAnimationInProgress()
2305                    && !mHeightCanMeasure;
2306            data.mAnchorX = mZoomManager.getDocumentAnchorX();
2307            data.mAnchorY = mZoomManager.getDocumentAnchorY();
2308            mWebViewCore.sendMessage(EventHub.VIEW_SIZE_CHANGED, data);
2309            mLastWidthSent = newWidth;
2310            mLastHeightSent = newHeight;
2311            mZoomManager.clearDocumentAnchor();
2312            return true;
2313        }
2314        return false;
2315    }
2316
2317    @Override
2318    protected int computeHorizontalScrollRange() {
2319        if (mDrawHistory) {
2320            return mHistoryWidth;
2321        } else if (mHorizontalScrollBarMode == SCROLLBAR_ALWAYSOFF
2322                && !mZoomManager.canZoomOut()) {
2323            // only honor the scrollbar mode when it is at minimum zoom level
2324            return computeHorizontalScrollExtent();
2325        } else {
2326            // to avoid rounding error caused unnecessary scrollbar, use floor
2327            return (int) Math.floor(mContentWidth * mZoomManager.getScale());
2328        }
2329    }
2330
2331    @Override
2332    protected int computeVerticalScrollRange() {
2333        if (mDrawHistory) {
2334            return mHistoryHeight;
2335        } else if (mVerticalScrollBarMode == SCROLLBAR_ALWAYSOFF
2336                && !mZoomManager.canZoomOut()) {
2337            // only honor the scrollbar mode when it is at minimum zoom level
2338            return computeVerticalScrollExtent();
2339        } else {
2340            // to avoid rounding error caused unnecessary scrollbar, use floor
2341            return (int) Math.floor(mContentHeight * mZoomManager.getScale());
2342        }
2343    }
2344
2345    @Override
2346    protected int computeVerticalScrollOffset() {
2347        return Math.max(mScrollY - getTitleHeight(), 0);
2348    }
2349
2350    @Override
2351    protected int computeVerticalScrollExtent() {
2352        return getViewHeight();
2353    }
2354
2355    /** @hide */
2356    @Override
2357    protected void onDrawVerticalScrollBar(Canvas canvas,
2358                                           Drawable scrollBar,
2359                                           int l, int t, int r, int b) {
2360        scrollBar.setBounds(l, t + getVisibleTitleHeight(), r, b);
2361        scrollBar.draw(canvas);
2362    }
2363
2364    /**
2365     * Get the url for the current page. This is not always the same as the url
2366     * passed to WebViewClient.onPageStarted because although the load for
2367     * that url has begun, the current page may not have changed.
2368     * @return The url for the current page.
2369     */
2370    public String getUrl() {
2371        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
2372        return h != null ? h.getUrl() : null;
2373    }
2374
2375    /**
2376     * Get the original url for the current page. This is not always the same
2377     * as the url passed to WebViewClient.onPageStarted because although the
2378     * load for that url has begun, the current page may not have changed.
2379     * Also, there may have been redirects resulting in a different url to that
2380     * originally requested.
2381     * @return The url that was originally requested for the current page.
2382     */
2383    public String getOriginalUrl() {
2384        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
2385        return h != null ? h.getOriginalUrl() : null;
2386    }
2387
2388    /**
2389     * Get the title for the current page. This is the title of the current page
2390     * until WebViewClient.onReceivedTitle is called.
2391     * @return The title for the current page.
2392     */
2393    public String getTitle() {
2394        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
2395        return h != null ? h.getTitle() : null;
2396    }
2397
2398    /**
2399     * Get the favicon for the current page. This is the favicon of the current
2400     * page until WebViewClient.onReceivedIcon is called.
2401     * @return The favicon for the current page.
2402     */
2403    public Bitmap getFavicon() {
2404        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
2405        return h != null ? h.getFavicon() : null;
2406    }
2407
2408    /**
2409     * Get the touch icon url for the apple-touch-icon <link> element, or
2410     * a URL on this site's server pointing to the standard location of a
2411     * touch icon.
2412     * @hide
2413     */
2414    public String getTouchIconUrl() {
2415        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
2416        return h != null ? h.getTouchIconUrl() : null;
2417    }
2418
2419    /**
2420     * Get the progress for the current page.
2421     * @return The progress for the current page between 0 and 100.
2422     */
2423    public int getProgress() {
2424        return mCallbackProxy.getProgress();
2425    }
2426
2427    /**
2428     * @return the height of the HTML content.
2429     */
2430    public int getContentHeight() {
2431        return mContentHeight;
2432    }
2433
2434    /**
2435     * @return the width of the HTML content.
2436     * @hide
2437     */
2438    public int getContentWidth() {
2439        return mContentWidth;
2440    }
2441
2442    /**
2443     * Pause all layout, parsing, and javascript timers for all webviews. This
2444     * is a global requests, not restricted to just this webview. This can be
2445     * useful if the application has been paused.
2446     */
2447    public void pauseTimers() {
2448        mWebViewCore.sendMessage(EventHub.PAUSE_TIMERS);
2449    }
2450
2451    /**
2452     * Resume all layout, parsing, and javascript timers for all webviews.
2453     * This will resume dispatching all timers.
2454     */
2455    public void resumeTimers() {
2456        mWebViewCore.sendMessage(EventHub.RESUME_TIMERS);
2457    }
2458
2459    /**
2460     * Call this to pause any extra processing associated with this view and
2461     * its associated DOM/plugins/javascript/etc. For example, if the view is
2462     * taken offscreen, this could be called to reduce unnecessary CPU and/or
2463     * network traffic. When the view is again "active", call onResume().
2464     *
2465     * Note that this differs from pauseTimers(), which affects all views/DOMs
2466     * @hide
2467     */
2468    public void onPause() {
2469        if (!mIsPaused) {
2470            mIsPaused = true;
2471            mWebViewCore.sendMessage(EventHub.ON_PAUSE);
2472        }
2473    }
2474
2475    /**
2476     * Call this to balanace a previous call to onPause()
2477     * @hide
2478     */
2479    public void onResume() {
2480        if (mIsPaused) {
2481            mIsPaused = false;
2482            mWebViewCore.sendMessage(EventHub.ON_RESUME);
2483        }
2484    }
2485
2486    /**
2487     * Returns true if the view is paused, meaning onPause() was called. Calling
2488     * onResume() sets the paused state back to false.
2489     * @hide
2490     */
2491    public boolean isPaused() {
2492        return mIsPaused;
2493    }
2494
2495    /**
2496     * Call this to inform the view that memory is low so that it can
2497     * free any available memory.
2498     */
2499    public void freeMemory() {
2500        mWebViewCore.sendMessage(EventHub.FREE_MEMORY);
2501    }
2502
2503    /**
2504     * Clear the resource cache. Note that the cache is per-application, so
2505     * this will clear the cache for all WebViews used.
2506     *
2507     * @param includeDiskFiles If false, only the RAM cache is cleared.
2508     */
2509    public void clearCache(boolean includeDiskFiles) {
2510        // Note: this really needs to be a static method as it clears cache for all
2511        // WebView. But we need mWebViewCore to send message to WebCore thread, so
2512        // we can't make this static.
2513        mWebViewCore.sendMessage(EventHub.CLEAR_CACHE,
2514                includeDiskFiles ? 1 : 0, 0);
2515    }
2516
2517    /**
2518     * Make sure that clearing the form data removes the adapter from the
2519     * currently focused textfield if there is one.
2520     */
2521    public void clearFormData() {
2522        if (inEditingMode()) {
2523            AutoCompleteAdapter adapter = null;
2524            mWebTextView.setAdapterCustom(adapter);
2525        }
2526    }
2527
2528    /**
2529     * Tell the WebView to clear its internal back/forward list.
2530     */
2531    public void clearHistory() {
2532        mCallbackProxy.getBackForwardList().setClearPending();
2533        mWebViewCore.sendMessage(EventHub.CLEAR_HISTORY);
2534    }
2535
2536    /**
2537     * Clear the SSL preferences table stored in response to proceeding with SSL
2538     * certificate errors.
2539     */
2540    public void clearSslPreferences() {
2541        mWebViewCore.sendMessage(EventHub.CLEAR_SSL_PREF_TABLE);
2542    }
2543
2544    /**
2545     * Return the WebBackForwardList for this WebView. This contains the
2546     * back/forward list for use in querying each item in the history stack.
2547     * This is a copy of the private WebBackForwardList so it contains only a
2548     * snapshot of the current state. Multiple calls to this method may return
2549     * different objects. The object returned from this method will not be
2550     * updated to reflect any new state.
2551     */
2552    public WebBackForwardList copyBackForwardList() {
2553        return mCallbackProxy.getBackForwardList().clone();
2554    }
2555
2556    /*
2557     * Highlight and scroll to the next occurance of String in findAll.
2558     * Wraps the page infinitely, and scrolls.  Must be called after
2559     * calling findAll.
2560     *
2561     * @param forward Direction to search.
2562     */
2563    public void findNext(boolean forward) {
2564        if (0 == mNativeClass) return; // client isn't initialized
2565        nativeFindNext(forward);
2566    }
2567
2568    /*
2569     * Find all instances of find on the page and highlight them.
2570     * @param find  String to find.
2571     * @return int  The number of occurances of the String "find"
2572     *              that were found.
2573     */
2574    public int findAll(String find) {
2575        if (0 == mNativeClass) return 0; // client isn't initialized
2576        int result = find != null ? nativeFindAll(find.toLowerCase(),
2577                find.toUpperCase()) : 0;
2578        invalidate();
2579        mLastFind = find;
2580        return result;
2581    }
2582
2583    /**
2584     * @hide
2585     */
2586    public void setFindIsUp(boolean isUp) {
2587        mFindIsUp = isUp;
2588        if (0 == mNativeClass) return; // client isn't initialized
2589        nativeSetFindIsUp(isUp);
2590    }
2591
2592    /**
2593     * @hide
2594     */
2595    public int findIndex() {
2596        if (0 == mNativeClass) return -1;
2597        return nativeFindIndex();
2598    }
2599
2600    // Used to know whether the find dialog is open.  Affects whether
2601    // or not we draw the highlights for matches.
2602    private boolean mFindIsUp;
2603
2604    // Keep track of the last string sent, so we can search again after an
2605    // orientation change or the dismissal of the soft keyboard.
2606    private String mLastFind;
2607
2608    /**
2609     * Return the first substring consisting of the address of a physical
2610     * location. Currently, only addresses in the United States are detected,
2611     * and consist of:
2612     * - a house number
2613     * - a street name
2614     * - a street type (Road, Circle, etc), either spelled out or abbreviated
2615     * - a city name
2616     * - a state or territory, either spelled out or two-letter abbr.
2617     * - an optional 5 digit or 9 digit zip code.
2618     *
2619     * All names must be correctly capitalized, and the zip code, if present,
2620     * must be valid for the state. The street type must be a standard USPS
2621     * spelling or abbreviation. The state or territory must also be spelled
2622     * or abbreviated using USPS standards. The house number may not exceed
2623     * five digits.
2624     * @param addr The string to search for addresses.
2625     *
2626     * @return the address, or if no address is found, return null.
2627     */
2628    public static String findAddress(String addr) {
2629        return findAddress(addr, false);
2630    }
2631
2632    /**
2633     * @hide
2634     * Return the first substring consisting of the address of a physical
2635     * location. Currently, only addresses in the United States are detected,
2636     * and consist of:
2637     * - a house number
2638     * - a street name
2639     * - a street type (Road, Circle, etc), either spelled out or abbreviated
2640     * - a city name
2641     * - a state or territory, either spelled out or two-letter abbr.
2642     * - an optional 5 digit or 9 digit zip code.
2643     *
2644     * Names are optionally capitalized, and the zip code, if present,
2645     * must be valid for the state. The street type must be a standard USPS
2646     * spelling or abbreviation. The state or territory must also be spelled
2647     * or abbreviated using USPS standards. The house number may not exceed
2648     * five digits.
2649     * @param addr The string to search for addresses.
2650     * @param caseInsensitive addr Set to true to make search ignore case.
2651     *
2652     * @return the address, or if no address is found, return null.
2653     */
2654    public static String findAddress(String addr, boolean caseInsensitive) {
2655        return WebViewCore.nativeFindAddress(addr, caseInsensitive);
2656    }
2657
2658    /*
2659     * Clear the highlighting surrounding text matches created by findAll.
2660     */
2661    public void clearMatches() {
2662        mLastFind = "";
2663        if (mNativeClass == 0)
2664            return;
2665        nativeSetFindIsEmpty();
2666        invalidate();
2667    }
2668
2669    /**
2670     * @hide
2671     */
2672    public void notifyFindDialogDismissed() {
2673        if (mWebViewCore == null) {
2674            return;
2675        }
2676        clearMatches();
2677        setFindIsUp(false);
2678        // Now that the dialog has been removed, ensure that we scroll to a
2679        // location that is not beyond the end of the page.
2680        pinScrollTo(mScrollX, mScrollY, false, 0);
2681        invalidate();
2682    }
2683
2684    /**
2685     * Query the document to see if it contains any image references. The
2686     * message object will be dispatched with arg1 being set to 1 if images
2687     * were found and 0 if the document does not reference any images.
2688     * @param response The message that will be dispatched with the result.
2689     */
2690    public void documentHasImages(Message response) {
2691        if (response == null) {
2692            return;
2693        }
2694        mWebViewCore.sendMessage(EventHub.DOC_HAS_IMAGES, response);
2695    }
2696
2697    /**
2698     * Request the scroller to abort any ongoing animation
2699     *
2700     * @hide
2701     */
2702    public void stopScroll() {
2703        mScroller.forceFinished(true);
2704        mLastVelocity = 0;
2705    }
2706
2707    @Override
2708    public void computeScroll() {
2709        if (mScroller.computeScrollOffset()) {
2710            int oldX = mScrollX;
2711            int oldY = mScrollY;
2712            mScrollX = mScroller.getCurrX();
2713            mScrollY = mScroller.getCurrY();
2714            postInvalidate();  // So we draw again
2715            if (oldX != mScrollX || oldY != mScrollY) {
2716                onScrollChanged(mScrollX, mScrollY, oldX, oldY);
2717            } else {
2718                abortAnimation();
2719                mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY);
2720                WebViewCore.resumePriority();
2721                WebViewCore.resumeUpdatePicture(mWebViewCore);
2722            }
2723        } else {
2724            super.computeScroll();
2725        }
2726    }
2727
2728    private static int computeDuration(int dx, int dy) {
2729        int distance = Math.max(Math.abs(dx), Math.abs(dy));
2730        int duration = distance * 1000 / STD_SPEED;
2731        return Math.min(duration, MAX_DURATION);
2732    }
2733
2734    // helper to pin the scrollBy parameters (already in view coordinates)
2735    // returns true if the scroll was changed
2736    private boolean pinScrollBy(int dx, int dy, boolean animate, int animationDuration) {
2737        return pinScrollTo(mScrollX + dx, mScrollY + dy, animate, animationDuration);
2738    }
2739    // helper to pin the scrollTo parameters (already in view coordinates)
2740    // returns true if the scroll was changed
2741    private boolean pinScrollTo(int x, int y, boolean animate, int animationDuration) {
2742        x = pinLocX(x);
2743        y = pinLocY(y);
2744        int dx = x - mScrollX;
2745        int dy = y - mScrollY;
2746
2747        if ((dx | dy) == 0) {
2748            return false;
2749        }
2750        if (animate) {
2751            //        Log.d(LOGTAG, "startScroll: " + dx + " " + dy);
2752            mScroller.startScroll(mScrollX, mScrollY, dx, dy,
2753                    animationDuration > 0 ? animationDuration : computeDuration(dx, dy));
2754            awakenScrollBars(mScroller.getDuration());
2755            invalidate();
2756        } else {
2757            abortAnimation(); // just in case
2758            scrollTo(x, y);
2759        }
2760        return true;
2761    }
2762
2763    // Scale from content to view coordinates, and pin.
2764    // Also called by jni webview.cpp
2765    private boolean setContentScrollBy(int cx, int cy, boolean animate) {
2766        if (mDrawHistory) {
2767            // disallow WebView to change the scroll position as History Picture
2768            // is used in the view system.
2769            // TODO: as we switchOutDrawHistory when trackball or navigation
2770            // keys are hit, this should be safe. Right?
2771            return false;
2772        }
2773        cx = contentToViewDimension(cx);
2774        cy = contentToViewDimension(cy);
2775        if (mHeightCanMeasure) {
2776            // move our visible rect according to scroll request
2777            if (cy != 0) {
2778                Rect tempRect = new Rect();
2779                calcOurVisibleRect(tempRect);
2780                tempRect.offset(cx, cy);
2781                requestRectangleOnScreen(tempRect);
2782            }
2783            // FIXME: We scroll horizontally no matter what because currently
2784            // ScrollView and ListView will not scroll horizontally.
2785            // FIXME: Why do we only scroll horizontally if there is no
2786            // vertical scroll?
2787//                Log.d(LOGTAG, "setContentScrollBy cy=" + cy);
2788            return cy == 0 && cx != 0 && pinScrollBy(cx, 0, animate, 0);
2789        } else {
2790            return pinScrollBy(cx, cy, animate, 0);
2791        }
2792    }
2793
2794    /**
2795     * Called by CallbackProxy when the page finishes loading.
2796     * @param url The URL of the page which has finished loading.
2797     */
2798    /* package */ void onPageFinished(String url) {
2799        if (mPageThatNeedsToSlideTitleBarOffScreen != null) {
2800            // If the user is now on a different page, or has scrolled the page
2801            // past the point where the title bar is offscreen, ignore the
2802            // scroll request.
2803            if (mPageThatNeedsToSlideTitleBarOffScreen.equals(url)
2804                    && mScrollX == 0 && mScrollY == 0) {
2805                pinScrollTo(0, mYDistanceToSlideTitleOffScreen, true,
2806                        SLIDE_TITLE_DURATION);
2807            }
2808            mPageThatNeedsToSlideTitleBarOffScreen = null;
2809        }
2810
2811        injectAccessibilityForUrl(url);
2812    }
2813
2814    /**
2815     * This method injects accessibility in the loaded document if accessibility
2816     * is enabled. If JavaScript is enabled we try to inject a URL specific script.
2817     * If no URL specific script is found or JavaScript is disabled we fallback to
2818     * the default {@link AccessibilityInjector} implementation.
2819     *
2820     * @param url The URL loaded by this {@link WebView}.
2821     */
2822    private void injectAccessibilityForUrl(String url) {
2823        if (AccessibilityManager.getInstance(mContext).isEnabled()) {
2824            if (getSettings().getJavaScriptEnabled()) {
2825                loadUrl(ACCESSIBILITY_SCRIPT_CHOOSER_JAVASCRIPT);
2826            } else if (mAccessibilityInjector == null) {
2827                mAccessibilityInjector = new AccessibilityInjector(this);
2828            }
2829        } else {
2830            // it is possible that accessibility was turned off between reloads
2831            mAccessibilityInjector = null;
2832        }
2833    }
2834
2835    /**
2836     * The URL of a page that sent a message to scroll the title bar off screen.
2837     *
2838     * Many mobile sites tell the page to scroll to (0,1) in order to scroll the
2839     * title bar off the screen.  Sometimes, the scroll position is set before
2840     * the page finishes loading.  Rather than scrolling while the page is still
2841     * loading, keep track of the URL and new scroll position so we can perform
2842     * the scroll once the page finishes loading.
2843     */
2844    private String mPageThatNeedsToSlideTitleBarOffScreen;
2845
2846    /**
2847     * The destination Y scroll position to be used when the page finishes
2848     * loading.  See mPageThatNeedsToSlideTitleBarOffScreen.
2849     */
2850    private int mYDistanceToSlideTitleOffScreen;
2851
2852    // scale from content to view coordinates, and pin
2853    // return true if pin caused the final x/y different than the request cx/cy,
2854    // and a future scroll may reach the request cx/cy after our size has
2855    // changed
2856    // return false if the view scroll to the exact position as it is requested,
2857    // where negative numbers are taken to mean 0
2858    private boolean setContentScrollTo(int cx, int cy) {
2859        if (mDrawHistory) {
2860            // disallow WebView to change the scroll position as History Picture
2861            // is used in the view system.
2862            // One known case where this is called is that WebCore tries to
2863            // restore the scroll position. As history Picture already uses the
2864            // saved scroll position, it is ok to skip this.
2865            return false;
2866        }
2867        int vx;
2868        int vy;
2869        if ((cx | cy) == 0) {
2870            // If the page is being scrolled to (0,0), do not add in the title
2871            // bar's height, and simply scroll to (0,0). (The only other work
2872            // in contentToView_ is to multiply, so this would not change 0.)
2873            vx = 0;
2874            vy = 0;
2875        } else {
2876            vx = contentToViewX(cx);
2877            vy = contentToViewY(cy);
2878        }
2879//        Log.d(LOGTAG, "content scrollTo [" + cx + " " + cy + "] view=[" +
2880//                      vx + " " + vy + "]");
2881        // Some mobile sites attempt to scroll the title bar off the page by
2882        // scrolling to (0,1).  If we are at the top left corner of the
2883        // page, assume this is an attempt to scroll off the title bar, and
2884        // animate the title bar off screen slowly enough that the user can see
2885        // it.
2886        if (cx == 0 && cy == 1 && mScrollX == 0 && mScrollY == 0
2887                && mTitleBar != null) {
2888            // FIXME: 100 should be defined somewhere as our max progress.
2889            if (getProgress() < 100) {
2890                // Wait to scroll the title bar off screen until the page has
2891                // finished loading.  Keep track of the URL and the destination
2892                // Y position
2893                mPageThatNeedsToSlideTitleBarOffScreen = getUrl();
2894                mYDistanceToSlideTitleOffScreen = vy;
2895            } else {
2896                pinScrollTo(vx, vy, true, SLIDE_TITLE_DURATION);
2897            }
2898            // Since we are animating, we have not yet reached the desired
2899            // scroll position.  Do not return true to request another attempt
2900            return false;
2901        }
2902        pinScrollTo(vx, vy, false, 0);
2903        // If the request was to scroll to a negative coordinate, treat it as if
2904        // it was a request to scroll to 0
2905        if ((mScrollX != vx && cx >= 0) || (mScrollY != vy && cy >= 0)) {
2906            return true;
2907        } else {
2908            return false;
2909        }
2910    }
2911
2912    // scale from content to view coordinates, and pin
2913    private void spawnContentScrollTo(int cx, int cy) {
2914        if (mDrawHistory) {
2915            // disallow WebView to change the scroll position as History Picture
2916            // is used in the view system.
2917            return;
2918        }
2919        int vx = contentToViewX(cx);
2920        int vy = contentToViewY(cy);
2921        pinScrollTo(vx, vy, true, 0);
2922    }
2923
2924    /**
2925     * These are from webkit, and are in content coordinate system (unzoomed)
2926     */
2927    private void contentSizeChanged(boolean updateLayout) {
2928        // suppress 0,0 since we usually see real dimensions soon after
2929        // this avoids drawing the prev content in a funny place. If we find a
2930        // way to consolidate these notifications, this check may become
2931        // obsolete
2932        if ((mContentWidth | mContentHeight) == 0) {
2933            return;
2934        }
2935
2936        if (mHeightCanMeasure) {
2937            if (getMeasuredHeight() != contentToViewDimension(mContentHeight)
2938                    || updateLayout) {
2939                requestLayout();
2940            }
2941        } else if (mWidthCanMeasure) {
2942            if (getMeasuredWidth() != contentToViewDimension(mContentWidth)
2943                    || updateLayout) {
2944                requestLayout();
2945            }
2946        } else {
2947            // If we don't request a layout, try to send our view size to the
2948            // native side to ensure that WebCore has the correct dimensions.
2949            sendViewSizeZoom(false);
2950        }
2951    }
2952
2953    /**
2954     * Set the WebViewClient that will receive various notifications and
2955     * requests. This will replace the current handler.
2956     * @param client An implementation of WebViewClient.
2957     */
2958    public void setWebViewClient(WebViewClient client) {
2959        mCallbackProxy.setWebViewClient(client);
2960    }
2961
2962    /**
2963     * Gets the WebViewClient
2964     * @return the current WebViewClient instance.
2965     *
2966     *@hide pending API council approval.
2967     */
2968    public WebViewClient getWebViewClient() {
2969        return mCallbackProxy.getWebViewClient();
2970    }
2971
2972    /**
2973     * Register the interface to be used when content can not be handled by
2974     * the rendering engine, and should be downloaded instead. This will replace
2975     * the current handler.
2976     * @param listener An implementation of DownloadListener.
2977     */
2978    public void setDownloadListener(DownloadListener listener) {
2979        mCallbackProxy.setDownloadListener(listener);
2980    }
2981
2982    /**
2983     * Set the chrome handler. This is an implementation of WebChromeClient for
2984     * use in handling Javascript dialogs, favicons, titles, and the progress.
2985     * This will replace the current handler.
2986     * @param client An implementation of WebChromeClient.
2987     */
2988    public void setWebChromeClient(WebChromeClient client) {
2989        mCallbackProxy.setWebChromeClient(client);
2990    }
2991
2992    /**
2993     * Gets the chrome handler.
2994     * @return the current WebChromeClient instance.
2995     *
2996     * @hide API council approval.
2997     */
2998    public WebChromeClient getWebChromeClient() {
2999        return mCallbackProxy.getWebChromeClient();
3000    }
3001
3002    /**
3003     * Set the back/forward list client. This is an implementation of
3004     * WebBackForwardListClient for handling new items and changes in the
3005     * history index.
3006     * @param client An implementation of WebBackForwardListClient.
3007     * {@hide}
3008     */
3009    public void setWebBackForwardListClient(WebBackForwardListClient client) {
3010        mCallbackProxy.setWebBackForwardListClient(client);
3011    }
3012
3013    /**
3014     * Gets the WebBackForwardListClient.
3015     * {@hide}
3016     */
3017    public WebBackForwardListClient getWebBackForwardListClient() {
3018        return mCallbackProxy.getWebBackForwardListClient();
3019    }
3020
3021    /**
3022     * Set the Picture listener. This is an interface used to receive
3023     * notifications of a new Picture.
3024     * @param listener An implementation of WebView.PictureListener.
3025     */
3026    public void setPictureListener(PictureListener listener) {
3027        mPictureListener = listener;
3028    }
3029
3030    /**
3031     * {@hide}
3032     */
3033    /* FIXME: Debug only! Remove for SDK! */
3034    public void externalRepresentation(Message callback) {
3035        mWebViewCore.sendMessage(EventHub.REQUEST_EXT_REPRESENTATION, callback);
3036    }
3037
3038    /**
3039     * {@hide}
3040     */
3041    /* FIXME: Debug only! Remove for SDK! */
3042    public void documentAsText(Message callback) {
3043        mWebViewCore.sendMessage(EventHub.REQUEST_DOC_AS_TEXT, callback);
3044    }
3045
3046    /**
3047     * Use this function to bind an object to Javascript so that the
3048     * methods can be accessed from Javascript.
3049     * <p><strong>IMPORTANT:</strong>
3050     * <ul>
3051     * <li> Using addJavascriptInterface() allows JavaScript to control your
3052     * application. This can be a very useful feature or a dangerous security
3053     * issue. When the HTML in the WebView is untrustworthy (for example, part
3054     * or all of the HTML is provided by some person or process), then an
3055     * attacker could inject HTML that will execute your code and possibly any
3056     * code of the attacker's choosing.<br>
3057     * Do not use addJavascriptInterface() unless all of the HTML in this
3058     * WebView was written by you.</li>
3059     * <li> The Java object that is bound runs in another thread and not in
3060     * the thread that it was constructed in.</li>
3061     * </ul></p>
3062     * @param obj The class instance to bind to Javascript
3063     * @param interfaceName The name to used to expose the class in Javascript
3064     */
3065    public void addJavascriptInterface(Object obj, String interfaceName) {
3066        WebViewCore.JSInterfaceData arg = new WebViewCore.JSInterfaceData();
3067        arg.mObject = obj;
3068        arg.mInterfaceName = interfaceName;
3069        mWebViewCore.sendMessage(EventHub.ADD_JS_INTERFACE, arg);
3070    }
3071
3072    /**
3073     * Return the WebSettings object used to control the settings for this
3074     * WebView.
3075     * @return A WebSettings object that can be used to control this WebView's
3076     *         settings.
3077     */
3078    public WebSettings getSettings() {
3079        return (mWebViewCore != null) ? mWebViewCore.getSettings() : null;
3080    }
3081
3082    /**
3083     * Use this method to inform the webview about packages that are installed
3084     * in the system. This information will be used by the
3085     * navigator.isApplicationInstalled() API.
3086     * @param packageNames is a set of package names that are known to be
3087     * installed in the system.
3088     *
3089     * @hide not a public API
3090     */
3091    public void addPackageNames(Set<String> packageNames) {
3092        mWebViewCore.sendMessage(EventHub.ADD_PACKAGE_NAMES, packageNames);
3093    }
3094
3095    /**
3096     * Use this method to inform the webview about single packages that are
3097     * installed in the system. This information will be used by the
3098     * navigator.isApplicationInstalled() API.
3099     * @param packageName is the name of a package that is known to be
3100     * installed in the system.
3101     *
3102     * @hide not a public API
3103     */
3104    public void addPackageName(String packageName) {
3105        mWebViewCore.sendMessage(EventHub.ADD_PACKAGE_NAME, packageName);
3106    }
3107
3108    /**
3109     * Use this method to inform the webview about packages that are uninstalled
3110     * in the system. This information will be used by the
3111     * navigator.isApplicationInstalled() API.
3112     * @param packageName is the name of a package that has been uninstalled in
3113     * the system.
3114     *
3115     * @hide not a public API
3116     */
3117    public void removePackageName(String packageName) {
3118        mWebViewCore.sendMessage(EventHub.REMOVE_PACKAGE_NAME, packageName);
3119    }
3120
3121   /**
3122    * Return the list of currently loaded plugins.
3123    * @return The list of currently loaded plugins.
3124    *
3125    * @deprecated This was used for Gears, which has been deprecated.
3126    */
3127    @Deprecated
3128    public static synchronized PluginList getPluginList() {
3129        return new PluginList();
3130    }
3131
3132   /**
3133    * @deprecated This was used for Gears, which has been deprecated.
3134    */
3135    @Deprecated
3136    public void refreshPlugins(boolean reloadOpenPages) { }
3137
3138    //-------------------------------------------------------------------------
3139    // Override View methods
3140    //-------------------------------------------------------------------------
3141
3142    @Override
3143    protected void finalize() throws Throwable {
3144        try {
3145            destroy();
3146        } finally {
3147            super.finalize();
3148        }
3149    }
3150
3151    @Override
3152    protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
3153        if (child == mTitleBar) {
3154            // When drawing the title bar, move it horizontally to always show
3155            // at the top of the WebView.
3156            mTitleBar.offsetLeftAndRight(mScrollX - mTitleBar.getLeft());
3157        }
3158        return super.drawChild(canvas, child, drawingTime);
3159    }
3160
3161    private void drawContent(Canvas canvas) {
3162        // Update the buttons in the picture, so when we draw the picture
3163        // to the screen, they are in the correct state.
3164        // Tell the native side if user is a) touching the screen,
3165        // b) pressing the trackball down, or c) pressing the enter key
3166        // If the cursor is on a button, we need to draw it in the pressed
3167        // state.
3168        // If mNativeClass is 0, we should not reach here, so we do not
3169        // need to check it again.
3170        nativeRecordButtons(hasFocus() && hasWindowFocus(),
3171                            mTouchMode == TOUCH_SHORTPRESS_START_MODE
3172                            || mTrackballDown || mGotCenterDown, false);
3173        drawCoreAndCursorRing(canvas, mBackgroundColor, mDrawCursorRing);
3174    }
3175
3176    @Override
3177    protected void onDraw(Canvas canvas) {
3178        // if mNativeClass is 0, the WebView has been destroyed. Do nothing.
3179        if (mNativeClass == 0) {
3180            return;
3181        }
3182
3183        // if both mContentWidth and mContentHeight are 0, it means there is no
3184        // valid Picture passed to WebView yet. This can happen when WebView
3185        // just starts. Draw the background and return.
3186        if ((mContentWidth | mContentHeight) == 0 && mHistoryPicture == null) {
3187            canvas.drawColor(mBackgroundColor);
3188            return;
3189        }
3190
3191        int saveCount = canvas.save();
3192        if (mTitleBar != null) {
3193            canvas.translate(0, (int) mTitleBar.getHeight());
3194        }
3195        if (mDragTrackerHandler == null) {
3196            drawContent(canvas);
3197        } else {
3198            if (!mDragTrackerHandler.draw(canvas)) {
3199                // sometimes the tracker doesn't draw, even though its active
3200                drawContent(canvas);
3201            }
3202            if (mDragTrackerHandler.isFinished()) {
3203                mDragTrackerHandler = null;
3204            }
3205        }
3206        canvas.restoreToCount(saveCount);
3207
3208        // Now draw the shadow.
3209        int titleH = getVisibleTitleHeight();
3210        if (mTitleBar != null && titleH == 0) {
3211            int height = (int) (5f * getContext().getResources()
3212                    .getDisplayMetrics().density);
3213            mTitleShadow.setBounds(mScrollX, mScrollY, mScrollX + getWidth(),
3214                    mScrollY + height);
3215            mTitleShadow.draw(canvas);
3216        }
3217        if (AUTO_REDRAW_HACK && mAutoRedraw) {
3218            invalidate();
3219        }
3220        if (inEditingMode()) mWebTextView.onDrawSubstitute();
3221        mWebViewCore.signalRepaintDone();
3222
3223        // paint the highlight in the end
3224        if (!mTouchHighlightRegion.isEmpty()) {
3225            if (mTouchHightlightPaint == null) {
3226                mTouchHightlightPaint = new Paint();
3227                mTouchHightlightPaint.setColor(mHightlightColor);
3228                mTouchHightlightPaint.setAntiAlias(true);
3229                mTouchHightlightPaint.setPathEffect(new CornerPathEffect(
3230                        TOUCH_HIGHLIGHT_ARC));
3231            }
3232            canvas.drawPath(mTouchHighlightRegion.getBoundaryPath(),
3233                    mTouchHightlightPaint);
3234        }
3235        if (DEBUG_TOUCH_HIGHLIGHT) {
3236            if (getSettings().getNavDump()) {
3237                if ((mTouchHighlightX | mTouchHighlightY) != 0) {
3238                    if (mTouchCrossHairColor == null) {
3239                        mTouchCrossHairColor = new Paint();
3240                        mTouchCrossHairColor.setColor(Color.RED);
3241                    }
3242                    canvas.drawLine(mTouchHighlightX - mNavSlop,
3243                            mTouchHighlightY - mNavSlop, mTouchHighlightX
3244                                    + mNavSlop + 1, mTouchHighlightY + mNavSlop
3245                                    + 1, mTouchCrossHairColor);
3246                    canvas.drawLine(mTouchHighlightX + mNavSlop + 1,
3247                            mTouchHighlightY - mNavSlop, mTouchHighlightX
3248                                    - mNavSlop,
3249                            mTouchHighlightY + mNavSlop + 1,
3250                            mTouchCrossHairColor);
3251                }
3252            }
3253        }
3254    }
3255
3256    private void removeTouchHighlight(boolean removePendingMessage) {
3257        if (removePendingMessage) {
3258            mWebViewCore.removeMessages(EventHub.GET_TOUCH_HIGHLIGHT_RECTS);
3259        }
3260        mWebViewCore.sendMessage(EventHub.REMOVE_TOUCH_HIGHLIGHT_RECTS);
3261    }
3262
3263    @Override
3264    public void setLayoutParams(ViewGroup.LayoutParams params) {
3265        if (params.height == LayoutParams.WRAP_CONTENT) {
3266            mWrapContent = true;
3267        }
3268        super.setLayoutParams(params);
3269    }
3270
3271    @Override
3272    public boolean performLongClick() {
3273        // performLongClick() is the result of a delayed message. If we switch
3274        // to windows overview, the WebView will be temporarily removed from the
3275        // view system. In that case, do nothing.
3276        if (getParent() == null) return false;
3277        if (mNativeClass != 0 && nativeCursorIsTextInput()) {
3278            // Send the click so that the textfield is in focus
3279            centerKeyPressOnTextField();
3280            rebuildWebTextView();
3281        } else {
3282            clearTextEntry();
3283        }
3284        if (inEditingMode()) {
3285            return mWebTextView.performLongClick();
3286        }
3287        /* if long click brings up a context menu, the super function
3288         * returns true and we're done. Otherwise, nothing happened when
3289         * the user clicked. */
3290        if (super.performLongClick()) {
3291            return true;
3292        }
3293        /* In the case where the application hasn't already handled the long
3294         * click action, look for a word under the  click. If one is found,
3295         * animate the text selection into view.
3296         * FIXME: no animation code yet */
3297        if (mSelectingText) return false; // long click does nothing on selection
3298        int x = viewToContentX((int) mLastTouchX + mScrollX);
3299        int y = viewToContentY((int) mLastTouchY + mScrollY);
3300        setUpSelect();
3301        if (mNativeClass != 0 && nativeWordSelection(x, y)) {
3302            nativeSetExtendSelection();
3303            getWebChromeClient().onSelectionStart(this);
3304            return true;
3305        }
3306        notifySelectDialogDismissed();
3307        return false;
3308    }
3309
3310    private boolean didUpdateTextViewBounds(boolean allowIntersect) {
3311        Rect contentBounds = nativeFocusCandidateNodeBounds();
3312        Rect vBox = contentToViewRect(contentBounds);
3313        Rect visibleRect = new Rect();
3314        calcOurVisibleRect(visibleRect);
3315        // If the textfield is on screen, place the WebTextView in
3316        // its new place, accounting for our new scroll/zoom values,
3317        // and adjust its textsize.
3318        if (allowIntersect ? Rect.intersects(visibleRect, vBox)
3319                : visibleRect.contains(vBox)) {
3320            mWebTextView.setRect(vBox.left, vBox.top, vBox.width(),
3321                    vBox.height());
3322            mWebTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
3323                    contentToViewDimension(
3324                    nativeFocusCandidateTextSize()));
3325            return true;
3326        } else {
3327            // The textfield is now off screen.  The user probably
3328            // was not zooming to see the textfield better.  Remove
3329            // the WebTextView.  If the user types a key, and the
3330            // textfield is still in focus, we will reconstruct
3331            // the WebTextView and scroll it back on screen.
3332            mWebTextView.remove();
3333            return false;
3334        }
3335    }
3336
3337    private void onZoomAnimationStart() {
3338        // If it is in password mode, turn it off so it does not draw misplaced.
3339        if (inEditingMode() && nativeFocusCandidateIsPassword()) {
3340            mWebTextView.setInPassword(false);
3341        }
3342    }
3343
3344    private void onZoomAnimationEnd() {
3345        // adjust the edit text view if needed
3346        if (inEditingMode() && didUpdateTextViewBounds(false) && nativeFocusCandidateIsPassword()) {
3347            // If it is a password field, start drawing the WebTextView once
3348            // again.
3349            mWebTextView.setInPassword(true);
3350        }
3351    }
3352
3353    void onFixedLengthZoomAnimationStart() {
3354        WebViewCore.pauseUpdatePicture(getWebViewCore());
3355        onZoomAnimationStart();
3356    }
3357
3358    void onFixedLengthZoomAnimationEnd() {
3359        WebViewCore.resumeUpdatePicture(mWebViewCore);
3360        onZoomAnimationEnd();
3361    }
3362
3363    private static final int ZOOM_BITS = Paint.FILTER_BITMAP_FLAG |
3364                                         Paint.DITHER_FLAG |
3365                                         Paint.SUBPIXEL_TEXT_FLAG;
3366    private static final int SCROLL_BITS = Paint.FILTER_BITMAP_FLAG |
3367                                           Paint.DITHER_FLAG;
3368
3369    private final DrawFilter mZoomFilter =
3370            new PaintFlagsDrawFilter(ZOOM_BITS, Paint.LINEAR_TEXT_FLAG);
3371    // If we need to trade better quality for speed, set mScrollFilter to null
3372    private final DrawFilter mScrollFilter =
3373            new PaintFlagsDrawFilter(SCROLL_BITS, 0);
3374
3375    private void drawCoreAndCursorRing(Canvas canvas, int color,
3376        boolean drawCursorRing) {
3377        if (mDrawHistory) {
3378            canvas.scale(mZoomManager.getScale(), mZoomManager.getScale());
3379            canvas.drawPicture(mHistoryPicture);
3380            return;
3381        }
3382        if (mNativeClass == 0) return;
3383
3384        boolean animateZoom = mZoomManager.isFixedLengthAnimationInProgress();
3385        boolean animateScroll = ((!mScroller.isFinished()
3386                || mVelocityTracker != null)
3387                && (mTouchMode != TOUCH_DRAG_MODE ||
3388                mHeldMotionless != MOTIONLESS_TRUE))
3389                || mDeferTouchMode == TOUCH_DRAG_MODE;
3390        if (mTouchMode == TOUCH_DRAG_MODE) {
3391            if (mHeldMotionless == MOTIONLESS_PENDING) {
3392                mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
3393                mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS);
3394                mHeldMotionless = MOTIONLESS_FALSE;
3395            }
3396            if (mHeldMotionless == MOTIONLESS_FALSE) {
3397                mPrivateHandler.sendMessageDelayed(mPrivateHandler
3398                        .obtainMessage(DRAG_HELD_MOTIONLESS), MOTIONLESS_TIME);
3399                mHeldMotionless = MOTIONLESS_PENDING;
3400            }
3401        }
3402        if (animateZoom) {
3403            mZoomManager.animateZoom(canvas);
3404        } else {
3405            canvas.scale(mZoomManager.getScale(), mZoomManager.getScale());
3406        }
3407
3408        boolean UIAnimationsRunning = false;
3409        // Currently for each draw we compute the animation values;
3410        // We may in the future decide to do that independently.
3411        if (mNativeClass != 0 && nativeEvaluateLayersAnimations()) {
3412            UIAnimationsRunning = true;
3413            // If we have unfinished (or unstarted) animations,
3414            // we ask for a repaint.
3415            invalidate();
3416        }
3417
3418        // decide which adornments to draw
3419        int extras = DRAW_EXTRAS_NONE;
3420        if (DebugFlags.WEB_VIEW) {
3421            Log.v(LOGTAG, "mFindIsUp=" + mFindIsUp
3422                    + " mSelectingText=" + mSelectingText
3423                    + " nativePageShouldHandleShiftAndArrows()="
3424                    + nativePageShouldHandleShiftAndArrows()
3425                    + " animateZoom=" + animateZoom);
3426        }
3427        if (mFindIsUp) {
3428            extras = DRAW_EXTRAS_FIND;
3429        } else if (mSelectingText) {
3430            extras = DRAW_EXTRAS_SELECTION;
3431            nativeSetSelectionPointer(mDrawSelectionPointer,
3432                    mZoomManager.getInvScale(),
3433                    mSelectX, mSelectY - getTitleHeight());
3434        } else if (drawCursorRing) {
3435            extras = DRAW_EXTRAS_CURSOR_RING;
3436        }
3437        DrawFilter df = null;
3438        if (mZoomManager.isZoomAnimating() || UIAnimationsRunning) {
3439            df = mZoomFilter;
3440        } else if (animateScroll) {
3441            df = mScrollFilter;
3442        }
3443        canvas.setDrawFilter(df);
3444        int content = nativeDraw(canvas, color, extras, true);
3445        canvas.setDrawFilter(null);
3446        if (content != 0) {
3447            mWebViewCore.sendMessage(EventHub.SPLIT_PICTURE_SET, content, 0);
3448        }
3449
3450        if (extras == DRAW_EXTRAS_CURSOR_RING) {
3451            if (mTouchMode == TOUCH_SHORTPRESS_START_MODE) {
3452                mTouchMode = TOUCH_SHORTPRESS_MODE;
3453            }
3454        }
3455        if (mFocusSizeChanged) {
3456            mFocusSizeChanged = false;
3457            // If we are zooming, this will get handled above, when the zoom
3458            // finishes.  We also do not need to do this unless the WebTextView
3459            // is showing.
3460            if (!animateZoom && inEditingMode()) {
3461                didUpdateTextViewBounds(true);
3462            }
3463        }
3464    }
3465
3466    // draw history
3467    private boolean mDrawHistory = false;
3468    private Picture mHistoryPicture = null;
3469    private int mHistoryWidth = 0;
3470    private int mHistoryHeight = 0;
3471
3472    // Only check the flag, can be called from WebCore thread
3473    boolean drawHistory() {
3474        return mDrawHistory;
3475    }
3476
3477    int getHistoryPictureWidth() {
3478        return (mHistoryPicture != null) ? mHistoryPicture.getWidth() : 0;
3479    }
3480
3481    // Should only be called in UI thread
3482    void switchOutDrawHistory() {
3483        if (null == mWebViewCore) return; // CallbackProxy may trigger this
3484        if (mDrawHistory && (getProgress() == 100 || nativeHasContent())) {
3485            mDrawHistory = false;
3486            mHistoryPicture = null;
3487            invalidate();
3488            int oldScrollX = mScrollX;
3489            int oldScrollY = mScrollY;
3490            mScrollX = pinLocX(mScrollX);
3491            mScrollY = pinLocY(mScrollY);
3492            if (oldScrollX != mScrollX || oldScrollY != mScrollY) {
3493                mUserScroll = false;
3494                mWebViewCore.sendMessage(EventHub.SYNC_SCROLL, oldScrollX,
3495                        oldScrollY);
3496                onScrollChanged(mScrollX, mScrollY, oldScrollX, oldScrollY);
3497            } else {
3498                sendOurVisibleRect();
3499            }
3500        }
3501    }
3502
3503    WebViewCore.CursorData cursorData() {
3504        WebViewCore.CursorData result = new WebViewCore.CursorData();
3505        result.mMoveGeneration = nativeMoveGeneration();
3506        result.mFrame = nativeCursorFramePointer();
3507        Point position = nativeCursorPosition();
3508        result.mX = position.x;
3509        result.mY = position.y;
3510        return result;
3511    }
3512
3513    /**
3514     *  Delete text from start to end in the focused textfield. If there is no
3515     *  focus, or if start == end, silently fail.  If start and end are out of
3516     *  order, swap them.
3517     *  @param  start   Beginning of selection to delete.
3518     *  @param  end     End of selection to delete.
3519     */
3520    /* package */ void deleteSelection(int start, int end) {
3521        mTextGeneration++;
3522        WebViewCore.TextSelectionData data
3523                = new WebViewCore.TextSelectionData(start, end);
3524        mWebViewCore.sendMessage(EventHub.DELETE_SELECTION, mTextGeneration, 0,
3525                data);
3526    }
3527
3528    /**
3529     *  Set the selection to (start, end) in the focused textfield. If start and
3530     *  end are out of order, swap them.
3531     *  @param  start   Beginning of selection.
3532     *  @param  end     End of selection.
3533     */
3534    /* package */ void setSelection(int start, int end) {
3535        if (mWebViewCore != null) {
3536            mWebViewCore.sendMessage(EventHub.SET_SELECTION, start, end);
3537        }
3538    }
3539
3540    @Override
3541    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
3542      InputConnection connection = super.onCreateInputConnection(outAttrs);
3543      outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_FULLSCREEN;
3544      return connection;
3545    }
3546
3547    /**
3548     * Called in response to a message from webkit telling us that the soft
3549     * keyboard should be launched.
3550     */
3551    private void displaySoftKeyboard(boolean isTextView) {
3552        InputMethodManager imm = (InputMethodManager)
3553                getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
3554
3555        // bring it back to the reading level scale so that user can enter text
3556        boolean zoom = mZoomManager.getScale() < mZoomManager.getReadingLevelScale();
3557        if (zoom) {
3558            mZoomManager.setZoomCenter(mLastTouchX, mLastTouchY);
3559            mZoomManager.setZoomScale(mZoomManager.getReadingLevelScale(), false);
3560        }
3561        if (isTextView) {
3562            rebuildWebTextView();
3563            if (inEditingMode()) {
3564                imm.showSoftInput(mWebTextView, 0);
3565                if (zoom) {
3566                    didUpdateTextViewBounds(true);
3567                }
3568                return;
3569            }
3570        }
3571        // Used by plugins.
3572        // Also used if the navigation cache is out of date, and
3573        // does not recognize that a textfield is in focus.  In that
3574        // case, use WebView as the targeted view.
3575        // see http://b/issue?id=2457459
3576        imm.showSoftInput(this, 0);
3577    }
3578
3579    // Called by WebKit to instruct the UI to hide the keyboard
3580    private void hideSoftKeyboard() {
3581        InputMethodManager imm = (InputMethodManager)
3582                getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
3583
3584        imm.hideSoftInputFromWindow(this.getWindowToken(), 0);
3585    }
3586
3587    /*
3588     * This method checks the current focus and cursor and potentially rebuilds
3589     * mWebTextView to have the appropriate properties, such as password,
3590     * multiline, and what text it contains.  It also removes it if necessary.
3591     */
3592    /* package */ void rebuildWebTextView() {
3593        // If the WebView does not have focus, do nothing until it gains focus.
3594        if (!hasFocus() && (null == mWebTextView || !mWebTextView.hasFocus())) {
3595            return;
3596        }
3597        boolean alreadyThere = inEditingMode();
3598        // inEditingMode can only return true if mWebTextView is non-null,
3599        // so we can safely call remove() if (alreadyThere)
3600        if (0 == mNativeClass || !nativeFocusCandidateIsTextInput()) {
3601            if (alreadyThere) {
3602                mWebTextView.remove();
3603            }
3604            return;
3605        }
3606        // At this point, we know we have found an input field, so go ahead
3607        // and create the WebTextView if necessary.
3608        if (mWebTextView == null) {
3609            mWebTextView = new WebTextView(mContext, WebView.this);
3610            // Initialize our generation number.
3611            mTextGeneration = 0;
3612        }
3613        mWebTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
3614                contentToViewDimension(nativeFocusCandidateTextSize()));
3615        Rect visibleRect = new Rect();
3616        calcOurContentVisibleRect(visibleRect);
3617        // Note that sendOurVisibleRect calls viewToContent, so the coordinates
3618        // should be in content coordinates.
3619        Rect bounds = nativeFocusCandidateNodeBounds();
3620        Rect vBox = contentToViewRect(bounds);
3621        mWebTextView.setRect(vBox.left, vBox.top, vBox.width(), vBox.height());
3622        if (!Rect.intersects(bounds, visibleRect)) {
3623            mWebTextView.bringIntoView();
3624        }
3625        String text = nativeFocusCandidateText();
3626        int nodePointer = nativeFocusCandidatePointer();
3627        if (alreadyThere && mWebTextView.isSameTextField(nodePointer)) {
3628            // It is possible that we have the same textfield, but it has moved,
3629            // i.e. In the case of opening/closing the screen.
3630            // In that case, we need to set the dimensions, but not the other
3631            // aspects.
3632            // If the text has been changed by webkit, update it.  However, if
3633            // there has been more UI text input, ignore it.  We will receive
3634            // another update when that text is recognized.
3635            if (text != null && !text.equals(mWebTextView.getText().toString())
3636                    && nativeTextGeneration() == mTextGeneration) {
3637                mWebTextView.setTextAndKeepSelection(text);
3638            }
3639        } else {
3640            mWebTextView.setGravity(nativeFocusCandidateIsRtlText() ?
3641                    Gravity.RIGHT : Gravity.NO_GRAVITY);
3642            // This needs to be called before setType, which may call
3643            // requestFormData, and it needs to have the correct nodePointer.
3644            mWebTextView.setNodePointer(nodePointer);
3645            mWebTextView.setType(nativeFocusCandidateType());
3646            if (null == text) {
3647                if (DebugFlags.WEB_VIEW) {
3648                    Log.v(LOGTAG, "rebuildWebTextView null == text");
3649                }
3650                text = "";
3651            }
3652            mWebTextView.setTextAndKeepSelection(text);
3653            InputMethodManager imm = InputMethodManager.peekInstance();
3654            if (imm != null && imm.isActive(mWebTextView)) {
3655                imm.restartInput(mWebTextView);
3656            }
3657        }
3658        mWebTextView.requestFocus();
3659    }
3660
3661    /**
3662     * Called by WebTextView to find saved form data associated with the
3663     * textfield
3664     * @param name Name of the textfield.
3665     * @param nodePointer Pointer to the node of the textfield, so it can be
3666     *          compared to the currently focused textfield when the data is
3667     *          retrieved.
3668     */
3669    /* package */ void requestFormData(String name, int nodePointer) {
3670        if (mWebViewCore.getSettings().getSaveFormData()) {
3671            Message update = mPrivateHandler.obtainMessage(REQUEST_FORM_DATA);
3672            update.arg1 = nodePointer;
3673            RequestFormData updater = new RequestFormData(name, getUrl(),
3674                    update);
3675            Thread t = new Thread(updater);
3676            t.start();
3677        }
3678    }
3679
3680    /**
3681     * Pass a message to find out the <label> associated with the <input>
3682     * identified by nodePointer
3683     * @param framePointer Pointer to the frame containing the <input> node
3684     * @param nodePointer Pointer to the node for which a <label> is desired.
3685     */
3686    /* package */ void requestLabel(int framePointer, int nodePointer) {
3687        mWebViewCore.sendMessage(EventHub.REQUEST_LABEL, framePointer,
3688                nodePointer);
3689    }
3690
3691    /*
3692     * This class requests an Adapter for the WebTextView which shows past
3693     * entries stored in the database.  It is a Runnable so that it can be done
3694     * in its own thread, without slowing down the UI.
3695     */
3696    private class RequestFormData implements Runnable {
3697        private String mName;
3698        private String mUrl;
3699        private Message mUpdateMessage;
3700
3701        public RequestFormData(String name, String url, Message msg) {
3702            mName = name;
3703            mUrl = url;
3704            mUpdateMessage = msg;
3705        }
3706
3707        public void run() {
3708            ArrayList<String> pastEntries = mDatabase.getFormData(mUrl, mName);
3709            if (pastEntries.size() > 0) {
3710                AutoCompleteAdapter adapter = new
3711                        AutoCompleteAdapter(mContext, pastEntries);
3712                mUpdateMessage.obj = adapter;
3713                mUpdateMessage.sendToTarget();
3714            }
3715        }
3716    }
3717
3718    /**
3719     * Dump the display tree to "/sdcard/displayTree.txt"
3720     *
3721     * @hide debug only
3722     */
3723    public void dumpDisplayTree() {
3724        nativeDumpDisplayTree(getUrl());
3725    }
3726
3727    /**
3728     * Dump the dom tree to adb shell if "toFile" is False, otherwise dump it to
3729     * "/sdcard/domTree.txt"
3730     *
3731     * @hide debug only
3732     */
3733    public void dumpDomTree(boolean toFile) {
3734        mWebViewCore.sendMessage(EventHub.DUMP_DOMTREE, toFile ? 1 : 0, 0);
3735    }
3736
3737    /**
3738     * Dump the render tree to adb shell if "toFile" is False, otherwise dump it
3739     * to "/sdcard/renderTree.txt"
3740     *
3741     * @hide debug only
3742     */
3743    public void dumpRenderTree(boolean toFile) {
3744        mWebViewCore.sendMessage(EventHub.DUMP_RENDERTREE, toFile ? 1 : 0, 0);
3745    }
3746
3747    /**
3748     * Called by DRT on UI thread, need to proxy to WebCore thread.
3749     *
3750     * @hide debug only
3751     */
3752    public void useMockDeviceOrientation() {
3753        mWebViewCore.sendMessage(EventHub.USE_MOCK_DEVICE_ORIENTATION);
3754    }
3755
3756    /**
3757     * Called by DRT on WebCore thread.
3758     *
3759     * @hide debug only
3760     */
3761    public void setMockDeviceOrientation(boolean canProvideAlpha, double alpha,
3762            boolean canProvideBeta, double beta, boolean canProvideGamma, double gamma) {
3763        mWebViewCore.setMockDeviceOrientation(canProvideAlpha, alpha, canProvideBeta, beta,
3764                canProvideGamma, gamma);
3765    }
3766
3767    /**
3768     * Dump the V8 counters to standard output.
3769     * Note that you need a build with V8 and WEBCORE_INSTRUMENTATION set to
3770     * true. Otherwise, this will do nothing.
3771     *
3772     * @hide debug only
3773     */
3774    public void dumpV8Counters() {
3775        mWebViewCore.sendMessage(EventHub.DUMP_V8COUNTERS);
3776    }
3777
3778    // This is used to determine long press with the center key.  Does not
3779    // affect long press with the trackball/touch.
3780    private boolean mGotCenterDown = false;
3781
3782    @Override
3783    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
3784        // send complex characters to webkit for use by JS and plugins
3785        if (keyCode == KeyEvent.KEYCODE_UNKNOWN && event.getCharacters() != null) {
3786            // pass the key to DOM
3787            mWebViewCore.sendMessage(EventHub.KEY_DOWN, event);
3788            mWebViewCore.sendMessage(EventHub.KEY_UP, event);
3789            // return true as DOM handles the key
3790            return true;
3791        }
3792        return false;
3793    }
3794
3795    @Override
3796    public boolean onKeyDown(int keyCode, KeyEvent event) {
3797        if (DebugFlags.WEB_VIEW) {
3798            Log.v(LOGTAG, "keyDown at " + System.currentTimeMillis()
3799                    + ", " + event + ", unicode=" + event.getUnicodeChar());
3800        }
3801
3802        if (mNativeClass == 0) {
3803            return false;
3804        }
3805
3806        // do this hack up front, so it always works, regardless of touch-mode
3807        if (AUTO_REDRAW_HACK && (keyCode == KeyEvent.KEYCODE_CALL)) {
3808            mAutoRedraw = !mAutoRedraw;
3809            if (mAutoRedraw) {
3810                invalidate();
3811            }
3812            return true;
3813        }
3814
3815        // Bubble up the key event if
3816        // 1. it is a system key; or
3817        // 2. the host application wants to handle it;
3818        // 3. the accessibility injector is present and wants to handle it;
3819        if (event.isSystem()
3820                || mCallbackProxy.uiOverrideKeyEvent(event)
3821                || (mAccessibilityInjector != null && mAccessibilityInjector.onKeyEvent(event))) {
3822            return false;
3823        }
3824
3825        if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT
3826                || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT) {
3827            if (nativePageShouldHandleShiftAndArrows()) {
3828                mShiftIsPressed = true;
3829            } else if (!nativeCursorWantsKeyEvents() && !mSelectingText) {
3830                setUpSelect();
3831            }
3832        }
3833
3834        if (keyCode == KeyEvent.KEYCODE_PAGE_UP) {
3835            pageUp(false);
3836            return true;
3837        }
3838
3839        if (keyCode == KeyEvent.KEYCODE_PAGE_DOWN) {
3840            pageDown(false);
3841            return true;
3842        }
3843
3844        if (keyCode >= KeyEvent.KEYCODE_DPAD_UP
3845                && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) {
3846            switchOutDrawHistory();
3847            if (nativePageShouldHandleShiftAndArrows()) {
3848                letPageHandleNavKey(keyCode, event.getEventTime(), true);
3849                return true;
3850            }
3851            if (mSelectingText) {
3852                int xRate = keyCode == KeyEvent.KEYCODE_DPAD_LEFT
3853                    ? -1 : keyCode == KeyEvent.KEYCODE_DPAD_RIGHT ? 1 : 0;
3854                int yRate = keyCode == KeyEvent.KEYCODE_DPAD_UP ?
3855                    -1 : keyCode == KeyEvent.KEYCODE_DPAD_DOWN ? 1 : 0;
3856                int multiplier = event.getRepeatCount() + 1;
3857                moveSelection(xRate * multiplier, yRate * multiplier);
3858                return true;
3859            }
3860            if (navHandledKey(keyCode, 1, false, event.getEventTime())) {
3861                playSoundEffect(keyCodeToSoundsEffect(keyCode));
3862                return true;
3863            }
3864            // Bubble up the key event as WebView doesn't handle it
3865            return false;
3866        }
3867
3868        if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
3869            switchOutDrawHistory();
3870            if (event.getRepeatCount() == 0) {
3871                if (mSelectingText) {
3872                    return true; // discard press if copy in progress
3873                }
3874                mGotCenterDown = true;
3875                mPrivateHandler.sendMessageDelayed(mPrivateHandler
3876                        .obtainMessage(LONG_PRESS_CENTER), LONG_PRESS_TIMEOUT);
3877                // Already checked mNativeClass, so we do not need to check it
3878                // again.
3879                nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true);
3880                return true;
3881            }
3882            // Bubble up the key event as WebView doesn't handle it
3883            return false;
3884        }
3885
3886        if (keyCode != KeyEvent.KEYCODE_SHIFT_LEFT
3887                && keyCode != KeyEvent.KEYCODE_SHIFT_RIGHT) {
3888            // turn off copy select if a shift-key combo is pressed
3889            selectionDone();
3890            mShiftIsPressed = false;
3891        }
3892
3893        if (getSettings().getNavDump()) {
3894            switch (keyCode) {
3895                case KeyEvent.KEYCODE_4:
3896                    dumpDisplayTree();
3897                    break;
3898                case KeyEvent.KEYCODE_5:
3899                case KeyEvent.KEYCODE_6:
3900                    dumpDomTree(keyCode == KeyEvent.KEYCODE_5);
3901                    break;
3902                case KeyEvent.KEYCODE_7:
3903                case KeyEvent.KEYCODE_8:
3904                    dumpRenderTree(keyCode == KeyEvent.KEYCODE_7);
3905                    break;
3906                case KeyEvent.KEYCODE_9:
3907                    nativeInstrumentReport();
3908                    return true;
3909            }
3910        }
3911
3912        if (nativeCursorIsTextInput()) {
3913            // This message will put the node in focus, for the DOM's notion
3914            // of focus, and make the focuscontroller active
3915            mWebViewCore.sendMessage(EventHub.CLICK, nativeCursorFramePointer(),
3916                    nativeCursorNodePointer());
3917            // This will bring up the WebTextView and put it in focus, for
3918            // our view system's notion of focus
3919            rebuildWebTextView();
3920            // Now we need to pass the event to it
3921            if (inEditingMode()) {
3922                mWebTextView.setDefaultSelection();
3923                return mWebTextView.dispatchKeyEvent(event);
3924            }
3925        } else if (nativeHasFocusNode()) {
3926            // In this case, the cursor is not on a text input, but the focus
3927            // might be.  Check it, and if so, hand over to the WebTextView.
3928            rebuildWebTextView();
3929            if (inEditingMode()) {
3930                mWebTextView.setDefaultSelection();
3931                return mWebTextView.dispatchKeyEvent(event);
3932            }
3933        }
3934
3935        // TODO: should we pass all the keys to DOM or check the meta tag
3936        if (nativeCursorWantsKeyEvents() || true) {
3937            // pass the key to DOM
3938            mWebViewCore.sendMessage(EventHub.KEY_DOWN, event);
3939            // return true as DOM handles the key
3940            return true;
3941        }
3942
3943        // Bubble up the key event as WebView doesn't handle it
3944        return false;
3945    }
3946
3947    @Override
3948    public boolean onKeyUp(int keyCode, KeyEvent event) {
3949        if (DebugFlags.WEB_VIEW) {
3950            Log.v(LOGTAG, "keyUp at " + System.currentTimeMillis()
3951                    + ", " + event + ", unicode=" + event.getUnicodeChar());
3952        }
3953
3954        if (mNativeClass == 0) {
3955            return false;
3956        }
3957
3958        // special CALL handling when cursor node's href is "tel:XXX"
3959        if (keyCode == KeyEvent.KEYCODE_CALL && nativeHasCursorNode()) {
3960            String text = nativeCursorText();
3961            if (!nativeCursorIsTextInput() && text != null
3962                    && text.startsWith(SCHEME_TEL)) {
3963                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(text));
3964                getContext().startActivity(intent);
3965                return true;
3966            }
3967        }
3968
3969        // Bubble up the key event if
3970        // 1. it is a system key; or
3971        // 2. the host application wants to handle it;
3972        // 3. the accessibility injector is present and wants to handle it;
3973        if (event.isSystem()
3974                || mCallbackProxy.uiOverrideKeyEvent(event)
3975                || (mAccessibilityInjector != null && mAccessibilityInjector.onKeyEvent(event))) {
3976            return false;
3977        }
3978
3979        if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT
3980                || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT) {
3981            if (nativePageShouldHandleShiftAndArrows()) {
3982                mShiftIsPressed = false;
3983            } else if (copySelection()) {
3984                selectionDone();
3985                return true;
3986            }
3987        }
3988
3989        if (keyCode >= KeyEvent.KEYCODE_DPAD_UP
3990                && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) {
3991            if (nativePageShouldHandleShiftAndArrows()) {
3992                letPageHandleNavKey(keyCode, event.getEventTime(), false);
3993                return true;
3994            }
3995            // always handle the navigation keys in the UI thread
3996            // Bubble up the key event as WebView doesn't handle it
3997            return false;
3998        }
3999
4000        if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
4001            // remove the long press message first
4002            mPrivateHandler.removeMessages(LONG_PRESS_CENTER);
4003            mGotCenterDown = false;
4004
4005            if (mSelectingText) {
4006                if (mExtendSelection) {
4007                    copySelection();
4008                    selectionDone();
4009                } else {
4010                    mExtendSelection = true;
4011                    nativeSetExtendSelection();
4012                    invalidate(); // draw the i-beam instead of the arrow
4013                }
4014                return true; // discard press if copy in progress
4015            }
4016
4017            // perform the single click
4018            Rect visibleRect = sendOurVisibleRect();
4019            // Note that sendOurVisibleRect calls viewToContent, so the
4020            // coordinates should be in content coordinates.
4021            if (!nativeCursorIntersects(visibleRect)) {
4022                return false;
4023            }
4024            WebViewCore.CursorData data = cursorData();
4025            mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE, data);
4026            playSoundEffect(SoundEffectConstants.CLICK);
4027            if (nativeCursorIsTextInput()) {
4028                rebuildWebTextView();
4029                centerKeyPressOnTextField();
4030                if (inEditingMode()) {
4031                    mWebTextView.setDefaultSelection();
4032                }
4033                return true;
4034            }
4035            clearTextEntry();
4036            nativeSetFollowedLink(true);
4037            if (!mCallbackProxy.uiOverrideUrlLoading(nativeCursorText())) {
4038                mWebViewCore.sendMessage(EventHub.CLICK, data.mFrame,
4039                        nativeCursorNodePointer());
4040            }
4041            return true;
4042        }
4043
4044        // TODO: should we pass all the keys to DOM or check the meta tag
4045        if (nativeCursorWantsKeyEvents() || true) {
4046            // pass the key to DOM
4047            mWebViewCore.sendMessage(EventHub.KEY_UP, event);
4048            // return true as DOM handles the key
4049            return true;
4050        }
4051
4052        // Bubble up the key event as WebView doesn't handle it
4053        return false;
4054    }
4055
4056    /**
4057     * @hide pending API council approval.
4058     */
4059    public void setUpSelect() {
4060        if (0 == mNativeClass) return; // client isn't initialized
4061        if (inFullScreenMode()) return;
4062        if (mSelectingText) return;
4063        mExtendSelection = false;
4064        mSelectingText = mDrawSelectionPointer = true;
4065        // don't let the picture change during text selection
4066        WebViewCore.pauseUpdatePicture(mWebViewCore);
4067        nativeResetSelection();
4068        if (nativeHasCursorNode()) {
4069            Rect rect = nativeCursorNodeBounds();
4070            mSelectX = contentToViewX(rect.left);
4071            mSelectY = contentToViewY(rect.top);
4072        } else if (mLastTouchY > getVisibleTitleHeight()) {
4073            mSelectX = mScrollX + (int) mLastTouchX;
4074            mSelectY = mScrollY + (int) mLastTouchY;
4075        } else {
4076            mSelectX = mScrollX + getViewWidth() / 2;
4077            mSelectY = mScrollY + getViewHeightWithTitle() / 2;
4078        }
4079        nativeHideCursor();
4080    }
4081
4082    /**
4083     * Use this method to put the WebView into text selection mode.
4084     * Do not rely on this functionality; it will be deprecated in the future.
4085     */
4086    public void emulateShiftHeld() {
4087        setUpSelect();
4088    }
4089
4090    /**
4091     * @hide pending API council approval.
4092     */
4093    public void selectAll() {
4094        if (0 == mNativeClass) return; // client isn't initialized
4095        if (inFullScreenMode()) return;
4096        if (!mSelectingText) setUpSelect();
4097        nativeSelectAll();
4098        mDrawSelectionPointer = false;
4099        mExtendSelection = true;
4100        invalidate();
4101    }
4102
4103    /**
4104     * @hide pending API council approval.
4105     */
4106    public boolean selectDialogIsUp() {
4107        return mSelectingText;
4108    }
4109
4110    /**
4111     * @hide pending API council approval.
4112     */
4113    public void notifySelectDialogDismissed() {
4114        mSelectingText = false;
4115        WebViewCore.resumeUpdatePicture(mWebViewCore);
4116    }
4117
4118    /**
4119     * @hide pending API council approval.
4120     */
4121    public void selectionDone() {
4122        if (mSelectingText) {
4123            getWebChromeClient().onSelectionDone(this);
4124            invalidate(); // redraw without selection
4125            notifySelectDialogDismissed();
4126        }
4127    }
4128
4129    /**
4130     * @hide pending API council approval.
4131     */
4132    public boolean copySelection() {
4133        boolean copiedSomething = false;
4134        String selection = getSelection();
4135        if (selection != "") {
4136            if (DebugFlags.WEB_VIEW) {
4137                Log.v(LOGTAG, "copySelection \"" + selection + "\"");
4138            }
4139            Toast.makeText(mContext
4140                    , com.android.internal.R.string.text_copied
4141                    , Toast.LENGTH_SHORT).show();
4142            copiedSomething = true;
4143            ClipboardManager cm = (ClipboardManager)getContext()
4144                    .getSystemService(Context.CLIPBOARD_SERVICE);
4145            cm.setText(selection);
4146        }
4147        invalidate(); // remove selection region and pointer
4148        return copiedSomething;
4149    }
4150
4151    /**
4152     * @hide pending API council approval.
4153     */
4154    public String getSelection() {
4155        if (mNativeClass == 0) return "";
4156        return nativeGetSelection();
4157    }
4158
4159    @Override
4160    protected void onAttachedToWindow() {
4161        super.onAttachedToWindow();
4162        if (hasWindowFocus()) setActive(true);
4163    }
4164
4165    @Override
4166    protected void onDetachedFromWindow() {
4167        clearTextEntry();
4168        mZoomManager.dismissZoomPicker();
4169        if (hasWindowFocus()) setActive(false);
4170        super.onDetachedFromWindow();
4171    }
4172
4173    @Override
4174    protected void onVisibilityChanged(View changedView, int visibility) {
4175        super.onVisibilityChanged(changedView, visibility);
4176        // The zoomManager may be null if the webview is created from XML that
4177        // specifies the view's visibility param as not visible (see http://b/2794841)
4178        if (visibility != View.VISIBLE && mZoomManager != null) {
4179            mZoomManager.dismissZoomPicker();
4180        }
4181    }
4182
4183    /**
4184     * @deprecated WebView no longer needs to implement
4185     * ViewGroup.OnHierarchyChangeListener.  This method does nothing now.
4186     */
4187    @Deprecated
4188    public void onChildViewAdded(View parent, View child) {}
4189
4190    /**
4191     * @deprecated WebView no longer needs to implement
4192     * ViewGroup.OnHierarchyChangeListener.  This method does nothing now.
4193     */
4194    @Deprecated
4195    public void onChildViewRemoved(View p, View child) {}
4196
4197    /**
4198     * @deprecated WebView should not have implemented
4199     * ViewTreeObserver.OnGlobalFocusChangeListener.  This method
4200     * does nothing now.
4201     */
4202    @Deprecated
4203    public void onGlobalFocusChanged(View oldFocus, View newFocus) {
4204    }
4205
4206    private void setActive(boolean active) {
4207        if (active) {
4208            if (hasFocus()) {
4209                // If our window regained focus, and we have focus, then begin
4210                // drawing the cursor ring
4211                mDrawCursorRing = true;
4212                setFocusControllerActive(true);
4213                if (mNativeClass != 0) {
4214                    nativeRecordButtons(true, false, true);
4215                }
4216            } else {
4217                if (!inEditingMode()) {
4218                    // If our window gained focus, but we do not have it, do not
4219                    // draw the cursor ring.
4220                    mDrawCursorRing = false;
4221                    setFocusControllerActive(false);
4222                }
4223                // We do not call nativeRecordButtons here because we assume
4224                // that when we lost focus, or window focus, it got called with
4225                // false for the first parameter
4226            }
4227        } else {
4228            if (!mZoomManager.isZoomPickerVisible()) {
4229                /*
4230                 * The external zoom controls come in their own window, so our
4231                 * window loses focus. Our policy is to not draw the cursor ring
4232                 * if our window is not focused, but this is an exception since
4233                 * the user can still navigate the web page with the zoom
4234                 * controls showing.
4235                 */
4236                mDrawCursorRing = false;
4237            }
4238            mGotKeyDown = false;
4239            mShiftIsPressed = false;
4240            mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
4241            mTouchMode = TOUCH_DONE_MODE;
4242            if (mNativeClass != 0) {
4243                nativeRecordButtons(false, false, true);
4244            }
4245            setFocusControllerActive(false);
4246        }
4247        invalidate();
4248    }
4249
4250    // To avoid drawing the cursor ring, and remove the TextView when our window
4251    // loses focus.
4252    @Override
4253    public void onWindowFocusChanged(boolean hasWindowFocus) {
4254        setActive(hasWindowFocus);
4255        if (hasWindowFocus) {
4256            JWebCoreJavaBridge.setActiveWebView(this);
4257        } else {
4258            JWebCoreJavaBridge.removeActiveWebView(this);
4259        }
4260        super.onWindowFocusChanged(hasWindowFocus);
4261    }
4262
4263    /*
4264     * Pass a message to WebCore Thread, telling the WebCore::Page's
4265     * FocusController to be  "inactive" so that it will
4266     * not draw the blinking cursor.  It gets set to "active" to draw the cursor
4267     * in WebViewCore.cpp, when the WebCore thread receives key events/clicks.
4268     */
4269    /* package */ void setFocusControllerActive(boolean active) {
4270        if (mWebViewCore == null) return;
4271        mWebViewCore.sendMessage(EventHub.SET_ACTIVE, active ? 1 : 0, 0);
4272    }
4273
4274    @Override
4275    protected void onFocusChanged(boolean focused, int direction,
4276            Rect previouslyFocusedRect) {
4277        if (DebugFlags.WEB_VIEW) {
4278            Log.v(LOGTAG, "MT focusChanged " + focused + ", " + direction);
4279        }
4280        if (focused) {
4281            // When we regain focus, if we have window focus, resume drawing
4282            // the cursor ring
4283            if (hasWindowFocus()) {
4284                mDrawCursorRing = true;
4285                if (mNativeClass != 0) {
4286                    nativeRecordButtons(true, false, true);
4287                }
4288                setFocusControllerActive(true);
4289            //} else {
4290                // The WebView has gained focus while we do not have
4291                // windowfocus.  When our window lost focus, we should have
4292                // called nativeRecordButtons(false...)
4293            }
4294        } else {
4295            // When we lost focus, unless focus went to the TextView (which is
4296            // true if we are in editing mode), stop drawing the cursor ring.
4297            if (!inEditingMode()) {
4298                mDrawCursorRing = false;
4299                if (mNativeClass != 0) {
4300                    nativeRecordButtons(false, false, true);
4301                }
4302                setFocusControllerActive(false);
4303            }
4304            mGotKeyDown = false;
4305        }
4306
4307        super.onFocusChanged(focused, direction, previouslyFocusedRect);
4308    }
4309
4310    /**
4311     * @hide
4312     */
4313    @Override
4314    protected boolean setFrame(int left, int top, int right, int bottom) {
4315        boolean changed = super.setFrame(left, top, right, bottom);
4316        if (!changed && mHeightCanMeasure) {
4317            // When mHeightCanMeasure is true, we will set mLastHeightSent to 0
4318            // in WebViewCore after we get the first layout. We do call
4319            // requestLayout() when we get contentSizeChanged(). But the View
4320            // system won't call onSizeChanged if the dimension is not changed.
4321            // In this case, we need to call sendViewSizeZoom() explicitly to
4322            // notify the WebKit about the new dimensions.
4323            sendViewSizeZoom(false);
4324        }
4325        return changed;
4326    }
4327
4328    @Override
4329    protected void onSizeChanged(int w, int h, int ow, int oh) {
4330        super.onSizeChanged(w, h, ow, oh);
4331
4332        // adjust the max viewport width depending on the view dimensions. This
4333        // is to ensure the scaling is not going insane. So do not shrink it if
4334        // the view size is temporarily smaller, e.g. when soft keyboard is up.
4335        int newMaxViewportWidth = (int) (Math.max(w, h) / mZoomManager.getDefaultMinZoomScale());
4336        if (newMaxViewportWidth > sMaxViewportWidth) {
4337            sMaxViewportWidth = newMaxViewportWidth;
4338        }
4339
4340        mZoomManager.onSizeChanged(w, h, ow, oh);
4341    }
4342
4343    @Override
4344    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
4345        super.onScrollChanged(l, t, oldl, oldt);
4346        sendOurVisibleRect();
4347        // update WebKit if visible title bar height changed. The logic is same
4348        // as getVisibleTitleHeight.
4349        int titleHeight = getTitleHeight();
4350        if (Math.max(titleHeight - t, 0) != Math.max(titleHeight - oldt, 0)) {
4351            sendViewSizeZoom(false);
4352        }
4353    }
4354
4355    @Override
4356    public boolean dispatchKeyEvent(KeyEvent event) {
4357        boolean dispatch = true;
4358
4359        // Textfields, plugins, and contentEditable nodes need to receive the
4360        // shift up key even if another key was released while the shift key
4361        // was held down.
4362        if (!inEditingMode() && (mNativeClass == 0
4363                || !nativePageShouldHandleShiftAndArrows())) {
4364            if (event.getAction() == KeyEvent.ACTION_DOWN) {
4365                mGotKeyDown = true;
4366            } else {
4367                if (!mGotKeyDown) {
4368                    /*
4369                     * We got a key up for which we were not the recipient of
4370                     * the original key down. Don't give it to the view.
4371                     */
4372                    dispatch = false;
4373                }
4374                mGotKeyDown = false;
4375            }
4376        }
4377
4378        if (dispatch) {
4379            return super.dispatchKeyEvent(event);
4380        } else {
4381            // We didn't dispatch, so let something else handle the key
4382            return false;
4383        }
4384    }
4385
4386    // Here are the snap align logic:
4387    // 1. If it starts nearly horizontally or vertically, snap align;
4388    // 2. If there is a dramitic direction change, let it go;
4389    // 3. If there is a same direction back and forth, lock it.
4390
4391    // adjustable parameters
4392    private int mMinLockSnapReverseDistance;
4393    private static final float MAX_SLOPE_FOR_DIAG = 1.5f;
4394    private static final int MIN_BREAK_SNAP_CROSS_DISTANCE = 80;
4395
4396    private static int sign(float x) {
4397        return x > 0 ? 1 : (x < 0 ? -1 : 0);
4398    }
4399
4400    // if the page can scroll <= this value, we won't allow the drag tracker
4401    // to have any effect.
4402    private static final int MIN_SCROLL_AMOUNT_TO_DISABLE_DRAG_TRACKER = 4;
4403
4404    private class DragTrackerHandler {
4405        private final DragTracker mProxy;
4406        private final float mStartY, mStartX;
4407        private final float mMinDY, mMinDX;
4408        private final float mMaxDY, mMaxDX;
4409        private float mCurrStretchY, mCurrStretchX;
4410        private int mSX, mSY;
4411        private Interpolator mInterp;
4412        private float[] mXY = new float[2];
4413
4414        // inner (non-state) classes can't have enums :(
4415        private static final int DRAGGING_STATE = 0;
4416        private static final int ANIMATING_STATE = 1;
4417        private static final int FINISHED_STATE = 2;
4418        private int mState;
4419
4420        public DragTrackerHandler(float x, float y, DragTracker proxy) {
4421            mProxy = proxy;
4422
4423            int docBottom = computeVerticalScrollRange() + getTitleHeight();
4424            int viewTop = getScrollY();
4425            int viewBottom = viewTop + getHeight();
4426
4427            mStartY = y;
4428            mMinDY = -viewTop;
4429            mMaxDY = docBottom - viewBottom;
4430
4431            if (DebugFlags.DRAG_TRACKER || DEBUG_DRAG_TRACKER) {
4432                Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, " dragtracker y= " + y +
4433                      " up/down= " + mMinDY + " " + mMaxDY);
4434            }
4435
4436            int docRight = computeHorizontalScrollRange();
4437            int viewLeft = getScrollX();
4438            int viewRight = viewLeft + getWidth();
4439            mStartX = x;
4440            mMinDX = -viewLeft;
4441            mMaxDX = docRight - viewRight;
4442
4443            mState = DRAGGING_STATE;
4444            mProxy.onStartDrag(x, y);
4445
4446            // ensure we buildBitmap at least once
4447            mSX = -99999;
4448        }
4449
4450        private float computeStretch(float delta, float min, float max) {
4451            float stretch = 0;
4452            if (max - min > MIN_SCROLL_AMOUNT_TO_DISABLE_DRAG_TRACKER) {
4453                if (delta < min) {
4454                    stretch = delta - min;
4455                } else if (delta > max) {
4456                    stretch = delta - max;
4457                }
4458            }
4459            return stretch;
4460        }
4461
4462        public void dragTo(float x, float y) {
4463            float sy = computeStretch(mStartY - y, mMinDY, mMaxDY);
4464            float sx = computeStretch(mStartX - x, mMinDX, mMaxDX);
4465
4466            if ((mSnapScrollMode & SNAP_X) != 0) {
4467                sy = 0;
4468            } else if ((mSnapScrollMode & SNAP_Y) != 0) {
4469                sx = 0;
4470            }
4471
4472            if (mCurrStretchX != sx || mCurrStretchY != sy) {
4473                mCurrStretchX = sx;
4474                mCurrStretchY = sy;
4475                if (DebugFlags.DRAG_TRACKER || DEBUG_DRAG_TRACKER) {
4476                    Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, "---- stretch " + sx +
4477                          " " + sy);
4478                }
4479                if (mProxy.onStretchChange(sx, sy)) {
4480                    invalidate();
4481                }
4482            }
4483        }
4484
4485        public void stopDrag() {
4486            final int DURATION = 200;
4487            int now = (int)SystemClock.uptimeMillis();
4488            mInterp = new Interpolator(2);
4489            mXY[0] = mCurrStretchX;
4490            mXY[1] = mCurrStretchY;
4491         //   float[] blend = new float[] { 0.5f, 0, 0.75f, 1 };
4492            float[] blend = new float[] { 0, 0.5f, 0.75f, 1 };
4493            mInterp.setKeyFrame(0, now, mXY, blend);
4494            float[] zerozero = new float[] { 0, 0 };
4495            mInterp.setKeyFrame(1, now + DURATION, zerozero, null);
4496            mState = ANIMATING_STATE;
4497
4498            if (DebugFlags.DRAG_TRACKER || DEBUG_DRAG_TRACKER) {
4499                Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, "----- stopDrag, starting animation");
4500            }
4501        }
4502
4503        // Call this after each draw. If it ruturns null, the tracker is done
4504        public boolean isFinished() {
4505            return mState == FINISHED_STATE;
4506        }
4507
4508        private int hiddenHeightOfTitleBar() {
4509            return getTitleHeight() - getVisibleTitleHeight();
4510        }
4511
4512        // need a way to know if 565 or 8888 is the right config for
4513        // capturing the display and giving it to the drag proxy
4514        private Bitmap.Config offscreenBitmapConfig() {
4515            // hard code 565 for now
4516            return Bitmap.Config.RGB_565;
4517        }
4518
4519        /*  If the tracker draws, then this returns true, otherwise it will
4520            return false, and draw nothing.
4521         */
4522        public boolean draw(Canvas canvas) {
4523            if (mCurrStretchX != 0 || mCurrStretchY != 0) {
4524                int sx = getScrollX();
4525                int sy = getScrollY() - hiddenHeightOfTitleBar();
4526                if (mSX != sx || mSY != sy) {
4527                    buildBitmap(sx, sy);
4528                    mSX = sx;
4529                    mSY = sy;
4530                }
4531
4532                if (mState == ANIMATING_STATE) {
4533                    Interpolator.Result result = mInterp.timeToValues(mXY);
4534                    if (result == Interpolator.Result.FREEZE_END) {
4535                        mState = FINISHED_STATE;
4536                        return false;
4537                    } else {
4538                        mProxy.onStretchChange(mXY[0], mXY[1]);
4539                        invalidate();
4540                        // fall through to the draw
4541                    }
4542                }
4543                int count = canvas.save(Canvas.MATRIX_SAVE_FLAG);
4544                canvas.translate(sx, sy);
4545                mProxy.onDraw(canvas);
4546                canvas.restoreToCount(count);
4547                return true;
4548            }
4549            if (DebugFlags.DRAG_TRACKER || DEBUG_DRAG_TRACKER) {
4550                Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, " -- draw false " +
4551                      mCurrStretchX + " " + mCurrStretchY);
4552            }
4553            return false;
4554        }
4555
4556        private void buildBitmap(int sx, int sy) {
4557            int w = getWidth();
4558            int h = getViewHeight();
4559            Bitmap bm = Bitmap.createBitmap(w, h, offscreenBitmapConfig());
4560            Canvas canvas = new Canvas(bm);
4561            canvas.translate(-sx, -sy);
4562            drawContent(canvas);
4563
4564            if (DebugFlags.DRAG_TRACKER || DEBUG_DRAG_TRACKER) {
4565                Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, "--- buildBitmap " + sx +
4566                      " " + sy + " " + w + " " + h);
4567            }
4568            mProxy.onBitmapChange(bm);
4569        }
4570    }
4571
4572    /** @hide */
4573    public static class DragTracker {
4574        public void onStartDrag(float x, float y) {}
4575        public boolean onStretchChange(float sx, float sy) {
4576            // return true to have us inval the view
4577            return false;
4578        }
4579        public void onStopDrag() {}
4580        public void onBitmapChange(Bitmap bm) {}
4581        public void onDraw(Canvas canvas) {}
4582    }
4583
4584    /** @hide */
4585    public DragTracker getDragTracker() {
4586        return mDragTracker;
4587    }
4588
4589    /** @hide */
4590    public void setDragTracker(DragTracker tracker) {
4591        mDragTracker = tracker;
4592    }
4593
4594    private DragTracker mDragTracker;
4595    private DragTrackerHandler mDragTrackerHandler;
4596
4597    private boolean hitFocusedPlugin(int contentX, int contentY) {
4598        if (DebugFlags.WEB_VIEW) {
4599            Log.v(LOGTAG, "nativeFocusIsPlugin()=" + nativeFocusIsPlugin());
4600            Rect r = nativeFocusNodeBounds();
4601            Log.v(LOGTAG, "nativeFocusNodeBounds()=(" + r.left + ", " + r.top
4602                    + ", " + r.right + ", " + r.bottom + ")");
4603        }
4604        return nativeFocusIsPlugin()
4605                && nativeFocusNodeBounds().contains(contentX, contentY);
4606    }
4607
4608    private boolean shouldForwardTouchEvent() {
4609        return mFullScreenHolder != null || (mForwardTouchEvents
4610                && !mSelectingText
4611                && mPreventDefault != PREVENT_DEFAULT_IGNORE);
4612    }
4613
4614    private boolean inFullScreenMode() {
4615        return mFullScreenHolder != null;
4616    }
4617
4618    void onPinchToZoomAnimationStart() {
4619        // cancel the single touch handling
4620        cancelTouch();
4621        onZoomAnimationStart();
4622    }
4623
4624    void onPinchToZoomAnimationEnd(ScaleGestureDetector detector) {
4625        onZoomAnimationEnd();
4626        // start a drag, TOUCH_PINCH_DRAG, can't use TOUCH_INIT_MODE as
4627        // it may trigger the unwanted click, can't use TOUCH_DRAG_MODE
4628        // as it may trigger the unwanted fling.
4629        mTouchMode = TOUCH_PINCH_DRAG;
4630        mConfirmMove = true;
4631        startTouch(detector.getFocusX(), detector.getFocusY(), mLastTouchTime);
4632    }
4633
4634    private void startScrollingLayer(float gestureX, float gestureY) {
4635        if (mTouchMode != TOUCH_DRAG_LAYER_MODE) {
4636            int contentX = viewToContentX((int) gestureX + mScrollX);
4637            int contentY = viewToContentY((int) gestureY + mScrollY);
4638            mScrollingLayer = nativeScrollableLayer(contentX, contentY);
4639            if (mScrollingLayer != 0) {
4640                mTouchMode = TOUCH_DRAG_LAYER_MODE;
4641            }
4642        }
4643    }
4644
4645    // 1/(density * density) used to compute the distance between points.
4646    // Computed in init().
4647    private float DRAG_LAYER_INVERSE_DENSITY_SQUARED;
4648
4649    // The distance between two points reported in onTouchEvent scaled by the
4650    // density of the screen.
4651    private static final int DRAG_LAYER_FINGER_DISTANCE = 20000;
4652
4653    @Override
4654    public boolean onTouchEvent(MotionEvent ev) {
4655        if (mNativeClass == 0 || !isClickable() || !isLongClickable()) {
4656            return false;
4657        }
4658
4659        if (DebugFlags.WEB_VIEW) {
4660            Log.v(LOGTAG, ev + " at " + ev.getEventTime() + " mTouchMode="
4661                    + mTouchMode);
4662        }
4663
4664        int action = ev.getAction();
4665        float x = ev.getX();
4666        float y = ev.getY();
4667        long eventTime = ev.getEventTime();
4668
4669        final ScaleGestureDetector detector =
4670                mZoomManager.getMultiTouchGestureDetector();
4671        boolean skipScaleGesture = false;
4672        // Set to the mid-point of a two-finger gesture used to detect if the
4673        // user has touched a layer.
4674        float gestureX = x;
4675        float gestureY = y;
4676        if (detector == null || !detector.isInProgress()) {
4677            // The gesture for scrolling a layer is two fingers close together.
4678            // FIXME: we may consider giving WebKit an option to handle
4679            // multi-touch events later.
4680            if (ev.getPointerCount() > 1) {
4681                float dx = ev.getX(1) - ev.getX(0);
4682                float dy = ev.getY(1) - ev.getY(0);
4683                float dist = (dx * dx + dy * dy) *
4684                        DRAG_LAYER_INVERSE_DENSITY_SQUARED;
4685                // Use the approximate center to determine if the gesture is in
4686                // a layer.
4687                gestureX = ev.getX(0) + (dx * .5f);
4688                gestureY = ev.getY(0) + (dy * .5f);
4689                // Now use a consistent point for tracking movement.
4690                if (ev.getX(0) < ev.getX(1)) {
4691                    x = ev.getX(0);
4692                    y = ev.getY(0);
4693                } else {
4694                    x = ev.getX(1);
4695                    y = ev.getY(1);
4696                }
4697                action = ev.getActionMasked();
4698                if (dist < DRAG_LAYER_FINGER_DISTANCE) {
4699                    skipScaleGesture = true;
4700                } else if (mTouchMode == TOUCH_DRAG_LAYER_MODE) {
4701                    // Fingers moved too far apart while dragging, the user
4702                    // might be trying to zoom.
4703                    mTouchMode = TOUCH_INIT_MODE;
4704                }
4705            }
4706        }
4707
4708        // FIXME: we may consider to give WebKit an option to handle multi-touch
4709        // events later.
4710        if (mZoomManager.supportsMultiTouchZoom() && ev.getPointerCount() > 1 &&
4711                mTouchMode != TOUCH_DRAG_LAYER_MODE && !skipScaleGesture) {
4712
4713            // if the page disallows zoom, skip multi-pointer action
4714            if (mZoomManager.isZoomScaleFixed()) {
4715                return true;
4716            }
4717
4718            if (!detector.isInProgress() &&
4719                    ev.getActionMasked() != MotionEvent.ACTION_POINTER_DOWN) {
4720                // Insert a fake pointer down event in order to start
4721                // the zoom scale detector.
4722                MotionEvent temp = MotionEvent.obtain(ev);
4723                // Clear the original event and set it to
4724                // ACTION_POINTER_DOWN.
4725                temp.setAction(temp.getAction() &
4726                        ~MotionEvent.ACTION_MASK |
4727                        MotionEvent.ACTION_POINTER_DOWN);
4728                detector.onTouchEvent(temp);
4729            }
4730
4731            detector.onTouchEvent(ev);
4732
4733            if (detector.isInProgress()) {
4734                mLastTouchTime = eventTime;
4735                return true;
4736            }
4737
4738            x = detector.getFocusX();
4739            y = detector.getFocusY();
4740            action = ev.getAction() & MotionEvent.ACTION_MASK;
4741            if (action == MotionEvent.ACTION_POINTER_DOWN) {
4742                cancelTouch();
4743                action = MotionEvent.ACTION_DOWN;
4744            } else if (action == MotionEvent.ACTION_POINTER_UP) {
4745                // set mLastTouchX/Y to the remaining point
4746                mLastTouchX = x;
4747                mLastTouchY = y;
4748            } else if (action == MotionEvent.ACTION_MOVE) {
4749                // negative x or y indicate it is on the edge, skip it.
4750                if (x < 0 || y < 0) {
4751                    return true;
4752                }
4753            }
4754        }
4755
4756        // Due to the touch screen edge effect, a touch closer to the edge
4757        // always snapped to the edge. As getViewWidth() can be different from
4758        // getWidth() due to the scrollbar, adjusting the point to match
4759        // getViewWidth(). Same applied to the height.
4760        x = Math.min(x, getViewWidth() - 1);
4761        y = Math.min(y, getViewHeightWithTitle() - 1);
4762
4763        float fDeltaX = mLastTouchX - x;
4764        float fDeltaY = mLastTouchY - y;
4765        int deltaX = (int) fDeltaX;
4766        int deltaY = (int) fDeltaY;
4767        int contentX = viewToContentX((int) x + mScrollX);
4768        int contentY = viewToContentY((int) y + mScrollY);
4769
4770        switch (action) {
4771            case MotionEvent.ACTION_DOWN: {
4772                mPreventDefault = PREVENT_DEFAULT_NO;
4773                mConfirmMove = false;
4774                if (!mScroller.isFinished()) {
4775                    // stop the current scroll animation, but if this is
4776                    // the start of a fling, allow it to add to the current
4777                    // fling's velocity
4778                    mScroller.abortAnimation();
4779                    mTouchMode = TOUCH_DRAG_START_MODE;
4780                    mConfirmMove = true;
4781                    mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY);
4782                } else if (mPrivateHandler.hasMessages(RELEASE_SINGLE_TAP)) {
4783                    mPrivateHandler.removeMessages(RELEASE_SINGLE_TAP);
4784                    if (getSettings().supportTouchOnly()) {
4785                        removeTouchHighlight(true);
4786                    }
4787                    if (deltaX * deltaX + deltaY * deltaY < mDoubleTapSlopSquare) {
4788                        mTouchMode = TOUCH_DOUBLE_TAP_MODE;
4789                    } else {
4790                        // commit the short press action for the previous tap
4791                        doShortPress();
4792                        mTouchMode = TOUCH_INIT_MODE;
4793                        mDeferTouchProcess = (!inFullScreenMode()
4794                                && mForwardTouchEvents) ? hitFocusedPlugin(
4795                                contentX, contentY) : false;
4796                    }
4797                } else { // the normal case
4798                    mTouchMode = TOUCH_INIT_MODE;
4799                    mDeferTouchProcess = (!inFullScreenMode()
4800                            && mForwardTouchEvents) ? hitFocusedPlugin(
4801                            contentX, contentY) : false;
4802                    mWebViewCore.sendMessage(
4803                            EventHub.UPDATE_FRAME_CACHE_IF_LOADING);
4804                    if (getSettings().supportTouchOnly()) {
4805                        TouchHighlightData data = new TouchHighlightData();
4806                        data.mX = contentX;
4807                        data.mY = contentY;
4808                        data.mSlop = viewToContentDimension(mNavSlop);
4809                        mWebViewCore.sendMessageDelayed(
4810                                EventHub.GET_TOUCH_HIGHLIGHT_RECTS, data,
4811                                ViewConfiguration.getTapTimeout());
4812                        if (DEBUG_TOUCH_HIGHLIGHT) {
4813                            if (getSettings().getNavDump()) {
4814                                mTouchHighlightX = (int) x + mScrollX;
4815                                mTouchHighlightY = (int) y + mScrollY;
4816                                mPrivateHandler.postDelayed(new Runnable() {
4817                                    public void run() {
4818                                        mTouchHighlightX = mTouchHighlightY = 0;
4819                                        invalidate();
4820                                    }
4821                                }, TOUCH_HIGHLIGHT_ELAPSE_TIME);
4822                            }
4823                        }
4824                    }
4825                    if (mLogEvent && eventTime - mLastTouchUpTime < 1000) {
4826                        EventLog.writeEvent(EventLogTags.BROWSER_DOUBLE_TAP_DURATION,
4827                                (eventTime - mLastTouchUpTime), eventTime);
4828                    }
4829                    if (mSelectingText) {
4830                        mDrawSelectionPointer = false;
4831                        mSelectionStarted = nativeStartSelection(contentX, contentY);
4832                        if (DebugFlags.WEB_VIEW) {
4833                            Log.v(LOGTAG, "select=" + contentX + "," + contentY);
4834                        }
4835                        invalidate();
4836                    }
4837                }
4838                // Trigger the link
4839                if (mTouchMode == TOUCH_INIT_MODE
4840                        || mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
4841                    mPrivateHandler.sendEmptyMessageDelayed(
4842                            SWITCH_TO_SHORTPRESS, TAP_TIMEOUT);
4843                    mPrivateHandler.sendEmptyMessageDelayed(
4844                            SWITCH_TO_LONGPRESS, LONG_PRESS_TIMEOUT);
4845                    if (inFullScreenMode() || mDeferTouchProcess) {
4846                        mPreventDefault = PREVENT_DEFAULT_YES;
4847                    } else if (mForwardTouchEvents) {
4848                        mPreventDefault = PREVENT_DEFAULT_MAYBE_YES;
4849                    } else {
4850                        mPreventDefault = PREVENT_DEFAULT_NO;
4851                    }
4852                    // pass the touch events from UI thread to WebCore thread
4853                    if (shouldForwardTouchEvent()) {
4854                        TouchEventData ted = new TouchEventData();
4855                        ted.mAction = action;
4856                        ted.mX = contentX;
4857                        ted.mY = contentY;
4858                        ted.mMetaState = ev.getMetaState();
4859                        ted.mReprocess = mDeferTouchProcess;
4860                        mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
4861                        if (mDeferTouchProcess) {
4862                            // still needs to set them for compute deltaX/Y
4863                            mLastTouchX = x;
4864                            mLastTouchY = y;
4865                            break;
4866                        }
4867                        if (!inFullScreenMode()) {
4868                            mPrivateHandler.removeMessages(PREVENT_DEFAULT_TIMEOUT);
4869                            mPrivateHandler.sendMessageDelayed(mPrivateHandler
4870                                    .obtainMessage(PREVENT_DEFAULT_TIMEOUT,
4871                                            action, 0), TAP_TIMEOUT);
4872                        }
4873                    }
4874                }
4875                startTouch(x, y, eventTime);
4876                break;
4877            }
4878            case MotionEvent.ACTION_MOVE: {
4879                boolean firstMove = false;
4880                if (!mConfirmMove && (deltaX * deltaX + deltaY * deltaY)
4881                        >= mTouchSlopSquare) {
4882                    mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
4883                    mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
4884                    mConfirmMove = true;
4885                    firstMove = true;
4886                    if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
4887                        mTouchMode = TOUCH_INIT_MODE;
4888                    }
4889                    if (getSettings().supportTouchOnly()) {
4890                        removeTouchHighlight(true);
4891                    }
4892                }
4893                // pass the touch events from UI thread to WebCore thread
4894                if (shouldForwardTouchEvent() && mConfirmMove && (firstMove
4895                        || eventTime - mLastSentTouchTime > mCurrentTouchInterval)) {
4896                    TouchEventData ted = new TouchEventData();
4897                    ted.mAction = action;
4898                    ted.mX = contentX;
4899                    ted.mY = contentY;
4900                    ted.mMetaState = ev.getMetaState();
4901                    ted.mReprocess = mDeferTouchProcess;
4902                    mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
4903                    mLastSentTouchTime = eventTime;
4904                    if (mDeferTouchProcess) {
4905                        break;
4906                    }
4907                    if (firstMove && !inFullScreenMode()) {
4908                        mPrivateHandler.sendMessageDelayed(mPrivateHandler
4909                                .obtainMessage(PREVENT_DEFAULT_TIMEOUT,
4910                                        action, 0), TAP_TIMEOUT);
4911                    }
4912                }
4913                if (mTouchMode == TOUCH_DONE_MODE
4914                        || mPreventDefault == PREVENT_DEFAULT_YES) {
4915                    // no dragging during scroll zoom animation, or when prevent
4916                    // default is yes
4917                    break;
4918                }
4919                if (mVelocityTracker == null) {
4920                    Log.e(LOGTAG, "Got null mVelocityTracker when "
4921                            + "mPreventDefault = " + mPreventDefault
4922                            + " mDeferTouchProcess = " + mDeferTouchProcess
4923                            + " mTouchMode = " + mTouchMode);
4924                }
4925                mVelocityTracker.addMovement(ev);
4926                if (mSelectingText && mSelectionStarted) {
4927                    if (DebugFlags.WEB_VIEW) {
4928                        Log.v(LOGTAG, "extend=" + contentX + "," + contentY);
4929                    }
4930                    nativeExtendSelection(contentX, contentY);
4931                    invalidate();
4932                    break;
4933                }
4934
4935                if (mTouchMode != TOUCH_DRAG_MODE &&
4936                        mTouchMode != TOUCH_DRAG_LAYER_MODE) {
4937
4938                    if (!mConfirmMove) {
4939                        break;
4940                    }
4941
4942                    if (mPreventDefault == PREVENT_DEFAULT_MAYBE_YES
4943                            || mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN) {
4944                        // track mLastTouchTime as we may need to do fling at
4945                        // ACTION_UP
4946                        mLastTouchTime = eventTime;
4947                        break;
4948                    }
4949                    // if it starts nearly horizontal or vertical, enforce it
4950                    int ax = Math.abs(deltaX);
4951                    int ay = Math.abs(deltaY);
4952                    if (ax > MAX_SLOPE_FOR_DIAG * ay) {
4953                        mSnapScrollMode = SNAP_X;
4954                        mSnapPositive = deltaX > 0;
4955                    } else if (ay > MAX_SLOPE_FOR_DIAG * ax) {
4956                        mSnapScrollMode = SNAP_Y;
4957                        mSnapPositive = deltaY > 0;
4958                    }
4959
4960                    mTouchMode = TOUCH_DRAG_MODE;
4961                    mLastTouchX = x;
4962                    mLastTouchY = y;
4963                    fDeltaX = 0.0f;
4964                    fDeltaY = 0.0f;
4965                    deltaX = 0;
4966                    deltaY = 0;
4967
4968                    if (skipScaleGesture) {
4969                        startScrollingLayer(gestureX, gestureY);
4970                    }
4971                    startDrag();
4972                }
4973
4974                if (mDragTrackerHandler != null) {
4975                    mDragTrackerHandler.dragTo(x, y);
4976                }
4977
4978                // do pan
4979                if (mTouchMode != TOUCH_DRAG_LAYER_MODE) {
4980                    int newScrollX = pinLocX(mScrollX + deltaX);
4981                    int newDeltaX = newScrollX - mScrollX;
4982                    if (deltaX != newDeltaX) {
4983                        deltaX = newDeltaX;
4984                        fDeltaX = (float) newDeltaX;
4985                    }
4986                    int newScrollY = pinLocY(mScrollY + deltaY);
4987                    int newDeltaY = newScrollY - mScrollY;
4988                    if (deltaY != newDeltaY) {
4989                        deltaY = newDeltaY;
4990                        fDeltaY = (float) newDeltaY;
4991                    }
4992                }
4993                boolean done = false;
4994                boolean keepScrollBarsVisible = false;
4995                if (Math.abs(fDeltaX) < 1.0f && Math.abs(fDeltaY) < 1.0f) {
4996                    mLastTouchX = x;
4997                    mLastTouchY = y;
4998                    keepScrollBarsVisible = done = true;
4999                } else {
5000                    if (mSnapScrollMode == SNAP_X || mSnapScrollMode == SNAP_Y) {
5001                        int ax = Math.abs(deltaX);
5002                        int ay = Math.abs(deltaY);
5003                        if (mSnapScrollMode == SNAP_X) {
5004                            // radical change means getting out of snap mode
5005                            if (ay > MAX_SLOPE_FOR_DIAG * ax
5006                                    && ay > MIN_BREAK_SNAP_CROSS_DISTANCE) {
5007                                mSnapScrollMode = SNAP_NONE;
5008                            }
5009                            // reverse direction means lock in the snap mode
5010                            if (ax > MAX_SLOPE_FOR_DIAG * ay &&
5011                                    (mSnapPositive
5012                                    ? deltaX < -mMinLockSnapReverseDistance
5013                                    : deltaX > mMinLockSnapReverseDistance)) {
5014                                mSnapScrollMode |= SNAP_LOCK;
5015                            }
5016                        } else {
5017                            // radical change means getting out of snap mode
5018                            if (ax > MAX_SLOPE_FOR_DIAG * ay
5019                                    && ax > MIN_BREAK_SNAP_CROSS_DISTANCE) {
5020                                mSnapScrollMode = SNAP_NONE;
5021                            }
5022                            // reverse direction means lock in the snap mode
5023                            if (ay > MAX_SLOPE_FOR_DIAG * ax &&
5024                                    (mSnapPositive
5025                                    ? deltaY < -mMinLockSnapReverseDistance
5026                                    : deltaY > mMinLockSnapReverseDistance)) {
5027                                mSnapScrollMode |= SNAP_LOCK;
5028                            }
5029                        }
5030                    }
5031                    if (mSnapScrollMode != SNAP_NONE) {
5032                        if ((mSnapScrollMode & SNAP_X) == SNAP_X) {
5033                            deltaY = 0;
5034                        } else {
5035                            deltaX = 0;
5036                        }
5037                    }
5038                    if ((deltaX | deltaY) != 0) {
5039                        if (deltaX != 0) {
5040                            mLastTouchX = x;
5041                        }
5042                        if (deltaY != 0) {
5043                            mLastTouchY = y;
5044                        }
5045                        mHeldMotionless = MOTIONLESS_FALSE;
5046                    } else {
5047                        // keep the scrollbar on the screen even there is no
5048                        // scroll
5049                        mLastTouchX = x;
5050                        mLastTouchY = y;
5051                        keepScrollBarsVisible = true;
5052                    }
5053                    mLastTouchTime = eventTime;
5054                    mUserScroll = true;
5055                }
5056
5057                doDrag(deltaX, deltaY);
5058
5059                // Turn off scrollbars when dragging a layer.
5060                if (keepScrollBarsVisible &&
5061                        mTouchMode != TOUCH_DRAG_LAYER_MODE) {
5062                    if (mHeldMotionless != MOTIONLESS_TRUE) {
5063                        mHeldMotionless = MOTIONLESS_TRUE;
5064                        invalidate();
5065                    }
5066                    // keep the scrollbar on the screen even there is no scroll
5067                    awakenScrollBars(ViewConfiguration.getScrollDefaultDelay(),
5068                            false);
5069                    // return false to indicate that we can't pan out of the
5070                    // view space
5071                    return !done;
5072                }
5073                break;
5074            }
5075            case MotionEvent.ACTION_UP: {
5076                if (!isFocused()) requestFocus();
5077                // pass the touch events from UI thread to WebCore thread
5078                if (shouldForwardTouchEvent()) {
5079                    TouchEventData ted = new TouchEventData();
5080                    ted.mAction = action;
5081                    ted.mX = contentX;
5082                    ted.mY = contentY;
5083                    ted.mMetaState = ev.getMetaState();
5084                    ted.mReprocess = mDeferTouchProcess;
5085                    mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
5086                }
5087                mLastTouchUpTime = eventTime;
5088                switch (mTouchMode) {
5089                    case TOUCH_DOUBLE_TAP_MODE: // double tap
5090                        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
5091                        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
5092                        if (inFullScreenMode() || mDeferTouchProcess) {
5093                            TouchEventData ted = new TouchEventData();
5094                            ted.mAction = WebViewCore.ACTION_DOUBLETAP;
5095                            ted.mX = contentX;
5096                            ted.mY = contentY;
5097                            ted.mMetaState = ev.getMetaState();
5098                            ted.mReprocess = mDeferTouchProcess;
5099                            mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
5100                        } else if (mPreventDefault != PREVENT_DEFAULT_YES){
5101                            mZoomManager.handleDoubleTap(mLastTouchX, mLastTouchY);
5102                            mTouchMode = TOUCH_DONE_MODE;
5103                        }
5104                        break;
5105                    case TOUCH_INIT_MODE: // tap
5106                    case TOUCH_SHORTPRESS_START_MODE:
5107                    case TOUCH_SHORTPRESS_MODE:
5108                        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
5109                        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
5110                        if (mConfirmMove) {
5111                            Log.w(LOGTAG, "Miss a drag as we are waiting for" +
5112                                    " WebCore's response for touch down.");
5113                            if (mPreventDefault != PREVENT_DEFAULT_YES
5114                                    && (computeMaxScrollX() > 0
5115                                            || computeMaxScrollY() > 0)) {
5116                                // If the user has performed a very quick touch
5117                                // sequence it is possible that we may get here
5118                                // before WebCore has had a chance to process the events.
5119                                // In this case, any call to preventDefault in the
5120                                // JS touch handler will not have been executed yet.
5121                                // Hence we will see both the UI (now) and WebCore
5122                                // (when context switches) handling the event,
5123                                // regardless of whether the web developer actually
5124                                // doeses preventDefault in their touch handler. This
5125                                // is the nature of our asynchronous touch model.
5126
5127                                // we will not rewrite drag code here, but we
5128                                // will try fling if it applies.
5129                                WebViewCore.reducePriority();
5130                                // to get better performance, pause updating the
5131                                // picture
5132                                WebViewCore.pauseUpdatePicture(mWebViewCore);
5133                                // fall through to TOUCH_DRAG_MODE
5134                            } else {
5135                                // WebKit may consume the touch event and modify
5136                                // DOM. drawContentPicture() will be called with
5137                                // animateSroll as true for better performance.
5138                                // Force redraw in high-quality.
5139                                invalidate();
5140                                break;
5141                            }
5142                        } else {
5143                            if (mSelectingText) {
5144                                // tapping on selection or controls does nothing
5145                                if (!nativeHitSelection(contentX, contentY)) {
5146                                    selectionDone();
5147                                }
5148                                break;
5149                            }
5150                            // only trigger double tap if the WebView is
5151                            // scalable
5152                            if (mTouchMode == TOUCH_INIT_MODE
5153                                    && (canZoomIn() || canZoomOut())) {
5154                                mPrivateHandler.sendEmptyMessageDelayed(
5155                                        RELEASE_SINGLE_TAP, ViewConfiguration
5156                                                .getDoubleTapTimeout());
5157                            } else {
5158                                doShortPress();
5159                            }
5160                            break;
5161                        }
5162                    case TOUCH_DRAG_MODE:
5163                        mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
5164                        mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS);
5165                        // if the user waits a while w/o moving before the
5166                        // up, we don't want to do a fling
5167                        if (eventTime - mLastTouchTime <= MIN_FLING_TIME) {
5168                            if (mVelocityTracker == null) {
5169                                Log.e(LOGTAG, "Got null mVelocityTracker when "
5170                                        + "mPreventDefault = "
5171                                        + mPreventDefault
5172                                        + " mDeferTouchProcess = "
5173                                        + mDeferTouchProcess);
5174                            }
5175                            mVelocityTracker.addMovement(ev);
5176                            // set to MOTIONLESS_IGNORE so that it won't keep
5177                            // removing and sending message in
5178                            // drawCoreAndCursorRing()
5179                            mHeldMotionless = MOTIONLESS_IGNORE;
5180                            doFling();
5181                            break;
5182                        }
5183                        // redraw in high-quality, as we're done dragging
5184                        mHeldMotionless = MOTIONLESS_TRUE;
5185                        invalidate();
5186                        // fall through
5187                    case TOUCH_DRAG_START_MODE:
5188                    case TOUCH_DRAG_LAYER_MODE:
5189                        // TOUCH_DRAG_START_MODE should not happen for the real
5190                        // device as we almost certain will get a MOVE. But this
5191                        // is possible on emulator.
5192                        mLastVelocity = 0;
5193                        WebViewCore.resumePriority();
5194                        WebViewCore.resumeUpdatePicture(mWebViewCore);
5195                        break;
5196                }
5197                stopTouch();
5198                break;
5199            }
5200            case MotionEvent.ACTION_CANCEL: {
5201                if (mTouchMode == TOUCH_DRAG_MODE) {
5202                    invalidate();
5203                }
5204                cancelWebCoreTouchEvent(contentX, contentY, false);
5205                cancelTouch();
5206                break;
5207            }
5208        }
5209        return true;
5210    }
5211
5212    private void cancelWebCoreTouchEvent(int x, int y, boolean removeEvents) {
5213        if (shouldForwardTouchEvent()) {
5214            if (removeEvents) {
5215                mWebViewCore.removeMessages(EventHub.TOUCH_EVENT);
5216            }
5217            TouchEventData ted = new TouchEventData();
5218            ted.mX = x;
5219            ted.mY = y;
5220            ted.mAction = MotionEvent.ACTION_CANCEL;
5221            mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
5222            mPreventDefault = PREVENT_DEFAULT_IGNORE;
5223        }
5224    }
5225
5226    private void startTouch(float x, float y, long eventTime) {
5227        // Remember where the motion event started
5228        mLastTouchX = x;
5229        mLastTouchY = y;
5230        mLastTouchTime = eventTime;
5231        mVelocityTracker = VelocityTracker.obtain();
5232        mSnapScrollMode = SNAP_NONE;
5233        if (mDragTracker != null) {
5234            mDragTrackerHandler = new DragTrackerHandler(x, y, mDragTracker);
5235        }
5236    }
5237
5238    private void startDrag() {
5239        WebViewCore.reducePriority();
5240        // to get better performance, pause updating the picture
5241        WebViewCore.pauseUpdatePicture(mWebViewCore);
5242        if (!mDragFromTextInput) {
5243            nativeHideCursor();
5244        }
5245
5246        if (mHorizontalScrollBarMode != SCROLLBAR_ALWAYSOFF
5247                || mVerticalScrollBarMode != SCROLLBAR_ALWAYSOFF) {
5248            mZoomManager.invokeZoomPicker();
5249        }
5250    }
5251
5252    private void doDrag(int deltaX, int deltaY) {
5253        if ((deltaX | deltaY) != 0) {
5254            if (mTouchMode == TOUCH_DRAG_LAYER_MODE) {
5255                deltaX = viewToContentDimension(deltaX);
5256                deltaY = viewToContentDimension(deltaY);
5257                if (nativeScrollLayer(mScrollingLayer, deltaX, deltaY)) {
5258                    invalidate();
5259                }
5260                return;
5261            }
5262            scrollBy(deltaX, deltaY);
5263        }
5264        mZoomManager.keepZoomPickerVisible();
5265    }
5266
5267    private void stopTouch() {
5268        if (mDragTrackerHandler != null) {
5269            mDragTrackerHandler.stopDrag();
5270        }
5271        // we also use mVelocityTracker == null to tell us that we are
5272        // not "moving around", so we can take the slower/prettier
5273        // mode in the drawing code
5274        if (mVelocityTracker != null) {
5275            mVelocityTracker.recycle();
5276            mVelocityTracker = null;
5277        }
5278    }
5279
5280    private void cancelTouch() {
5281        if (mDragTrackerHandler != null) {
5282            mDragTrackerHandler.stopDrag();
5283        }
5284        // we also use mVelocityTracker == null to tell us that we are
5285        // not "moving around", so we can take the slower/prettier
5286        // mode in the drawing code
5287        if (mVelocityTracker != null) {
5288            mVelocityTracker.recycle();
5289            mVelocityTracker = null;
5290        }
5291        if (mTouchMode == TOUCH_DRAG_MODE ||
5292                mTouchMode == TOUCH_DRAG_LAYER_MODE) {
5293            WebViewCore.resumePriority();
5294            WebViewCore.resumeUpdatePicture(mWebViewCore);
5295        }
5296        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
5297        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
5298        mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
5299        mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS);
5300        if (getSettings().supportTouchOnly()) {
5301            removeTouchHighlight(true);
5302        }
5303        mHeldMotionless = MOTIONLESS_TRUE;
5304        mTouchMode = TOUCH_DONE_MODE;
5305        nativeHideCursor();
5306    }
5307
5308    private long mTrackballFirstTime = 0;
5309    private long mTrackballLastTime = 0;
5310    private float mTrackballRemainsX = 0.0f;
5311    private float mTrackballRemainsY = 0.0f;
5312    private int mTrackballXMove = 0;
5313    private int mTrackballYMove = 0;
5314    private boolean mSelectingText = false;
5315    private boolean mSelectionStarted = false;
5316    private boolean mExtendSelection = false;
5317    private boolean mDrawSelectionPointer = false;
5318    private static final int TRACKBALL_KEY_TIMEOUT = 1000;
5319    private static final int TRACKBALL_TIMEOUT = 200;
5320    private static final int TRACKBALL_WAIT = 100;
5321    private static final int TRACKBALL_SCALE = 400;
5322    private static final int TRACKBALL_SCROLL_COUNT = 5;
5323    private static final int TRACKBALL_MOVE_COUNT = 10;
5324    private static final int TRACKBALL_MULTIPLIER = 3;
5325    private static final int SELECT_CURSOR_OFFSET = 16;
5326    private int mSelectX = 0;
5327    private int mSelectY = 0;
5328    private boolean mFocusSizeChanged = false;
5329    private boolean mShiftIsPressed = false;
5330    private boolean mTrackballDown = false;
5331    private long mTrackballUpTime = 0;
5332    private long mLastCursorTime = 0;
5333    private Rect mLastCursorBounds;
5334
5335    // Set by default; BrowserActivity clears to interpret trackball data
5336    // directly for movement. Currently, the framework only passes
5337    // arrow key events, not trackball events, from one child to the next
5338    private boolean mMapTrackballToArrowKeys = true;
5339
5340    public void setMapTrackballToArrowKeys(boolean setMap) {
5341        mMapTrackballToArrowKeys = setMap;
5342    }
5343
5344    void resetTrackballTime() {
5345        mTrackballLastTime = 0;
5346    }
5347
5348    @Override
5349    public boolean onTrackballEvent(MotionEvent ev) {
5350        long time = ev.getEventTime();
5351        if ((ev.getMetaState() & KeyEvent.META_ALT_ON) != 0) {
5352            if (ev.getY() > 0) pageDown(true);
5353            if (ev.getY() < 0) pageUp(true);
5354            return true;
5355        }
5356        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
5357            if (mSelectingText) {
5358                return true; // discard press if copy in progress
5359            }
5360            mTrackballDown = true;
5361            if (mNativeClass == 0) {
5362                return false;
5363            }
5364            nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true);
5365            if (time - mLastCursorTime <= TRACKBALL_TIMEOUT
5366                    && !mLastCursorBounds.equals(nativeGetCursorRingBounds())) {
5367                nativeSelectBestAt(mLastCursorBounds);
5368            }
5369            if (DebugFlags.WEB_VIEW) {
5370                Log.v(LOGTAG, "onTrackballEvent down ev=" + ev
5371                        + " time=" + time
5372                        + " mLastCursorTime=" + mLastCursorTime);
5373            }
5374            if (isInTouchMode()) requestFocusFromTouch();
5375            return false; // let common code in onKeyDown at it
5376        }
5377        if (ev.getAction() == MotionEvent.ACTION_UP) {
5378            // LONG_PRESS_CENTER is set in common onKeyDown
5379            mPrivateHandler.removeMessages(LONG_PRESS_CENTER);
5380            mTrackballDown = false;
5381            mTrackballUpTime = time;
5382            if (mSelectingText) {
5383                if (mExtendSelection) {
5384                    copySelection();
5385                    selectionDone();
5386                } else {
5387                    mExtendSelection = true;
5388                    nativeSetExtendSelection();
5389                    invalidate(); // draw the i-beam instead of the arrow
5390                }
5391                return true; // discard press if copy in progress
5392            }
5393            if (DebugFlags.WEB_VIEW) {
5394                Log.v(LOGTAG, "onTrackballEvent up ev=" + ev
5395                        + " time=" + time
5396                );
5397            }
5398            return false; // let common code in onKeyUp at it
5399        }
5400        if (mMapTrackballToArrowKeys && mShiftIsPressed == false) {
5401            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent gmail quit");
5402            return false;
5403        }
5404        if (mTrackballDown) {
5405            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent down quit");
5406            return true; // discard move if trackball is down
5407        }
5408        if (time - mTrackballUpTime < TRACKBALL_TIMEOUT) {
5409            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent up timeout quit");
5410            return true;
5411        }
5412        // TODO: alternatively we can do panning as touch does
5413        switchOutDrawHistory();
5414        if (time - mTrackballLastTime > TRACKBALL_TIMEOUT) {
5415            if (DebugFlags.WEB_VIEW) {
5416                Log.v(LOGTAG, "onTrackballEvent time="
5417                        + time + " last=" + mTrackballLastTime);
5418            }
5419            mTrackballFirstTime = time;
5420            mTrackballXMove = mTrackballYMove = 0;
5421        }
5422        mTrackballLastTime = time;
5423        if (DebugFlags.WEB_VIEW) {
5424            Log.v(LOGTAG, "onTrackballEvent ev=" + ev + " time=" + time);
5425        }
5426        mTrackballRemainsX += ev.getX();
5427        mTrackballRemainsY += ev.getY();
5428        doTrackball(time);
5429        return true;
5430    }
5431
5432    void moveSelection(float xRate, float yRate) {
5433        if (mNativeClass == 0)
5434            return;
5435        int width = getViewWidth();
5436        int height = getViewHeight();
5437        mSelectX += xRate;
5438        mSelectY += yRate;
5439        int maxX = width + mScrollX;
5440        int maxY = height + mScrollY;
5441        mSelectX = Math.min(maxX, Math.max(mScrollX - SELECT_CURSOR_OFFSET
5442                , mSelectX));
5443        mSelectY = Math.min(maxY, Math.max(mScrollY - SELECT_CURSOR_OFFSET
5444                , mSelectY));
5445        if (DebugFlags.WEB_VIEW) {
5446            Log.v(LOGTAG, "moveSelection"
5447                    + " mSelectX=" + mSelectX
5448                    + " mSelectY=" + mSelectY
5449                    + " mScrollX=" + mScrollX
5450                    + " mScrollY=" + mScrollY
5451                    + " xRate=" + xRate
5452                    + " yRate=" + yRate
5453                    );
5454        }
5455        nativeMoveSelection(viewToContentX(mSelectX), viewToContentY(mSelectY));
5456        int scrollX = mSelectX < mScrollX ? -SELECT_CURSOR_OFFSET
5457                : mSelectX > maxX - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET
5458                : 0;
5459        int scrollY = mSelectY < mScrollY ? -SELECT_CURSOR_OFFSET
5460                : mSelectY > maxY - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET
5461                : 0;
5462        pinScrollBy(scrollX, scrollY, true, 0);
5463        Rect select = new Rect(mSelectX, mSelectY, mSelectX + 1, mSelectY + 1);
5464        requestRectangleOnScreen(select);
5465        invalidate();
5466   }
5467
5468    private int scaleTrackballX(float xRate, int width) {
5469        int xMove = (int) (xRate / TRACKBALL_SCALE * width);
5470        int nextXMove = xMove;
5471        if (xMove > 0) {
5472            if (xMove > mTrackballXMove) {
5473                xMove -= mTrackballXMove;
5474            }
5475        } else if (xMove < mTrackballXMove) {
5476            xMove -= mTrackballXMove;
5477        }
5478        mTrackballXMove = nextXMove;
5479        return xMove;
5480    }
5481
5482    private int scaleTrackballY(float yRate, int height) {
5483        int yMove = (int) (yRate / TRACKBALL_SCALE * height);
5484        int nextYMove = yMove;
5485        if (yMove > 0) {
5486            if (yMove > mTrackballYMove) {
5487                yMove -= mTrackballYMove;
5488            }
5489        } else if (yMove < mTrackballYMove) {
5490            yMove -= mTrackballYMove;
5491        }
5492        mTrackballYMove = nextYMove;
5493        return yMove;
5494    }
5495
5496    private int keyCodeToSoundsEffect(int keyCode) {
5497        switch(keyCode) {
5498            case KeyEvent.KEYCODE_DPAD_UP:
5499                return SoundEffectConstants.NAVIGATION_UP;
5500            case KeyEvent.KEYCODE_DPAD_RIGHT:
5501                return SoundEffectConstants.NAVIGATION_RIGHT;
5502            case KeyEvent.KEYCODE_DPAD_DOWN:
5503                return SoundEffectConstants.NAVIGATION_DOWN;
5504            case KeyEvent.KEYCODE_DPAD_LEFT:
5505                return SoundEffectConstants.NAVIGATION_LEFT;
5506        }
5507        throw new IllegalArgumentException("keyCode must be one of " +
5508                "{KEYCODE_DPAD_UP, KEYCODE_DPAD_RIGHT, KEYCODE_DPAD_DOWN, " +
5509                "KEYCODE_DPAD_LEFT}.");
5510    }
5511
5512    private void doTrackball(long time) {
5513        int elapsed = (int) (mTrackballLastTime - mTrackballFirstTime);
5514        if (elapsed == 0) {
5515            elapsed = TRACKBALL_TIMEOUT;
5516        }
5517        float xRate = mTrackballRemainsX * 1000 / elapsed;
5518        float yRate = mTrackballRemainsY * 1000 / elapsed;
5519        int viewWidth = getViewWidth();
5520        int viewHeight = getViewHeight();
5521        if (mSelectingText) {
5522            if (!mDrawSelectionPointer) {
5523                // The last selection was made by touch, disabling drawing the
5524                // selection pointer. Allow the trackball to adjust the
5525                // position of the touch control.
5526                mSelectX = contentToViewX(nativeSelectionX());
5527                mSelectY = contentToViewY(nativeSelectionY());
5528                mDrawSelectionPointer = mExtendSelection = true;
5529                nativeSetExtendSelection();
5530            }
5531            moveSelection(scaleTrackballX(xRate, viewWidth),
5532                    scaleTrackballY(yRate, viewHeight));
5533            mTrackballRemainsX = mTrackballRemainsY = 0;
5534            return;
5535        }
5536        float ax = Math.abs(xRate);
5537        float ay = Math.abs(yRate);
5538        float maxA = Math.max(ax, ay);
5539        if (DebugFlags.WEB_VIEW) {
5540            Log.v(LOGTAG, "doTrackball elapsed=" + elapsed
5541                    + " xRate=" + xRate
5542                    + " yRate=" + yRate
5543                    + " mTrackballRemainsX=" + mTrackballRemainsX
5544                    + " mTrackballRemainsY=" + mTrackballRemainsY);
5545        }
5546        int width = mContentWidth - viewWidth;
5547        int height = mContentHeight - viewHeight;
5548        if (width < 0) width = 0;
5549        if (height < 0) height = 0;
5550        ax = Math.abs(mTrackballRemainsX * TRACKBALL_MULTIPLIER);
5551        ay = Math.abs(mTrackballRemainsY * TRACKBALL_MULTIPLIER);
5552        maxA = Math.max(ax, ay);
5553        int count = Math.max(0, (int) maxA);
5554        int oldScrollX = mScrollX;
5555        int oldScrollY = mScrollY;
5556        if (count > 0) {
5557            int selectKeyCode = ax < ay ? mTrackballRemainsY < 0 ?
5558                    KeyEvent.KEYCODE_DPAD_UP : KeyEvent.KEYCODE_DPAD_DOWN :
5559                    mTrackballRemainsX < 0 ? KeyEvent.KEYCODE_DPAD_LEFT :
5560                    KeyEvent.KEYCODE_DPAD_RIGHT;
5561            count = Math.min(count, TRACKBALL_MOVE_COUNT);
5562            if (DebugFlags.WEB_VIEW) {
5563                Log.v(LOGTAG, "doTrackball keyCode=" + selectKeyCode
5564                        + " count=" + count
5565                        + " mTrackballRemainsX=" + mTrackballRemainsX
5566                        + " mTrackballRemainsY=" + mTrackballRemainsY);
5567            }
5568            if (mNativeClass != 0 && nativePageShouldHandleShiftAndArrows()) {
5569                for (int i = 0; i < count; i++) {
5570                    letPageHandleNavKey(selectKeyCode, time, true);
5571                }
5572                letPageHandleNavKey(selectKeyCode, time, false);
5573            } else if (navHandledKey(selectKeyCode, count, false, time)) {
5574                playSoundEffect(keyCodeToSoundsEffect(selectKeyCode));
5575            }
5576            mTrackballRemainsX = mTrackballRemainsY = 0;
5577        }
5578        if (count >= TRACKBALL_SCROLL_COUNT) {
5579            int xMove = scaleTrackballX(xRate, width);
5580            int yMove = scaleTrackballY(yRate, height);
5581            if (DebugFlags.WEB_VIEW) {
5582                Log.v(LOGTAG, "doTrackball pinScrollBy"
5583                        + " count=" + count
5584                        + " xMove=" + xMove + " yMove=" + yMove
5585                        + " mScrollX-oldScrollX=" + (mScrollX-oldScrollX)
5586                        + " mScrollY-oldScrollY=" + (mScrollY-oldScrollY)
5587                        );
5588            }
5589            if (Math.abs(mScrollX - oldScrollX) > Math.abs(xMove)) {
5590                xMove = 0;
5591            }
5592            if (Math.abs(mScrollY - oldScrollY) > Math.abs(yMove)) {
5593                yMove = 0;
5594            }
5595            if (xMove != 0 || yMove != 0) {
5596                pinScrollBy(xMove, yMove, true, 0);
5597            }
5598            mUserScroll = true;
5599        }
5600    }
5601
5602    private int computeMaxScrollX() {
5603        return Math.max(computeHorizontalScrollRange() - getViewWidth(), 0);
5604    }
5605
5606    private int computeMaxScrollY() {
5607        return Math.max(computeVerticalScrollRange() + getTitleHeight()
5608                - getViewHeightWithTitle(), 0);
5609    }
5610
5611    boolean updateScrollCoordinates(int x, int y) {
5612        int oldX = mScrollX;
5613        int oldY = mScrollY;
5614        mScrollX = x;
5615        mScrollY = y;
5616        if (oldX != mScrollX || oldY != mScrollY) {
5617            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
5618            return true;
5619        } else {
5620            return false;
5621        }
5622    }
5623
5624    public void flingScroll(int vx, int vy) {
5625        mScroller.fling(mScrollX, mScrollY, vx, vy, 0, computeMaxScrollX(), 0,
5626                computeMaxScrollY());
5627        invalidate();
5628    }
5629
5630    private void doFling() {
5631        if (mVelocityTracker == null) {
5632            return;
5633        }
5634        int maxX = computeMaxScrollX();
5635        int maxY = computeMaxScrollY();
5636
5637        mVelocityTracker.computeCurrentVelocity(1000, mMaximumFling);
5638        int vx = (int) mVelocityTracker.getXVelocity();
5639        int vy = (int) mVelocityTracker.getYVelocity();
5640
5641        if (mSnapScrollMode != SNAP_NONE) {
5642            if ((mSnapScrollMode & SNAP_X) == SNAP_X) {
5643                vy = 0;
5644            } else {
5645                vx = 0;
5646            }
5647        }
5648        if (true /* EMG release: make our fling more like Maps' */) {
5649            // maps cuts their velocity in half
5650            vx = vx * 3 / 4;
5651            vy = vy * 3 / 4;
5652        }
5653        if ((maxX == 0 && vy == 0) || (maxY == 0 && vx == 0)) {
5654            WebViewCore.resumePriority();
5655            WebViewCore.resumeUpdatePicture(mWebViewCore);
5656            return;
5657        }
5658        float currentVelocity = mScroller.getCurrVelocity();
5659        float velocity = (float) Math.hypot(vx, vy);
5660        if (mLastVelocity > 0 && currentVelocity > 0 && velocity
5661                > mLastVelocity * MINIMUM_VELOCITY_RATIO_FOR_ACCELERATION) {
5662            float deltaR = (float) (Math.abs(Math.atan2(mLastVelY, mLastVelX)
5663                    - Math.atan2(vy, vx)));
5664            final float circle = (float) (Math.PI) * 2.0f;
5665            if (deltaR > circle * 0.9f || deltaR < circle * 0.1f) {
5666                vx += currentVelocity * mLastVelX / mLastVelocity;
5667                vy += currentVelocity * mLastVelY / mLastVelocity;
5668                velocity = (float) Math.hypot(vx, vy);
5669                if (DebugFlags.WEB_VIEW) {
5670                    Log.v(LOGTAG, "doFling vx= " + vx + " vy=" + vy);
5671                }
5672            } else if (DebugFlags.WEB_VIEW) {
5673                Log.v(LOGTAG, "doFling missed " + deltaR / circle);
5674            }
5675        } else if (DebugFlags.WEB_VIEW) {
5676            Log.v(LOGTAG, "doFling start last=" + mLastVelocity
5677                    + " current=" + currentVelocity
5678                    + " vx=" + vx + " vy=" + vy
5679                    + " maxX=" + maxX + " maxY=" + maxY
5680                    + " mScrollX=" + mScrollX + " mScrollY=" + mScrollY);
5681        }
5682        mLastVelX = vx;
5683        mLastVelY = vy;
5684        mLastVelocity = velocity;
5685
5686        mScroller.fling(mScrollX, mScrollY, -vx, -vy, 0, maxX, 0, maxY);
5687        final int time = mScroller.getDuration();
5688        mPrivateHandler.sendEmptyMessageDelayed(RESUME_WEBCORE_PRIORITY, time);
5689        awakenScrollBars(time);
5690        invalidate();
5691    }
5692
5693    /**
5694     * Returns a view containing zoom controls i.e. +/- buttons. The caller is
5695     * in charge of installing this view to the view hierarchy. This view will
5696     * become visible when the user starts scrolling via touch and fade away if
5697     * the user does not interact with it.
5698     * <p/>
5699     * API version 3 introduces a built-in zoom mechanism that is shown
5700     * automatically by the MapView. This is the preferred approach for
5701     * showing the zoom UI.
5702     *
5703     * @deprecated The built-in zoom mechanism is preferred, see
5704     *             {@link WebSettings#setBuiltInZoomControls(boolean)}.
5705     */
5706    @Deprecated
5707    public View getZoomControls() {
5708        if (!getSettings().supportZoom()) {
5709            Log.w(LOGTAG, "This WebView doesn't support zoom.");
5710            return null;
5711        }
5712        return mZoomManager.getExternalZoomPicker();
5713    }
5714
5715    void dismissZoomControl() {
5716        mZoomManager.dismissZoomPicker();
5717    }
5718
5719    float getDefaultZoomScale() {
5720        return mZoomManager.getDefaultScale();
5721    }
5722
5723    /**
5724     * @return TRUE if the WebView can be zoomed in.
5725     */
5726    public boolean canZoomIn() {
5727        return mZoomManager.canZoomIn();
5728    }
5729
5730    /**
5731     * @return TRUE if the WebView can be zoomed out.
5732     */
5733    public boolean canZoomOut() {
5734        return mZoomManager.canZoomOut();
5735    }
5736
5737    /**
5738     * Perform zoom in in the webview
5739     * @return TRUE if zoom in succeeds. FALSE if no zoom changes.
5740     */
5741    public boolean zoomIn() {
5742        return mZoomManager.zoomIn();
5743    }
5744
5745    /**
5746     * Perform zoom out in the webview
5747     * @return TRUE if zoom out succeeds. FALSE if no zoom changes.
5748     */
5749    public boolean zoomOut() {
5750        return mZoomManager.zoomOut();
5751    }
5752
5753    private void updateSelection() {
5754        if (mNativeClass == 0) {
5755            return;
5756        }
5757        // mLastTouchX and mLastTouchY are the point in the current viewport
5758        int contentX = viewToContentX((int) mLastTouchX + mScrollX);
5759        int contentY = viewToContentY((int) mLastTouchY + mScrollY);
5760        Rect rect = new Rect(contentX - mNavSlop, contentY - mNavSlop,
5761                contentX + mNavSlop, contentY + mNavSlop);
5762        nativeSelectBestAt(rect);
5763    }
5764
5765    /**
5766     * Scroll the focused text field/area to match the WebTextView
5767     * @param xPercent New x position of the WebTextView from 0 to 1.
5768     * @param y New y position of the WebTextView in view coordinates
5769     */
5770    /*package*/ void scrollFocusedTextInput(float xPercent, int y) {
5771        if (!inEditingMode() || mWebViewCore == null) {
5772            return;
5773        }
5774        mWebViewCore.sendMessage(EventHub.SCROLL_TEXT_INPUT,
5775                // Since this position is relative to the top of the text input
5776                // field, we do not need to take the title bar's height into
5777                // consideration.
5778                viewToContentDimension(y),
5779                new Float(xPercent));
5780    }
5781
5782    /**
5783     * Set our starting point and time for a drag from the WebTextView.
5784     */
5785    /*package*/ void initiateTextFieldDrag(float x, float y, long eventTime) {
5786        if (!inEditingMode()) {
5787            return;
5788        }
5789        mLastTouchX = x + (float) (mWebTextView.getLeft() - mScrollX);
5790        mLastTouchY = y + (float) (mWebTextView.getTop() - mScrollY);
5791        mLastTouchTime = eventTime;
5792        if (!mScroller.isFinished()) {
5793            abortAnimation();
5794            mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY);
5795        }
5796        mSnapScrollMode = SNAP_NONE;
5797        mVelocityTracker = VelocityTracker.obtain();
5798        mTouchMode = TOUCH_DRAG_START_MODE;
5799    }
5800
5801    /**
5802     * Given a motion event from the WebTextView, set its location to our
5803     * coordinates, and handle the event.
5804     */
5805    /*package*/ boolean textFieldDrag(MotionEvent event) {
5806        if (!inEditingMode()) {
5807            return false;
5808        }
5809        mDragFromTextInput = true;
5810        event.offsetLocation((float) (mWebTextView.getLeft() - mScrollX),
5811                (float) (mWebTextView.getTop() - mScrollY));
5812        boolean result = onTouchEvent(event);
5813        mDragFromTextInput = false;
5814        return result;
5815    }
5816
5817    /**
5818     * Due a touch up from a WebTextView.  This will be handled by webkit to
5819     * change the selection.
5820     * @param event MotionEvent in the WebTextView's coordinates.
5821     */
5822    /*package*/ void touchUpOnTextField(MotionEvent event) {
5823        if (!inEditingMode()) {
5824            return;
5825        }
5826        int x = viewToContentX((int) event.getX() + mWebTextView.getLeft());
5827        int y = viewToContentY((int) event.getY() + mWebTextView.getTop());
5828        nativeMotionUp(x, y, mNavSlop);
5829    }
5830
5831    /**
5832     * Called when pressing the center key or trackball on a textfield.
5833     */
5834    /*package*/ void centerKeyPressOnTextField() {
5835        mWebViewCore.sendMessage(EventHub.CLICK, nativeCursorFramePointer(),
5836                    nativeCursorNodePointer());
5837    }
5838
5839    private void doShortPress() {
5840        if (mNativeClass == 0) {
5841            return;
5842        }
5843        if (mPreventDefault == PREVENT_DEFAULT_YES) {
5844            return;
5845        }
5846        mTouchMode = TOUCH_DONE_MODE;
5847        switchOutDrawHistory();
5848        // mLastTouchX and mLastTouchY are the point in the current viewport
5849        int contentX = viewToContentX((int) mLastTouchX + mScrollX);
5850        int contentY = viewToContentY((int) mLastTouchY + mScrollY);
5851        if (getSettings().supportTouchOnly()) {
5852            removeTouchHighlight(false);
5853            WebViewCore.TouchUpData touchUpData = new WebViewCore.TouchUpData();
5854            // use "0" as generation id to inform WebKit to use the same x/y as
5855            // it used when processing GET_TOUCH_HIGHLIGHT_RECTS
5856            touchUpData.mMoveGeneration = 0;
5857            mWebViewCore.sendMessage(EventHub.TOUCH_UP, touchUpData);
5858        } else if (nativePointInNavCache(contentX, contentY, mNavSlop)) {
5859            WebViewCore.MotionUpData motionUpData = new WebViewCore
5860                    .MotionUpData();
5861            motionUpData.mFrame = nativeCacheHitFramePointer();
5862            motionUpData.mNode = nativeCacheHitNodePointer();
5863            motionUpData.mBounds = nativeCacheHitNodeBounds();
5864            motionUpData.mX = contentX;
5865            motionUpData.mY = contentY;
5866            mWebViewCore.sendMessageAtFrontOfQueue(EventHub.VALID_NODE_BOUNDS,
5867                    motionUpData);
5868        } else {
5869            doMotionUp(contentX, contentY);
5870        }
5871    }
5872
5873    private void doMotionUp(int contentX, int contentY) {
5874        if (mLogEvent && nativeMotionUp(contentX, contentY, mNavSlop)) {
5875            EventLog.writeEvent(EventLogTags.BROWSER_SNAP_CENTER);
5876        }
5877        if (nativeHasCursorNode() && !nativeCursorIsTextInput()) {
5878            playSoundEffect(SoundEffectConstants.CLICK);
5879        }
5880    }
5881
5882    /*
5883     * Return true if the view (Plugin) is fully visible and maximized inside
5884     * the WebView.
5885     */
5886    boolean isPluginFitOnScreen(ViewManager.ChildView view) {
5887        final int viewWidth = getViewWidth();
5888        final int viewHeight = getViewHeightWithTitle();
5889        float scale = Math.min((float) viewWidth / view.width, (float) viewHeight / view.height);
5890        scale = mZoomManager.computeScaleWithLimits(scale);
5891        return !mZoomManager.willScaleTriggerZoom(scale)
5892                && contentToViewX(view.x) >= mScrollX
5893                && contentToViewX(view.x + view.width) <= mScrollX + viewWidth
5894                && contentToViewY(view.y) >= mScrollY
5895                && contentToViewY(view.y + view.height) <= mScrollY + viewHeight;
5896    }
5897
5898    /*
5899     * Maximize and center the rectangle, specified in the document coordinate
5900     * space, inside the WebView. If the zoom doesn't need to be changed, do an
5901     * animated scroll to center it. If the zoom needs to be changed, find the
5902     * zoom center and do a smooth zoom transition.
5903     */
5904    void centerFitRect(int docX, int docY, int docWidth, int docHeight) {
5905        int viewWidth = getViewWidth();
5906        int viewHeight = getViewHeightWithTitle();
5907        float scale = Math.min((float) viewWidth / docWidth, (float) viewHeight
5908                / docHeight);
5909        scale = mZoomManager.computeScaleWithLimits(scale);
5910        if (!mZoomManager.willScaleTriggerZoom(scale)) {
5911            pinScrollTo(contentToViewX(docX + docWidth / 2) - viewWidth / 2,
5912                    contentToViewY(docY + docHeight / 2) - viewHeight / 2,
5913                    true, 0);
5914        } else {
5915            float actualScale = mZoomManager.getScale();
5916            float oldScreenX = docX * actualScale - mScrollX;
5917            float rectViewX = docX * scale;
5918            float rectViewWidth = docWidth * scale;
5919            float newMaxWidth = mContentWidth * scale;
5920            float newScreenX = (viewWidth - rectViewWidth) / 2;
5921            // pin the newX to the WebView
5922            if (newScreenX > rectViewX) {
5923                newScreenX = rectViewX;
5924            } else if (newScreenX > (newMaxWidth - rectViewX - rectViewWidth)) {
5925                newScreenX = viewWidth - (newMaxWidth - rectViewX);
5926            }
5927            float zoomCenterX = (oldScreenX * scale - newScreenX * actualScale)
5928                    / (scale - actualScale);
5929            float oldScreenY = docY * actualScale + getTitleHeight()
5930                    - mScrollY;
5931            float rectViewY = docY * scale + getTitleHeight();
5932            float rectViewHeight = docHeight * scale;
5933            float newMaxHeight = mContentHeight * scale + getTitleHeight();
5934            float newScreenY = (viewHeight - rectViewHeight) / 2;
5935            // pin the newY to the WebView
5936            if (newScreenY > rectViewY) {
5937                newScreenY = rectViewY;
5938            } else if (newScreenY > (newMaxHeight - rectViewY - rectViewHeight)) {
5939                newScreenY = viewHeight - (newMaxHeight - rectViewY);
5940            }
5941            float zoomCenterY = (oldScreenY * scale - newScreenY * actualScale)
5942                    / (scale - actualScale);
5943            mZoomManager.setZoomCenter(zoomCenterX, zoomCenterY);
5944            mZoomManager.startZoomAnimation(scale, false);
5945        }
5946    }
5947
5948    // Called by JNI to handle a touch on a node representing an email address,
5949    // address, or phone number
5950    private void overrideLoading(String url) {
5951        mCallbackProxy.uiOverrideUrlLoading(url);
5952    }
5953
5954    @Override
5955    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
5956        // FIXME: If a subwindow is showing find, and the user touches the
5957        // background window, it can steal focus.
5958        if (mFindIsUp) return false;
5959        boolean result = false;
5960        if (inEditingMode()) {
5961            result = mWebTextView.requestFocus(direction,
5962                    previouslyFocusedRect);
5963        } else {
5964            result = super.requestFocus(direction, previouslyFocusedRect);
5965            if (mWebViewCore.getSettings().getNeedInitialFocus()) {
5966                // For cases such as GMail, where we gain focus from a direction,
5967                // we want to move to the first available link.
5968                // FIXME: If there are no visible links, we may not want to
5969                int fakeKeyDirection = 0;
5970                switch(direction) {
5971                    case View.FOCUS_UP:
5972                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_UP;
5973                        break;
5974                    case View.FOCUS_DOWN:
5975                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_DOWN;
5976                        break;
5977                    case View.FOCUS_LEFT:
5978                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_LEFT;
5979                        break;
5980                    case View.FOCUS_RIGHT:
5981                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_RIGHT;
5982                        break;
5983                    default:
5984                        return result;
5985                }
5986                if (mNativeClass != 0 && !nativeHasCursorNode()) {
5987                    navHandledKey(fakeKeyDirection, 1, true, 0);
5988                }
5989            }
5990        }
5991        return result;
5992    }
5993
5994    @Override
5995    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
5996        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
5997
5998        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
5999        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
6000        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
6001        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
6002
6003        int measuredHeight = heightSize;
6004        int measuredWidth = widthSize;
6005
6006        // Grab the content size from WebViewCore.
6007        int contentHeight = contentToViewDimension(mContentHeight);
6008        int contentWidth = contentToViewDimension(mContentWidth);
6009
6010//        Log.d(LOGTAG, "------- measure " + heightMode);
6011
6012        if (heightMode != MeasureSpec.EXACTLY) {
6013            mHeightCanMeasure = true;
6014            measuredHeight = contentHeight;
6015            if (heightMode == MeasureSpec.AT_MOST) {
6016                // If we are larger than the AT_MOST height, then our height can
6017                // no longer be measured and we should scroll internally.
6018                if (measuredHeight > heightSize) {
6019                    measuredHeight = heightSize;
6020                    mHeightCanMeasure = false;
6021                }
6022            }
6023        } else {
6024            mHeightCanMeasure = false;
6025        }
6026        if (mNativeClass != 0) {
6027            nativeSetHeightCanMeasure(mHeightCanMeasure);
6028        }
6029        // For the width, always use the given size unless unspecified.
6030        if (widthMode == MeasureSpec.UNSPECIFIED) {
6031            mWidthCanMeasure = true;
6032            measuredWidth = contentWidth;
6033        } else {
6034            mWidthCanMeasure = false;
6035        }
6036
6037        synchronized (this) {
6038            setMeasuredDimension(measuredWidth, measuredHeight);
6039        }
6040    }
6041
6042    @Override
6043    public boolean requestChildRectangleOnScreen(View child,
6044                                                 Rect rect,
6045                                                 boolean immediate) {
6046        // don't scroll while in zoom animation. When it is done, we will adjust
6047        // the necessary components (e.g., WebTextView if it is in editing mode)
6048        if (mZoomManager.isFixedLengthAnimationInProgress()) {
6049            return false;
6050        }
6051
6052        rect.offset(child.getLeft() - child.getScrollX(),
6053                child.getTop() - child.getScrollY());
6054
6055        Rect content = new Rect(viewToContentX(mScrollX),
6056                viewToContentY(mScrollY),
6057                viewToContentX(mScrollX + getWidth()
6058                - getVerticalScrollbarWidth()),
6059                viewToContentY(mScrollY + getViewHeightWithTitle()));
6060        content = nativeSubtractLayers(content);
6061        int screenTop = contentToViewY(content.top);
6062        int screenBottom = contentToViewY(content.bottom);
6063        int height = screenBottom - screenTop;
6064        int scrollYDelta = 0;
6065
6066        if (rect.bottom > screenBottom) {
6067            int oneThirdOfScreenHeight = height / 3;
6068            if (rect.height() > 2 * oneThirdOfScreenHeight) {
6069                // If the rectangle is too tall to fit in the bottom two thirds
6070                // of the screen, place it at the top.
6071                scrollYDelta = rect.top - screenTop;
6072            } else {
6073                // If the rectangle will still fit on screen, we want its
6074                // top to be in the top third of the screen.
6075                scrollYDelta = rect.top - (screenTop + oneThirdOfScreenHeight);
6076            }
6077        } else if (rect.top < screenTop) {
6078            scrollYDelta = rect.top - screenTop;
6079        }
6080
6081        int screenLeft = contentToViewX(content.left);
6082        int screenRight = contentToViewX(content.right);
6083        int width = screenRight - screenLeft;
6084        int scrollXDelta = 0;
6085
6086        if (rect.right > screenRight && rect.left > screenLeft) {
6087            if (rect.width() > width) {
6088                scrollXDelta += (rect.left - screenLeft);
6089            } else {
6090                scrollXDelta += (rect.right - screenRight);
6091            }
6092        } else if (rect.left < screenLeft) {
6093            scrollXDelta -= (screenLeft - rect.left);
6094        }
6095
6096        if ((scrollYDelta | scrollXDelta) != 0) {
6097            return pinScrollBy(scrollXDelta, scrollYDelta, !immediate, 0);
6098        }
6099
6100        return false;
6101    }
6102
6103    /* package */ void replaceTextfieldText(int oldStart, int oldEnd,
6104            String replace, int newStart, int newEnd) {
6105        WebViewCore.ReplaceTextData arg = new WebViewCore.ReplaceTextData();
6106        arg.mReplace = replace;
6107        arg.mNewStart = newStart;
6108        arg.mNewEnd = newEnd;
6109        mTextGeneration++;
6110        arg.mTextGeneration = mTextGeneration;
6111        mWebViewCore.sendMessage(EventHub.REPLACE_TEXT, oldStart, oldEnd, arg);
6112    }
6113
6114    /* package */ void passToJavaScript(String currentText, KeyEvent event) {
6115        WebViewCore.JSKeyData arg = new WebViewCore.JSKeyData();
6116        arg.mEvent = event;
6117        arg.mCurrentText = currentText;
6118        // Increase our text generation number, and pass it to webcore thread
6119        mTextGeneration++;
6120        mWebViewCore.sendMessage(EventHub.PASS_TO_JS, mTextGeneration, 0, arg);
6121        // WebKit's document state is not saved until about to leave the page.
6122        // To make sure the host application, like Browser, has the up to date
6123        // document state when it goes to background, we force to save the
6124        // document state.
6125        mWebViewCore.removeMessages(EventHub.SAVE_DOCUMENT_STATE);
6126        mWebViewCore.sendMessageDelayed(EventHub.SAVE_DOCUMENT_STATE,
6127                cursorData(), 1000);
6128    }
6129
6130    /* package */ synchronized WebViewCore getWebViewCore() {
6131        return mWebViewCore;
6132    }
6133
6134    //-------------------------------------------------------------------------
6135    // Methods can be called from a separate thread, like WebViewCore
6136    // If it needs to call the View system, it has to send message.
6137    //-------------------------------------------------------------------------
6138
6139    /**
6140     * General handler to receive message coming from webkit thread
6141     */
6142    class PrivateHandler extends Handler {
6143        @Override
6144        public void handleMessage(Message msg) {
6145            // exclude INVAL_RECT_MSG_ID since it is frequently output
6146            if (DebugFlags.WEB_VIEW && msg.what != INVAL_RECT_MSG_ID) {
6147                if (msg.what >= FIRST_PRIVATE_MSG_ID
6148                        && msg.what <= LAST_PRIVATE_MSG_ID) {
6149                    Log.v(LOGTAG, HandlerPrivateDebugString[msg.what
6150                            - FIRST_PRIVATE_MSG_ID]);
6151                } else if (msg.what >= FIRST_PACKAGE_MSG_ID
6152                        && msg.what <= LAST_PACKAGE_MSG_ID) {
6153                    Log.v(LOGTAG, HandlerPackageDebugString[msg.what
6154                            - FIRST_PACKAGE_MSG_ID]);
6155                } else {
6156                    Log.v(LOGTAG, Integer.toString(msg.what));
6157                }
6158            }
6159            if (mWebViewCore == null) {
6160                // after WebView's destroy() is called, skip handling messages.
6161                return;
6162            }
6163            switch (msg.what) {
6164                case REMEMBER_PASSWORD: {
6165                    mDatabase.setUsernamePassword(
6166                            msg.getData().getString("host"),
6167                            msg.getData().getString("username"),
6168                            msg.getData().getString("password"));
6169                    ((Message) msg.obj).sendToTarget();
6170                    break;
6171                }
6172                case NEVER_REMEMBER_PASSWORD: {
6173                    mDatabase.setUsernamePassword(
6174                            msg.getData().getString("host"), null, null);
6175                    ((Message) msg.obj).sendToTarget();
6176                    break;
6177                }
6178                case PREVENT_DEFAULT_TIMEOUT: {
6179                    // if timeout happens, cancel it so that it won't block UI
6180                    // to continue handling touch events
6181                    if ((msg.arg1 == MotionEvent.ACTION_DOWN
6182                            && mPreventDefault == PREVENT_DEFAULT_MAYBE_YES)
6183                            || (msg.arg1 == MotionEvent.ACTION_MOVE
6184                            && mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN)) {
6185                        cancelWebCoreTouchEvent(
6186                                viewToContentX((int) mLastTouchX + mScrollX),
6187                                viewToContentY((int) mLastTouchY + mScrollY),
6188                                true);
6189                    }
6190                    break;
6191                }
6192                case SWITCH_TO_SHORTPRESS: {
6193                    if (mTouchMode == TOUCH_INIT_MODE) {
6194                        if (!getSettings().supportTouchOnly()
6195                                && mPreventDefault != PREVENT_DEFAULT_YES) {
6196                            mTouchMode = TOUCH_SHORTPRESS_START_MODE;
6197                            updateSelection();
6198                        } else {
6199                            // set to TOUCH_SHORTPRESS_MODE so that it won't
6200                            // trigger double tap any more
6201                            mTouchMode = TOUCH_SHORTPRESS_MODE;
6202                        }
6203                    } else if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
6204                        mTouchMode = TOUCH_DONE_MODE;
6205                    }
6206                    break;
6207                }
6208                case SWITCH_TO_LONGPRESS: {
6209                    if (getSettings().supportTouchOnly()) {
6210                        removeTouchHighlight(false);
6211                    }
6212                    if (inFullScreenMode() || mDeferTouchProcess) {
6213                        TouchEventData ted = new TouchEventData();
6214                        ted.mAction = WebViewCore.ACTION_LONGPRESS;
6215                        ted.mX = viewToContentX((int) mLastTouchX + mScrollX);
6216                        ted.mY = viewToContentY((int) mLastTouchY + mScrollY);
6217                        // metaState for long press is tricky. Should it be the
6218                        // state when the press started or when the press was
6219                        // released? Or some intermediary key state? For
6220                        // simplicity for now, we don't set it.
6221                        ted.mMetaState = 0;
6222                        ted.mReprocess = mDeferTouchProcess;
6223                        mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
6224                    } else if (mPreventDefault != PREVENT_DEFAULT_YES) {
6225                        mTouchMode = TOUCH_DONE_MODE;
6226                        performLongClick();
6227                    }
6228                    break;
6229                }
6230                case RELEASE_SINGLE_TAP: {
6231                    doShortPress();
6232                    break;
6233                }
6234                case SCROLL_BY_MSG_ID:
6235                    setContentScrollBy(msg.arg1, msg.arg2, (Boolean) msg.obj);
6236                    break;
6237                case SYNC_SCROLL_TO_MSG_ID:
6238                    if (mUserScroll) {
6239                        // if user has scrolled explicitly, don't sync the
6240                        // scroll position any more
6241                        mUserScroll = false;
6242                        break;
6243                    }
6244                    // fall through
6245                case SCROLL_TO_MSG_ID:
6246                    if (setContentScrollTo(msg.arg1, msg.arg2)) {
6247                        // if we can't scroll to the exact position due to pin,
6248                        // send a message to WebCore to re-scroll when we get a
6249                        // new picture
6250                        mUserScroll = false;
6251                        mWebViewCore.sendMessage(EventHub.SYNC_SCROLL,
6252                                msg.arg1, msg.arg2);
6253                    }
6254                    break;
6255                case SPAWN_SCROLL_TO_MSG_ID:
6256                    spawnContentScrollTo(msg.arg1, msg.arg2);
6257                    break;
6258                case UPDATE_ZOOM_RANGE: {
6259                    WebViewCore.ViewState viewState = (WebViewCore.ViewState) msg.obj;
6260                    // mScrollX contains the new minPrefWidth
6261                    mZoomManager.updateZoomRange(viewState, getViewWidth(), viewState.mScrollX);
6262                    break;
6263                }
6264                case REPLACE_BASE_CONTENT: {
6265                    nativeReplaceBaseContent(msg.arg1);
6266                    break;
6267                }
6268                case NEW_PICTURE_MSG_ID: {
6269                    // called for new content
6270                    final WebViewCore.DrawData draw = (WebViewCore.DrawData) msg.obj;
6271                    nativeSetBaseLayer(draw.mBaseLayer);
6272                    final Point viewSize = draw.mViewPoint;
6273                    WebViewCore.ViewState viewState = draw.mViewState;
6274                    boolean isPictureAfterFirstLayout = viewState != null;
6275                    if (isPictureAfterFirstLayout) {
6276                        // Reset the last sent data here since dealing with new page.
6277                        mLastWidthSent = 0;
6278                        mZoomManager.onFirstLayout(draw);
6279                        if (!mDrawHistory) {
6280                            setContentScrollTo(viewState.mScrollX, viewState.mScrollY);
6281                            // As we are on a new page, remove the WebTextView. This
6282                            // is necessary for page loads driven by webkit, and in
6283                            // particular when the user was on a password field, so
6284                            // the WebTextView was visible.
6285                            clearTextEntry();
6286                        }
6287                    }
6288
6289                    // We update the layout (i.e. request a layout from the
6290                    // view system) if the last view size that we sent to
6291                    // WebCore matches the view size of the picture we just
6292                    // received in the fixed dimension.
6293                    final boolean updateLayout = viewSize.x == mLastWidthSent
6294                            && viewSize.y == mLastHeightSent;
6295                    recordNewContentSize(draw.mWidthHeight.x,
6296                            draw.mWidthHeight.y, updateLayout);
6297                    if (DebugFlags.WEB_VIEW) {
6298                        Rect b = draw.mInvalRegion.getBounds();
6299                        Log.v(LOGTAG, "NEW_PICTURE_MSG_ID {" +
6300                                b.left+","+b.top+","+b.right+","+b.bottom+"}");
6301                    }
6302                    invalidateContentRect(draw.mInvalRegion.getBounds());
6303
6304                    if (mPictureListener != null) {
6305                        mPictureListener.onNewPicture(WebView.this, capturePicture());
6306                    }
6307
6308                    // update the zoom information based on the new picture
6309                    mZoomManager.onNewPicture(draw);
6310
6311                    if (draw.mFocusSizeChanged && inEditingMode()) {
6312                        mFocusSizeChanged = true;
6313                    }
6314                    if (isPictureAfterFirstLayout) {
6315                        mViewManager.postReadyToDrawAll();
6316                    }
6317                    break;
6318                }
6319                case WEBCORE_INITIALIZED_MSG_ID:
6320                    // nativeCreate sets mNativeClass to a non-zero value
6321                    nativeCreate(msg.arg1);
6322                    break;
6323                case UPDATE_TEXTFIELD_TEXT_MSG_ID:
6324                    // Make sure that the textfield is currently focused
6325                    // and representing the same node as the pointer.
6326                    if (inEditingMode() &&
6327                            mWebTextView.isSameTextField(msg.arg1)) {
6328                        if (msg.getData().getBoolean("password")) {
6329                            Spannable text = (Spannable) mWebTextView.getText();
6330                            int start = Selection.getSelectionStart(text);
6331                            int end = Selection.getSelectionEnd(text);
6332                            mWebTextView.setInPassword(true);
6333                            // Restore the selection, which may have been
6334                            // ruined by setInPassword.
6335                            Spannable pword =
6336                                    (Spannable) mWebTextView.getText();
6337                            Selection.setSelection(pword, start, end);
6338                        // If the text entry has created more events, ignore
6339                        // this one.
6340                        } else if (msg.arg2 == mTextGeneration) {
6341                            mWebTextView.setTextAndKeepSelection(
6342                                    (String) msg.obj);
6343                        }
6344                    }
6345                    break;
6346                case REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID:
6347                    displaySoftKeyboard(true);
6348                    // fall through to UPDATE_TEXT_SELECTION_MSG_ID
6349                case UPDATE_TEXT_SELECTION_MSG_ID:
6350                    updateTextSelectionFromMessage(msg.arg1, msg.arg2,
6351                            (WebViewCore.TextSelectionData) msg.obj);
6352                    break;
6353                case RETURN_LABEL:
6354                    if (inEditingMode()
6355                            && mWebTextView.isSameTextField(msg.arg1)) {
6356                        mWebTextView.setHint((String) msg.obj);
6357                        InputMethodManager imm
6358                                = InputMethodManager.peekInstance();
6359                        // The hint is propagated to the IME in
6360                        // onCreateInputConnection.  If the IME is already
6361                        // active, restart it so that its hint text is updated.
6362                        if (imm != null && imm.isActive(mWebTextView)) {
6363                            imm.restartInput(mWebTextView);
6364                        }
6365                    }
6366                    break;
6367                case UNHANDLED_NAV_KEY:
6368                    navHandledKey(msg.arg1, 1, false, 0);
6369                    break;
6370                case UPDATE_TEXT_ENTRY_MSG_ID:
6371                    // this is sent after finishing resize in WebViewCore. Make
6372                    // sure the text edit box is still on the  screen.
6373                    if (inEditingMode() && nativeCursorIsTextInput()) {
6374                        mWebTextView.bringIntoView();
6375                        rebuildWebTextView();
6376                    }
6377                    break;
6378                case CLEAR_TEXT_ENTRY:
6379                    clearTextEntry();
6380                    break;
6381                case INVAL_RECT_MSG_ID: {
6382                    Rect r = (Rect)msg.obj;
6383                    if (r == null) {
6384                        invalidate();
6385                    } else {
6386                        // we need to scale r from content into view coords,
6387                        // which viewInvalidate() does for us
6388                        viewInvalidate(r.left, r.top, r.right, r.bottom);
6389                    }
6390                    break;
6391                }
6392                case REQUEST_FORM_DATA:
6393                    AutoCompleteAdapter adapter = (AutoCompleteAdapter) msg.obj;
6394                    if (mWebTextView.isSameTextField(msg.arg1)) {
6395                        mWebTextView.setAdapterCustom(adapter);
6396                    }
6397                    break;
6398                case RESUME_WEBCORE_PRIORITY:
6399                    WebViewCore.resumePriority();
6400                    WebViewCore.resumeUpdatePicture(mWebViewCore);
6401                    break;
6402
6403                case LONG_PRESS_CENTER:
6404                    // as this is shared by keydown and trackballdown, reset all
6405                    // the states
6406                    mGotCenterDown = false;
6407                    mTrackballDown = false;
6408                    performLongClick();
6409                    break;
6410
6411                case WEBCORE_NEED_TOUCH_EVENTS:
6412                    mForwardTouchEvents = (msg.arg1 != 0);
6413                    break;
6414
6415                case PREVENT_TOUCH_ID:
6416                    if (inFullScreenMode()) {
6417                        break;
6418                    }
6419                    if (msg.obj == null) {
6420                        if (msg.arg1 == MotionEvent.ACTION_DOWN
6421                                && mPreventDefault == PREVENT_DEFAULT_MAYBE_YES) {
6422                            // if prevent default is called from WebCore, UI
6423                            // will not handle the rest of the touch events any
6424                            // more.
6425                            mPreventDefault = msg.arg2 == 1 ? PREVENT_DEFAULT_YES
6426                                    : PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN;
6427                        } else if (msg.arg1 == MotionEvent.ACTION_MOVE
6428                                && mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN) {
6429                            // the return for the first ACTION_MOVE will decide
6430                            // whether UI will handle touch or not. Currently no
6431                            // support for alternating prevent default
6432                            mPreventDefault = msg.arg2 == 1 ? PREVENT_DEFAULT_YES
6433                                    : PREVENT_DEFAULT_NO;
6434                        }
6435                        if (mPreventDefault == PREVENT_DEFAULT_YES) {
6436                            mTouchHighlightRegion.setEmpty();
6437                        }
6438                    } else if (msg.arg2 == 0) {
6439                        // prevent default is not called in WebCore, so the
6440                        // message needs to be reprocessed in UI
6441                        TouchEventData ted = (TouchEventData) msg.obj;
6442                        switch (ted.mAction) {
6443                            case MotionEvent.ACTION_DOWN:
6444                                mLastDeferTouchX = contentToViewX(ted.mX)
6445                                        - mScrollX;
6446                                mLastDeferTouchY = contentToViewY(ted.mY)
6447                                        - mScrollY;
6448                                mDeferTouchMode = TOUCH_INIT_MODE;
6449                                break;
6450                            case MotionEvent.ACTION_MOVE: {
6451                                // no snapping in defer process
6452                                int x = contentToViewX(ted.mX) - mScrollX;
6453                                int y = contentToViewY(ted.mY) - mScrollY;
6454                                if (mDeferTouchMode != TOUCH_DRAG_MODE) {
6455                                    mDeferTouchMode = TOUCH_DRAG_MODE;
6456                                    mLastDeferTouchX = x;
6457                                    mLastDeferTouchY = y;
6458                                    startDrag();
6459                                }
6460                                int deltaX = pinLocX((int) (mScrollX
6461                                        + mLastDeferTouchX - x))
6462                                        - mScrollX;
6463                                int deltaY = pinLocY((int) (mScrollY
6464                                        + mLastDeferTouchY - y))
6465                                        - mScrollY;
6466                                doDrag(deltaX, deltaY);
6467                                if (deltaX != 0) mLastDeferTouchX = x;
6468                                if (deltaY != 0) mLastDeferTouchY = y;
6469                                break;
6470                            }
6471                            case MotionEvent.ACTION_UP:
6472                            case MotionEvent.ACTION_CANCEL:
6473                                if (mDeferTouchMode == TOUCH_DRAG_MODE) {
6474                                    // no fling in defer process
6475                                    WebViewCore.resumePriority();
6476                                    WebViewCore.resumeUpdatePicture(mWebViewCore);
6477                                }
6478                                mDeferTouchMode = TOUCH_DONE_MODE;
6479                                break;
6480                            case WebViewCore.ACTION_DOUBLETAP:
6481                                // doDoubleTap() needs mLastTouchX/Y as anchor
6482                                mLastTouchX = contentToViewX(ted.mX) - mScrollX;
6483                                mLastTouchY = contentToViewY(ted.mY) - mScrollY;
6484                                mZoomManager.handleDoubleTap(mLastTouchX, mLastTouchY);
6485                                mDeferTouchMode = TOUCH_DONE_MODE;
6486                                break;
6487                            case WebViewCore.ACTION_LONGPRESS:
6488                                HitTestResult hitTest = getHitTestResult();
6489                                if (hitTest != null && hitTest.mType
6490                                        != HitTestResult.UNKNOWN_TYPE) {
6491                                    performLongClick();
6492                                }
6493                                mDeferTouchMode = TOUCH_DONE_MODE;
6494                                break;
6495                        }
6496                    }
6497                    break;
6498
6499                case REQUEST_KEYBOARD:
6500                    if (msg.arg1 == 0) {
6501                        hideSoftKeyboard();
6502                    } else {
6503                        displaySoftKeyboard(false);
6504                    }
6505                    break;
6506
6507                case FIND_AGAIN:
6508                    // Ignore if find has been dismissed.
6509                    if (mFindIsUp) {
6510                        findAll(mLastFind);
6511                    }
6512                    break;
6513
6514                case DRAG_HELD_MOTIONLESS:
6515                    mHeldMotionless = MOTIONLESS_TRUE;
6516                    invalidate();
6517                    // fall through to keep scrollbars awake
6518
6519                case AWAKEN_SCROLL_BARS:
6520                    if (mTouchMode == TOUCH_DRAG_MODE
6521                            && mHeldMotionless == MOTIONLESS_TRUE) {
6522                        awakenScrollBars(ViewConfiguration
6523                                .getScrollDefaultDelay(), false);
6524                        mPrivateHandler.sendMessageDelayed(mPrivateHandler
6525                                .obtainMessage(AWAKEN_SCROLL_BARS),
6526                                ViewConfiguration.getScrollDefaultDelay());
6527                    }
6528                    break;
6529
6530                case DO_MOTION_UP:
6531                    doMotionUp(msg.arg1, msg.arg2);
6532                    break;
6533
6534                case SHOW_FULLSCREEN: {
6535                    View view = (View) msg.obj;
6536                    int npp = msg.arg1;
6537
6538                    if (mFullScreenHolder != null) {
6539                        Log.w(LOGTAG, "Should not have another full screen.");
6540                        mFullScreenHolder.dismiss();
6541                    }
6542                    mFullScreenHolder = new PluginFullScreenHolder(WebView.this, npp);
6543                    mFullScreenHolder.setContentView(view);
6544                    mFullScreenHolder.setCancelable(false);
6545                    mFullScreenHolder.setCanceledOnTouchOutside(false);
6546                    mFullScreenHolder.show();
6547
6548                    break;
6549                }
6550                case HIDE_FULLSCREEN:
6551                    if (inFullScreenMode()) {
6552                        mFullScreenHolder.dismiss();
6553                        mFullScreenHolder = null;
6554                    }
6555                    break;
6556
6557                case DOM_FOCUS_CHANGED:
6558                    if (inEditingMode()) {
6559                        nativeClearCursor();
6560                        rebuildWebTextView();
6561                    }
6562                    break;
6563
6564                case SHOW_RECT_MSG_ID: {
6565                    WebViewCore.ShowRectData data = (WebViewCore.ShowRectData) msg.obj;
6566                    int x = mScrollX;
6567                    int left = contentToViewX(data.mLeft);
6568                    int width = contentToViewDimension(data.mWidth);
6569                    int maxWidth = contentToViewDimension(data.mContentWidth);
6570                    int viewWidth = getViewWidth();
6571                    if (width < viewWidth) {
6572                        // center align
6573                        x += left + width / 2 - mScrollX - viewWidth / 2;
6574                    } else {
6575                        x += (int) (left + data.mXPercentInDoc * width
6576                                - mScrollX - data.mXPercentInView * viewWidth);
6577                    }
6578                    if (DebugFlags.WEB_VIEW) {
6579                        Log.v(LOGTAG, "showRectMsg=(left=" + left + ",width=" +
6580                              width + ",maxWidth=" + maxWidth +
6581                              ",viewWidth=" + viewWidth + ",x="
6582                              + x + ",xPercentInDoc=" + data.mXPercentInDoc +
6583                              ",xPercentInView=" + data.mXPercentInView+ ")");
6584                    }
6585                    // use the passing content width to cap x as the current
6586                    // mContentWidth may not be updated yet
6587                    x = Math.max(0,
6588                            (Math.min(maxWidth, x + viewWidth)) - viewWidth);
6589                    int top = contentToViewY(data.mTop);
6590                    int height = contentToViewDimension(data.mHeight);
6591                    int maxHeight = contentToViewDimension(data.mContentHeight);
6592                    int viewHeight = getViewHeight();
6593                    int y = (int) (top + data.mYPercentInDoc * height -
6594                                   data.mYPercentInView * viewHeight);
6595                    if (DebugFlags.WEB_VIEW) {
6596                        Log.v(LOGTAG, "showRectMsg=(top=" + top + ",height=" +
6597                              height + ",maxHeight=" + maxHeight +
6598                              ",viewHeight=" + viewHeight + ",y="
6599                              + y + ",yPercentInDoc=" + data.mYPercentInDoc +
6600                              ",yPercentInView=" + data.mYPercentInView+ ")");
6601                    }
6602                    // use the passing content height to cap y as the current
6603                    // mContentHeight may not be updated yet
6604                    y = Math.max(0,
6605                            (Math.min(maxHeight, y + viewHeight) - viewHeight));
6606                    // We need to take into account the visible title height
6607                    // when scrolling since y is an absolute view position.
6608                    y = Math.max(0, y - getVisibleTitleHeight());
6609                    scrollTo(x, y);
6610                    }
6611                    break;
6612
6613                case CENTER_FIT_RECT:
6614                    Rect r = (Rect)msg.obj;
6615                    centerFitRect(r.left, r.top, r.width(), r.height());
6616                    break;
6617
6618                case SET_SCROLLBAR_MODES:
6619                    mHorizontalScrollBarMode = msg.arg1;
6620                    mVerticalScrollBarMode = msg.arg2;
6621                    break;
6622
6623                case SELECTION_STRING_CHANGED:
6624                    if (mAccessibilityInjector != null) {
6625                        String selectionString = (String) msg.obj;
6626                        mAccessibilityInjector.onSelectionStringChange(selectionString);
6627                    }
6628                    break;
6629
6630                case SET_TOUCH_HIGHLIGHT_RECTS:
6631                    invalidate(mTouchHighlightRegion.getBounds());
6632                    mTouchHighlightRegion.setEmpty();
6633                    if (msg.obj != null) {
6634                        ArrayList<Rect> rects = (ArrayList<Rect>) msg.obj;
6635                        for (Rect rect : rects) {
6636                            Rect viewRect = contentToViewRect(rect);
6637                            // some sites, like stories in nytimes.com, set
6638                            // mouse event handler in the top div. It is not
6639                            // user friendly to highlight the div if it covers
6640                            // more than half of the screen.
6641                            if (viewRect.width() < getWidth() >> 1
6642                                    || viewRect.height() < getHeight() >> 1) {
6643                                mTouchHighlightRegion.union(viewRect);
6644                                invalidate(viewRect);
6645                            } else {
6646                                Log.w(LOGTAG, "Skip the huge selection rect:"
6647                                        + viewRect);
6648                            }
6649                        }
6650                    }
6651                    break;
6652
6653                case SAVE_WEBARCHIVE_FINISHED:
6654                    SaveWebArchiveMessage saveMessage = (SaveWebArchiveMessage)msg.obj;
6655                    if (saveMessage.mCallback != null) {
6656                        saveMessage.mCallback.onReceiveValue(saveMessage.mResultFile);
6657                    }
6658                    break;
6659
6660                default:
6661                    super.handleMessage(msg);
6662                    break;
6663            }
6664        }
6665    }
6666
6667    /**
6668     * Used when receiving messages for REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID
6669     * and UPDATE_TEXT_SELECTION_MSG_ID.  Update the selection of WebTextView.
6670     */
6671    private void updateTextSelectionFromMessage(int nodePointer,
6672            int textGeneration, WebViewCore.TextSelectionData data) {
6673        if (inEditingMode()
6674                && mWebTextView.isSameTextField(nodePointer)
6675                && textGeneration == mTextGeneration) {
6676            mWebTextView.setSelectionFromWebKit(data.mStart, data.mEnd);
6677        }
6678    }
6679
6680    // Class used to use a dropdown for a <select> element
6681    private class InvokeListBox implements Runnable {
6682        // Whether the listbox allows multiple selection.
6683        private boolean     mMultiple;
6684        // Passed in to a list with multiple selection to tell
6685        // which items are selected.
6686        private int[]       mSelectedArray;
6687        // Passed in to a list with single selection to tell
6688        // where the initial selection is.
6689        private int         mSelection;
6690
6691        private Container[] mContainers;
6692
6693        // Need these to provide stable ids to my ArrayAdapter,
6694        // which normally does not have stable ids. (Bug 1250098)
6695        private class Container extends Object {
6696            /**
6697             * Possible values for mEnabled.  Keep in sync with OptionStatus in
6698             * WebViewCore.cpp
6699             */
6700            final static int OPTGROUP = -1;
6701            final static int OPTION_DISABLED = 0;
6702            final static int OPTION_ENABLED = 1;
6703
6704            String  mString;
6705            int     mEnabled;
6706            int     mId;
6707
6708            public String toString() {
6709                return mString;
6710            }
6711        }
6712
6713        /**
6714         *  Subclass ArrayAdapter so we can disable OptionGroupLabels,
6715         *  and allow filtering.
6716         */
6717        private class MyArrayListAdapter extends ArrayAdapter<Container> {
6718            public MyArrayListAdapter(Context context, Container[] objects, boolean multiple) {
6719                super(context,
6720                            multiple ? com.android.internal.R.layout.select_dialog_multichoice :
6721                            com.android.internal.R.layout.select_dialog_singlechoice,
6722                            objects);
6723            }
6724
6725            @Override
6726            public View getView(int position, View convertView,
6727                    ViewGroup parent) {
6728                // Always pass in null so that we will get a new CheckedTextView
6729                // Otherwise, an item which was previously used as an <optgroup>
6730                // element (i.e. has no check), could get used as an <option>
6731                // element, which needs a checkbox/radio, but it would not have
6732                // one.
6733                convertView = super.getView(position, null, parent);
6734                Container c = item(position);
6735                if (c != null && Container.OPTION_ENABLED != c.mEnabled) {
6736                    // ListView does not draw dividers between disabled and
6737                    // enabled elements.  Use a LinearLayout to provide dividers
6738                    LinearLayout layout = new LinearLayout(mContext);
6739                    layout.setOrientation(LinearLayout.VERTICAL);
6740                    if (position > 0) {
6741                        View dividerTop = new View(mContext);
6742                        dividerTop.setBackgroundResource(
6743                                android.R.drawable.divider_horizontal_bright);
6744                        layout.addView(dividerTop);
6745                    }
6746
6747                    if (Container.OPTGROUP == c.mEnabled) {
6748                        // Currently select_dialog_multichoice and
6749                        // select_dialog_singlechoice are CheckedTextViews.  If
6750                        // that changes, the class cast will no longer be valid.
6751                        Assert.assertTrue(
6752                                convertView instanceof CheckedTextView);
6753                        ((CheckedTextView) convertView).setCheckMarkDrawable(
6754                                null);
6755                    } else {
6756                        // c.mEnabled == Container.OPTION_DISABLED
6757                        // Draw the disabled element in a disabled state.
6758                        convertView.setEnabled(false);
6759                    }
6760
6761                    layout.addView(convertView);
6762                    if (position < getCount() - 1) {
6763                        View dividerBottom = new View(mContext);
6764                        dividerBottom.setBackgroundResource(
6765                                android.R.drawable.divider_horizontal_bright);
6766                        layout.addView(dividerBottom);
6767                    }
6768                    return layout;
6769                }
6770                return convertView;
6771            }
6772
6773            @Override
6774            public boolean hasStableIds() {
6775                // AdapterView's onChanged method uses this to determine whether
6776                // to restore the old state.  Return false so that the old (out
6777                // of date) state does not replace the new, valid state.
6778                return false;
6779            }
6780
6781            private Container item(int position) {
6782                if (position < 0 || position >= getCount()) {
6783                    return null;
6784                }
6785                return (Container) getItem(position);
6786            }
6787
6788            @Override
6789            public long getItemId(int position) {
6790                Container item = item(position);
6791                if (item == null) {
6792                    return -1;
6793                }
6794                return item.mId;
6795            }
6796
6797            @Override
6798            public boolean areAllItemsEnabled() {
6799                return false;
6800            }
6801
6802            @Override
6803            public boolean isEnabled(int position) {
6804                Container item = item(position);
6805                if (item == null) {
6806                    return false;
6807                }
6808                return Container.OPTION_ENABLED == item.mEnabled;
6809            }
6810        }
6811
6812        private InvokeListBox(String[] array, int[] enabled, int[] selected) {
6813            mMultiple = true;
6814            mSelectedArray = selected;
6815
6816            int length = array.length;
6817            mContainers = new Container[length];
6818            for (int i = 0; i < length; i++) {
6819                mContainers[i] = new Container();
6820                mContainers[i].mString = array[i];
6821                mContainers[i].mEnabled = enabled[i];
6822                mContainers[i].mId = i;
6823            }
6824        }
6825
6826        private InvokeListBox(String[] array, int[] enabled, int selection) {
6827            mSelection = selection;
6828            mMultiple = false;
6829
6830            int length = array.length;
6831            mContainers = new Container[length];
6832            for (int i = 0; i < length; i++) {
6833                mContainers[i] = new Container();
6834                mContainers[i].mString = array[i];
6835                mContainers[i].mEnabled = enabled[i];
6836                mContainers[i].mId = i;
6837            }
6838        }
6839
6840        /*
6841         * Whenever the data set changes due to filtering, this class ensures
6842         * that the checked item remains checked.
6843         */
6844        private class SingleDataSetObserver extends DataSetObserver {
6845            private long        mCheckedId;
6846            private ListView    mListView;
6847            private Adapter     mAdapter;
6848
6849            /*
6850             * Create a new observer.
6851             * @param id The ID of the item to keep checked.
6852             * @param l ListView for getting and clearing the checked states
6853             * @param a Adapter for getting the IDs
6854             */
6855            public SingleDataSetObserver(long id, ListView l, Adapter a) {
6856                mCheckedId = id;
6857                mListView = l;
6858                mAdapter = a;
6859            }
6860
6861            public void onChanged() {
6862                // The filter may have changed which item is checked.  Find the
6863                // item that the ListView thinks is checked.
6864                int position = mListView.getCheckedItemPosition();
6865                long id = mAdapter.getItemId(position);
6866                if (mCheckedId != id) {
6867                    // Clear the ListView's idea of the checked item, since
6868                    // it is incorrect
6869                    mListView.clearChoices();
6870                    // Search for mCheckedId.  If it is in the filtered list,
6871                    // mark it as checked
6872                    int count = mAdapter.getCount();
6873                    for (int i = 0; i < count; i++) {
6874                        if (mAdapter.getItemId(i) == mCheckedId) {
6875                            mListView.setItemChecked(i, true);
6876                            break;
6877                        }
6878                    }
6879                }
6880            }
6881
6882            public void onInvalidate() {}
6883        }
6884
6885        public void run() {
6886            final ListView listView = (ListView) LayoutInflater.from(mContext)
6887                    .inflate(com.android.internal.R.layout.select_dialog, null);
6888            final MyArrayListAdapter adapter = new
6889                    MyArrayListAdapter(mContext, mContainers, mMultiple);
6890            AlertDialog.Builder b = new AlertDialog.Builder(mContext)
6891                    .setView(listView).setCancelable(true)
6892                    .setInverseBackgroundForced(true);
6893
6894            if (mMultiple) {
6895                b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
6896                    public void onClick(DialogInterface dialog, int which) {
6897                        mWebViewCore.sendMessage(
6898                                EventHub.LISTBOX_CHOICES,
6899                                adapter.getCount(), 0,
6900                                listView.getCheckedItemPositions());
6901                    }});
6902                b.setNegativeButton(android.R.string.cancel,
6903                        new DialogInterface.OnClickListener() {
6904                    public void onClick(DialogInterface dialog, int which) {
6905                        mWebViewCore.sendMessage(
6906                                EventHub.SINGLE_LISTBOX_CHOICE, -2, 0);
6907                }});
6908            }
6909            final AlertDialog dialog = b.create();
6910            listView.setAdapter(adapter);
6911            listView.setFocusableInTouchMode(true);
6912            // There is a bug (1250103) where the checks in a ListView with
6913            // multiple items selected are associated with the positions, not
6914            // the ids, so the items do not properly retain their checks when
6915            // filtered.  Do not allow filtering on multiple lists until
6916            // that bug is fixed.
6917
6918            listView.setTextFilterEnabled(!mMultiple);
6919            if (mMultiple) {
6920                listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
6921                int length = mSelectedArray.length;
6922                for (int i = 0; i < length; i++) {
6923                    listView.setItemChecked(mSelectedArray[i], true);
6924                }
6925            } else {
6926                listView.setOnItemClickListener(new OnItemClickListener() {
6927                    public void onItemClick(AdapterView parent, View v,
6928                            int position, long id) {
6929                        mWebViewCore.sendMessage(
6930                                EventHub.SINGLE_LISTBOX_CHOICE, (int)id, 0);
6931                        dialog.dismiss();
6932                    }
6933                });
6934                if (mSelection != -1) {
6935                    listView.setSelection(mSelection);
6936                    listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
6937                    listView.setItemChecked(mSelection, true);
6938                    DataSetObserver observer = new SingleDataSetObserver(
6939                            adapter.getItemId(mSelection), listView, adapter);
6940                    adapter.registerDataSetObserver(observer);
6941                }
6942            }
6943            dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
6944                public void onCancel(DialogInterface dialog) {
6945                    mWebViewCore.sendMessage(
6946                                EventHub.SINGLE_LISTBOX_CHOICE, -2, 0);
6947                }
6948            });
6949            dialog.show();
6950        }
6951    }
6952
6953    /*
6954     * Request a dropdown menu for a listbox with multiple selection.
6955     *
6956     * @param array Labels for the listbox.
6957     * @param enabledArray  State for each element in the list.  See static
6958     *      integers in Container class.
6959     * @param selectedArray Which positions are initally selected.
6960     */
6961    void requestListBox(String[] array, int[] enabledArray, int[]
6962            selectedArray) {
6963        mPrivateHandler.post(
6964                new InvokeListBox(array, enabledArray, selectedArray));
6965    }
6966
6967    /*
6968     * Request a dropdown menu for a listbox with single selection or a single
6969     * <select> element.
6970     *
6971     * @param array Labels for the listbox.
6972     * @param enabledArray  State for each element in the list.  See static
6973     *      integers in Container class.
6974     * @param selection Which position is initally selected.
6975     */
6976    void requestListBox(String[] array, int[] enabledArray, int selection) {
6977        mPrivateHandler.post(
6978                new InvokeListBox(array, enabledArray, selection));
6979    }
6980
6981    // called by JNI
6982    private void sendMoveFocus(int frame, int node) {
6983        mWebViewCore.sendMessage(EventHub.SET_MOVE_FOCUS,
6984                new WebViewCore.CursorData(frame, node, 0, 0));
6985    }
6986
6987    // called by JNI
6988    private void sendMoveMouse(int frame, int node, int x, int y) {
6989        mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE,
6990                new WebViewCore.CursorData(frame, node, x, y));
6991    }
6992
6993    /*
6994     * Send a mouse move event to the webcore thread.
6995     *
6996     * @param removeFocus Pass true if the "mouse" cursor is now over a node
6997     *                    which wants key events, but it is not the focus. This
6998     *                    will make the visual appear as though nothing is in
6999     *                    focus.  Remove the WebTextView, if present, and stop
7000     *                    drawing the blinking caret.
7001     * called by JNI
7002     */
7003    private void sendMoveMouseIfLatest(boolean removeFocus) {
7004        if (removeFocus) {
7005            clearTextEntry();
7006        }
7007        mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE_IF_LATEST,
7008                cursorData());
7009    }
7010
7011    // called by JNI
7012    private void sendMotionUp(int touchGeneration,
7013            int frame, int node, int x, int y) {
7014        WebViewCore.TouchUpData touchUpData = new WebViewCore.TouchUpData();
7015        touchUpData.mMoveGeneration = touchGeneration;
7016        touchUpData.mFrame = frame;
7017        touchUpData.mNode = node;
7018        touchUpData.mX = x;
7019        touchUpData.mY = y;
7020        mWebViewCore.sendMessage(EventHub.TOUCH_UP, touchUpData);
7021    }
7022
7023
7024    private int getScaledMaxXScroll() {
7025        int width;
7026        if (mHeightCanMeasure == false) {
7027            width = getViewWidth() / 4;
7028        } else {
7029            Rect visRect = new Rect();
7030            calcOurVisibleRect(visRect);
7031            width = visRect.width() / 2;
7032        }
7033        // FIXME the divisor should be retrieved from somewhere
7034        return viewToContentX(width);
7035    }
7036
7037    private int getScaledMaxYScroll() {
7038        int height;
7039        if (mHeightCanMeasure == false) {
7040            height = getViewHeight() / 4;
7041        } else {
7042            Rect visRect = new Rect();
7043            calcOurVisibleRect(visRect);
7044            height = visRect.height() / 2;
7045        }
7046        // FIXME the divisor should be retrieved from somewhere
7047        // the closest thing today is hard-coded into ScrollView.java
7048        // (from ScrollView.java, line 363)   int maxJump = height/2;
7049        return Math.round(height * mZoomManager.getInvScale());
7050    }
7051
7052    /**
7053     * Called by JNI to invalidate view
7054     */
7055    private void viewInvalidate() {
7056        invalidate();
7057    }
7058
7059    /**
7060     * Pass the key directly to the page.  This assumes that
7061     * nativePageShouldHandleShiftAndArrows() returned true.
7062     */
7063    private void letPageHandleNavKey(int keyCode, long time, boolean down) {
7064        int keyEventAction;
7065        int eventHubAction;
7066        if (down) {
7067            keyEventAction = KeyEvent.ACTION_DOWN;
7068            eventHubAction = EventHub.KEY_DOWN;
7069            playSoundEffect(keyCodeToSoundsEffect(keyCode));
7070        } else {
7071            keyEventAction = KeyEvent.ACTION_UP;
7072            eventHubAction = EventHub.KEY_UP;
7073        }
7074        KeyEvent event = new KeyEvent(time, time, keyEventAction, keyCode,
7075                1, (mShiftIsPressed ? KeyEvent.META_SHIFT_ON : 0)
7076                | (false ? KeyEvent.META_ALT_ON : 0) // FIXME
7077                | (false ? KeyEvent.META_SYM_ON : 0) // FIXME
7078                , 0, 0, 0);
7079        mWebViewCore.sendMessage(eventHubAction, event);
7080    }
7081
7082    // return true if the key was handled
7083    private boolean navHandledKey(int keyCode, int count, boolean noScroll,
7084            long time) {
7085        if (mNativeClass == 0) {
7086            return false;
7087        }
7088        mLastCursorTime = time;
7089        mLastCursorBounds = nativeGetCursorRingBounds();
7090        boolean keyHandled
7091                = nativeMoveCursor(keyCode, count, noScroll) == false;
7092        if (DebugFlags.WEB_VIEW) {
7093            Log.v(LOGTAG, "navHandledKey mLastCursorBounds=" + mLastCursorBounds
7094                    + " mLastCursorTime=" + mLastCursorTime
7095                    + " handled=" + keyHandled);
7096        }
7097        if (keyHandled == false || mHeightCanMeasure == false) {
7098            return keyHandled;
7099        }
7100        Rect contentCursorRingBounds = nativeGetCursorRingBounds();
7101        if (contentCursorRingBounds.isEmpty()) return keyHandled;
7102        Rect viewCursorRingBounds = contentToViewRect(contentCursorRingBounds);
7103        Rect visRect = new Rect();
7104        calcOurVisibleRect(visRect);
7105        Rect outset = new Rect(visRect);
7106        int maxXScroll = visRect.width() / 2;
7107        int maxYScroll = visRect.height() / 2;
7108        outset.inset(-maxXScroll, -maxYScroll);
7109        if (Rect.intersects(outset, viewCursorRingBounds) == false) {
7110            return keyHandled;
7111        }
7112        // FIXME: Necessary because ScrollView/ListView do not scroll left/right
7113        int maxH = Math.min(viewCursorRingBounds.right - visRect.right,
7114                maxXScroll);
7115        if (maxH > 0) {
7116            pinScrollBy(maxH, 0, true, 0);
7117        } else {
7118            maxH = Math.max(viewCursorRingBounds.left - visRect.left,
7119                    -maxXScroll);
7120            if (maxH < 0) {
7121                pinScrollBy(maxH, 0, true, 0);
7122            }
7123        }
7124        if (mLastCursorBounds.isEmpty()) return keyHandled;
7125        if (mLastCursorBounds.equals(contentCursorRingBounds)) {
7126            return keyHandled;
7127        }
7128        if (DebugFlags.WEB_VIEW) {
7129            Log.v(LOGTAG, "navHandledKey contentCursorRingBounds="
7130                    + contentCursorRingBounds);
7131        }
7132        requestRectangleOnScreen(viewCursorRingBounds);
7133        mUserScroll = true;
7134        return keyHandled;
7135    }
7136
7137    /**
7138     * Set the background color. It's white by default. Pass
7139     * zero to make the view transparent.
7140     * @param color   the ARGB color described by Color.java
7141     */
7142    public void setBackgroundColor(int color) {
7143        mBackgroundColor = color;
7144        mWebViewCore.sendMessage(EventHub.SET_BACKGROUND_COLOR, color);
7145    }
7146
7147    public void debugDump() {
7148        nativeDebugDump();
7149        mWebViewCore.sendMessage(EventHub.DUMP_NAVTREE);
7150    }
7151
7152    /**
7153     * Draw the HTML page into the specified canvas. This call ignores any
7154     * view-specific zoom, scroll offset, or other changes. It does not draw
7155     * any view-specific chrome, such as progress or URL bars.
7156     *
7157     * @hide only needs to be accessible to Browser and testing
7158     */
7159    public void drawPage(Canvas canvas) {
7160        nativeDraw(canvas, 0, 0, false);
7161    }
7162
7163    /**
7164     * Set the time to wait between passing touches to WebCore. See also the
7165     * TOUCH_SENT_INTERVAL member for further discussion.
7166     *
7167     * @hide This is only used by the DRT test application.
7168     */
7169    public void setTouchInterval(int interval) {
7170        mCurrentTouchInterval = interval;
7171    }
7172
7173    /**
7174     *  Update our cache with updatedText.
7175     *  @param updatedText  The new text to put in our cache.
7176     */
7177    /* package */ void updateCachedTextfield(String updatedText) {
7178        // Also place our generation number so that when we look at the cache
7179        // we recognize that it is up to date.
7180        nativeUpdateCachedTextfield(updatedText, mTextGeneration);
7181    }
7182
7183    private native int nativeCacheHitFramePointer();
7184    private native Rect nativeCacheHitNodeBounds();
7185    private native int nativeCacheHitNodePointer();
7186    /* package */ native void nativeClearCursor();
7187    private native void     nativeCreate(int ptr);
7188    private native int      nativeCursorFramePointer();
7189    private native Rect     nativeCursorNodeBounds();
7190    private native int nativeCursorNodePointer();
7191    /* package */ native boolean nativeCursorMatchesFocus();
7192    private native boolean  nativeCursorIntersects(Rect visibleRect);
7193    private native boolean  nativeCursorIsAnchor();
7194    private native boolean  nativeCursorIsTextInput();
7195    private native Point    nativeCursorPosition();
7196    private native String   nativeCursorText();
7197    /**
7198     * Returns true if the native cursor node says it wants to handle key events
7199     * (ala plugins). This can only be called if mNativeClass is non-zero!
7200     */
7201    private native boolean  nativeCursorWantsKeyEvents();
7202    private native void     nativeDebugDump();
7203    private native void     nativeDestroy();
7204
7205    /**
7206     * Draw the picture set with a background color and extra. If
7207     * "splitIfNeeded" is true and the return value is not 0, the return value
7208     * MUST be passed to WebViewCore with SPLIT_PICTURE_SET message so that the
7209     * native allocation can be freed.
7210     */
7211    private native int nativeDraw(Canvas canvas, int color, int extra,
7212            boolean splitIfNeeded);
7213    private native void     nativeDumpDisplayTree(String urlOrNull);
7214    private native boolean  nativeEvaluateLayersAnimations();
7215    private native void     nativeExtendSelection(int x, int y);
7216    private native int      nativeFindAll(String findLower, String findUpper);
7217    private native void     nativeFindNext(boolean forward);
7218    /* package */ native int      nativeFocusCandidateFramePointer();
7219    /* package */ native boolean  nativeFocusCandidateHasNextTextfield();
7220    /* package */ native boolean  nativeFocusCandidateIsPassword();
7221    private native boolean  nativeFocusCandidateIsRtlText();
7222    private native boolean  nativeFocusCandidateIsTextInput();
7223    /* package */ native int      nativeFocusCandidateMaxLength();
7224    /* package */ native String   nativeFocusCandidateName();
7225    private native Rect     nativeFocusCandidateNodeBounds();
7226    /* package */ native int      nativeFocusCandidatePointer();
7227    private native String   nativeFocusCandidateText();
7228    private native int      nativeFocusCandidateTextSize();
7229    /**
7230     * Returns an integer corresponding to WebView.cpp::type.
7231     * See WebTextView.setType()
7232     */
7233    private native int      nativeFocusCandidateType();
7234    private native boolean  nativeFocusIsPlugin();
7235    private native Rect     nativeFocusNodeBounds();
7236    /* package */ native int nativeFocusNodePointer();
7237    private native Rect     nativeGetCursorRingBounds();
7238    private native String   nativeGetSelection();
7239    private native boolean  nativeHasCursorNode();
7240    private native boolean  nativeHasFocusNode();
7241    private native void     nativeHideCursor();
7242    private native boolean  nativeHitSelection(int x, int y);
7243    private native String   nativeImageURI(int x, int y);
7244    private native void     nativeInstrumentReport();
7245    /* package */ native boolean nativeMoveCursorToNextTextInput();
7246    // return true if the page has been scrolled
7247    private native boolean  nativeMotionUp(int x, int y, int slop);
7248    // returns false if it handled the key
7249    private native boolean  nativeMoveCursor(int keyCode, int count,
7250            boolean noScroll);
7251    private native int      nativeMoveGeneration();
7252    private native void     nativeMoveSelection(int x, int y);
7253    /**
7254     * @return true if the page should get the shift and arrow keys, rather
7255     * than select text/navigation.
7256     *
7257     * If the focus is a plugin, or if the focus and cursor match and are
7258     * a contentEditable element, then the page should handle these keys.
7259     */
7260    private native boolean  nativePageShouldHandleShiftAndArrows();
7261    private native boolean  nativePointInNavCache(int x, int y, int slop);
7262    // Like many other of our native methods, you must make sure that
7263    // mNativeClass is not null before calling this method.
7264    private native void     nativeRecordButtons(boolean focused,
7265            boolean pressed, boolean invalidate);
7266    private native void     nativeResetSelection();
7267    private native void     nativeSelectAll();
7268    private native void     nativeSelectBestAt(Rect rect);
7269    private native int      nativeSelectionX();
7270    private native int      nativeSelectionY();
7271    private native int      nativeFindIndex();
7272    private native void     nativeSetExtendSelection();
7273    private native void     nativeSetFindIsEmpty();
7274    private native void     nativeSetFindIsUp(boolean isUp);
7275    private native void     nativeSetFollowedLink(boolean followed);
7276    private native void     nativeSetHeightCanMeasure(boolean measure);
7277    private native void     nativeSetBaseLayer(int layer);
7278    private native void     nativeReplaceBaseContent(int content);
7279    private native void     nativeCopyBaseContentToPicture(Picture pict);
7280    private native boolean  nativeHasContent();
7281    private native void     nativeSetSelectionPointer(boolean set,
7282            float scale, int x, int y);
7283    private native boolean  nativeStartSelection(int x, int y);
7284    private native Rect     nativeSubtractLayers(Rect content);
7285    private native int      nativeTextGeneration();
7286    // Never call this version except by updateCachedTextfield(String) -
7287    // we always want to pass in our generation number.
7288    private native void     nativeUpdateCachedTextfield(String updatedText,
7289            int generation);
7290    private native boolean  nativeWordSelection(int x, int y);
7291    // return NO_LEFTEDGE means failure.
7292    static final int NO_LEFTEDGE = -1;
7293    native int nativeGetBlockLeftEdge(int x, int y, float scale);
7294
7295    // Returns a pointer to the scrollable LayerAndroid at the given point.
7296    private native int      nativeScrollableLayer(int x, int y);
7297    private native boolean  nativeScrollLayer(int layer, int dx, int dy);
7298}
7299