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