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