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