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