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