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