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