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