WebView.java revision 861368a307cb1763b567ba90e418b1523359ee71
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 anchor or image element URL at the last tapped point.
2184     * If hrefMsg is null, this method returns immediately and does not
2185     * dispatch hrefMsg to its target. If the tapped point hits an image,
2186     * an anchor, or an image in an anchor, the message associates
2187     * strings in named keys in its data. The value paired with the key
2188     * may be an empty string.
2189     *
2190     * @param hrefMsg This message will be dispatched with the result of the
2191     *                request. The message data contains three keys:
2192     *                - "url" returns the anchor's href attribute.
2193     *                - "title" returns the anchor's text.
2194     *                - "src" returns the image's src attribute.
2195     */
2196    public void requestFocusNodeHref(Message hrefMsg) {
2197        if (hrefMsg == null) {
2198            return;
2199        }
2200        int contentX = viewToContentX((int) mLastTouchX + mScrollX);
2201        int contentY = viewToContentY((int) mLastTouchY + mScrollY);
2202        mWebViewCore.sendMessage(EventHub.REQUEST_CURSOR_HREF,
2203                contentX, contentY, hrefMsg);
2204    }
2205
2206    /**
2207     * Request the url of the image last touched by the user. msg will be sent
2208     * to its target with a String representing the url as its object.
2209     *
2210     * @param msg This message will be dispatched with the result of the request
2211     *            as the data member with "url" as key. The result can be null.
2212     */
2213    public void requestImageRef(Message msg) {
2214        if (0 == mNativeClass) return; // client isn't initialized
2215        int contentX = viewToContentX((int) mLastTouchX + mScrollX);
2216        int contentY = viewToContentY((int) mLastTouchY + mScrollY);
2217        String ref = nativeImageURI(contentX, contentY);
2218        Bundle data = msg.getData();
2219        data.putString("url", ref);
2220        msg.setData(data);
2221        msg.sendToTarget();
2222    }
2223
2224    static int pinLoc(int x, int viewMax, int docMax) {
2225//        Log.d(LOGTAG, "-- pinLoc " + x + " " + viewMax + " " + docMax);
2226        if (docMax < viewMax) {   // the doc has room on the sides for "blank"
2227            // pin the short document to the top/left of the screen
2228            x = 0;
2229//            Log.d(LOGTAG, "--- center " + x);
2230        } else if (x < 0) {
2231            x = 0;
2232//            Log.d(LOGTAG, "--- zero");
2233        } else if (x + viewMax > docMax) {
2234            x = docMax - viewMax;
2235//            Log.d(LOGTAG, "--- pin " + x);
2236        }
2237        return x;
2238    }
2239
2240    // Expects x in view coordinates
2241    int pinLocX(int x) {
2242        if (mInOverScrollMode) return x;
2243        return pinLoc(x, getViewWidth(), computeRealHorizontalScrollRange());
2244    }
2245
2246    // Expects y in view coordinates
2247    int pinLocY(int y) {
2248        if (mInOverScrollMode) return y;
2249        return pinLoc(y, getViewHeightWithTitle(),
2250                      computeRealVerticalScrollRange() + getTitleHeight());
2251    }
2252
2253    /**
2254     * A title bar which is embedded in this WebView, and scrolls along with it
2255     * vertically, but not horizontally.
2256     */
2257    private View mTitleBar;
2258
2259    /**
2260     * Add or remove a title bar to be embedded into the WebView, and scroll
2261     * along with it vertically, while remaining in view horizontally. Pass
2262     * null to remove the title bar from the WebView, and return to drawing
2263     * the WebView normally without translating to account for the title bar.
2264     * @hide
2265     */
2266    public void setEmbeddedTitleBar(View v) {
2267        if (mTitleBar == v) return;
2268        if (mTitleBar != null) {
2269            removeView(mTitleBar);
2270        }
2271        if (null != v) {
2272            addView(v, new AbsoluteLayout.LayoutParams(
2273                    ViewGroup.LayoutParams.MATCH_PARENT,
2274                    ViewGroup.LayoutParams.WRAP_CONTENT, 0, 0));
2275        }
2276        mTitleBar = v;
2277    }
2278
2279    /**
2280     * Given a distance in view space, convert it to content space. Note: this
2281     * does not reflect translation, just scaling, so this should not be called
2282     * with coordinates, but should be called for dimensions like width or
2283     * height.
2284     */
2285    private int viewToContentDimension(int d) {
2286        return Math.round(d * mZoomManager.getInvScale());
2287    }
2288
2289    /**
2290     * Given an x coordinate in view space, convert it to content space.  Also
2291     * may be used for absolute heights (such as for the WebTextView's
2292     * textSize, which is unaffected by the height of the title bar).
2293     */
2294    /*package*/ int viewToContentX(int x) {
2295        return viewToContentDimension(x);
2296    }
2297
2298    /**
2299     * Given a y coordinate in view space, convert it to content space.
2300     * Takes into account the height of the title bar if there is one
2301     * embedded into the WebView.
2302     */
2303    /*package*/ int viewToContentY(int y) {
2304        return viewToContentDimension(y - getTitleHeight());
2305    }
2306
2307    /**
2308     * Given a x coordinate in view space, convert it to content space.
2309     * Returns the result as a float.
2310     */
2311    private float viewToContentXf(int x) {
2312        return x * mZoomManager.getInvScale();
2313    }
2314
2315    /**
2316     * Given a y coordinate in view space, convert it to content space.
2317     * Takes into account the height of the title bar if there is one
2318     * embedded into the WebView. Returns the result as a float.
2319     */
2320    private float viewToContentYf(int y) {
2321        return (y - getTitleHeight()) * mZoomManager.getInvScale();
2322    }
2323
2324    /**
2325     * Given a distance in content space, convert it to view space. Note: this
2326     * does not reflect translation, just scaling, so this should not be called
2327     * with coordinates, but should be called for dimensions like width or
2328     * height.
2329     */
2330    /*package*/ int contentToViewDimension(int d) {
2331        return Math.round(d * mZoomManager.getScale());
2332    }
2333
2334    /**
2335     * Given an x coordinate in content space, convert it to view
2336     * space.
2337     */
2338    /*package*/ int contentToViewX(int x) {
2339        return contentToViewDimension(x);
2340    }
2341
2342    /**
2343     * Given a y coordinate in content space, convert it to view
2344     * space.  Takes into account the height of the title bar.
2345     */
2346    /*package*/ int contentToViewY(int y) {
2347        return contentToViewDimension(y) + getTitleHeight();
2348    }
2349
2350    private Rect contentToViewRect(Rect x) {
2351        return new Rect(contentToViewX(x.left), contentToViewY(x.top),
2352                        contentToViewX(x.right), contentToViewY(x.bottom));
2353    }
2354
2355    /*  To invalidate a rectangle in content coordinates, we need to transform
2356        the rect into view coordinates, so we can then call invalidate(...).
2357
2358        Normally, we would just call contentToView[XY](...), which eventually
2359        calls Math.round(coordinate * mActualScale). However, for invalidates,
2360        we need to account for the slop that occurs with antialiasing. To
2361        address that, we are a little more liberal in the size of the rect that
2362        we invalidate.
2363
2364        This liberal calculation calls floor() for the top/left, and ceil() for
2365        the bottom/right coordinates. This catches the possible extra pixels of
2366        antialiasing that we might have missed with just round().
2367     */
2368
2369    // Called by JNI to invalidate the View, given rectangle coordinates in
2370    // content space
2371    private void viewInvalidate(int l, int t, int r, int b) {
2372        final float scale = mZoomManager.getScale();
2373        final int dy = getTitleHeight();
2374        invalidate((int)Math.floor(l * scale),
2375                   (int)Math.floor(t * scale) + dy,
2376                   (int)Math.ceil(r * scale),
2377                   (int)Math.ceil(b * scale) + dy);
2378    }
2379
2380    // Called by JNI to invalidate the View after a delay, given rectangle
2381    // coordinates in content space
2382    private void viewInvalidateDelayed(long delay, int l, int t, int r, int b) {
2383        final float scale = mZoomManager.getScale();
2384        final int dy = getTitleHeight();
2385        postInvalidateDelayed(delay,
2386                              (int)Math.floor(l * scale),
2387                              (int)Math.floor(t * scale) + dy,
2388                              (int)Math.ceil(r * scale),
2389                              (int)Math.ceil(b * scale) + dy);
2390    }
2391
2392    private void invalidateContentRect(Rect r) {
2393        viewInvalidate(r.left, r.top, r.right, r.bottom);
2394    }
2395
2396    // stop the scroll animation, and don't let a subsequent fling add
2397    // to the existing velocity
2398    private void abortAnimation() {
2399        mScroller.abortAnimation();
2400        mLastVelocity = 0;
2401    }
2402
2403    /* call from webcoreview.draw(), so we're still executing in the UI thread
2404    */
2405    private void recordNewContentSize(int w, int h, boolean updateLayout) {
2406
2407        // premature data from webkit, ignore
2408        if ((w | h) == 0) {
2409            return;
2410        }
2411
2412        // don't abort a scroll animation if we didn't change anything
2413        if (mContentWidth != w || mContentHeight != h) {
2414            // record new dimensions
2415            mContentWidth = w;
2416            mContentHeight = h;
2417            // If history Picture is drawn, don't update scroll. They will be
2418            // updated when we get out of that mode.
2419            if (!mDrawHistory) {
2420                // repin our scroll, taking into account the new content size
2421                updateScrollCoordinates(pinLocX(mScrollX), pinLocY(mScrollY));
2422                if (!mScroller.isFinished()) {
2423                    // We are in the middle of a scroll.  Repin the final scroll
2424                    // position.
2425                    mScroller.setFinalX(pinLocX(mScroller.getFinalX()));
2426                    mScroller.setFinalY(pinLocY(mScroller.getFinalY()));
2427                }
2428            }
2429        }
2430        contentSizeChanged(updateLayout);
2431    }
2432
2433    // Used to avoid sending many visible rect messages.
2434    private Rect mLastVisibleRectSent;
2435    private Rect mLastGlobalRect;
2436
2437    Rect sendOurVisibleRect() {
2438        if (mZoomManager.isPreventingWebkitUpdates()) return mLastVisibleRectSent;
2439        Rect rect = new Rect();
2440        calcOurContentVisibleRect(rect);
2441        // Rect.equals() checks for null input.
2442        if (!rect.equals(mLastVisibleRectSent)) {
2443            Point pos = new Point(rect.left, rect.top);
2444            mWebViewCore.sendMessage(EventHub.SET_SCROLL_OFFSET,
2445                    nativeMoveGeneration(), mUserScroll ? 1 : 0, pos);
2446            mLastVisibleRectSent = rect;
2447            mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
2448        }
2449        Rect globalRect = new Rect();
2450        if (getGlobalVisibleRect(globalRect)
2451                && !globalRect.equals(mLastGlobalRect)) {
2452            if (DebugFlags.WEB_VIEW) {
2453                Log.v(LOGTAG, "sendOurVisibleRect=(" + globalRect.left + ","
2454                        + globalRect.top + ",r=" + globalRect.right + ",b="
2455                        + globalRect.bottom);
2456            }
2457            // TODO: the global offset is only used by windowRect()
2458            // in ChromeClientAndroid ; other clients such as touch
2459            // and mouse events could return view + screen relative points.
2460            mWebViewCore.sendMessage(EventHub.SET_GLOBAL_BOUNDS, globalRect);
2461            mLastGlobalRect = globalRect;
2462        }
2463        return rect;
2464    }
2465
2466    // Sets r to be the visible rectangle of our webview in view coordinates
2467    private void calcOurVisibleRect(Rect r) {
2468        Point p = new Point();
2469        getGlobalVisibleRect(r, p);
2470        r.offset(-p.x, -p.y);
2471    }
2472
2473    // Sets r to be our visible rectangle in content coordinates
2474    private void calcOurContentVisibleRect(Rect r) {
2475        calcOurVisibleRect(r);
2476        r.left = viewToContentX(r.left);
2477        // viewToContentY will remove the total height of the title bar.  Add
2478        // the visible height back in to account for the fact that if the title
2479        // bar is partially visible, the part of the visible rect which is
2480        // displaying our content is displaced by that amount.
2481        r.top = viewToContentY(r.top + getVisibleTitleHeight());
2482        r.right = viewToContentX(r.right);
2483        r.bottom = viewToContentY(r.bottom);
2484    }
2485
2486    // Sets r to be our visible rectangle in content coordinates. We use this
2487    // method on the native side to compute the position of the fixed layers.
2488    // Uses floating coordinates (necessary to correctly place elements when
2489    // the scale factor is not 1)
2490    private void calcOurContentVisibleRectF(RectF r) {
2491        Rect ri = new Rect(0,0,0,0);
2492        calcOurVisibleRect(ri);
2493        r.left = viewToContentXf(ri.left);
2494        // viewToContentY will remove the total height of the title bar.  Add
2495        // the visible height back in to account for the fact that if the title
2496        // bar is partially visible, the part of the visible rect which is
2497        // displaying our content is displaced by that amount.
2498        r.top = viewToContentYf(ri.top + getVisibleTitleHeight());
2499        r.right = viewToContentXf(ri.right);
2500        r.bottom = viewToContentYf(ri.bottom);
2501    }
2502
2503    static class ViewSizeData {
2504        int mWidth;
2505        int mHeight;
2506        int mTextWrapWidth;
2507        int mAnchorX;
2508        int mAnchorY;
2509        float mScale;
2510        boolean mIgnoreHeight;
2511    }
2512
2513    /**
2514     * Compute unzoomed width and height, and if they differ from the last
2515     * values we sent, send them to webkit (to be used as new viewport)
2516     *
2517     * @param force ensures that the message is sent to webkit even if the width
2518     * or height has not changed since the last message
2519     *
2520     * @return true if new values were sent
2521     */
2522    boolean sendViewSizeZoom(boolean force) {
2523        if (mZoomManager.isPreventingWebkitUpdates()) return false;
2524
2525        int viewWidth = getViewWidth();
2526        int newWidth = Math.round(viewWidth * mZoomManager.getInvScale());
2527        int newHeight = Math.round((getViewHeightWithTitle() - getTitleHeight()) * mZoomManager.getInvScale());
2528        /*
2529         * Because the native side may have already done a layout before the
2530         * View system was able to measure us, we have to send a height of 0 to
2531         * remove excess whitespace when we grow our width. This will trigger a
2532         * layout and a change in content size. This content size change will
2533         * mean that contentSizeChanged will either call this method directly or
2534         * indirectly from onSizeChanged.
2535         */
2536        if (newWidth > mLastWidthSent && mWrapContent) {
2537            newHeight = 0;
2538        }
2539        // Avoid sending another message if the dimensions have not changed.
2540        if (newWidth != mLastWidthSent || newHeight != mLastHeightSent || force) {
2541            ViewSizeData data = new ViewSizeData();
2542            data.mWidth = newWidth;
2543            data.mHeight = newHeight;
2544            data.mTextWrapWidth = Math.round(viewWidth / mZoomManager.getTextWrapScale());
2545            data.mScale = mZoomManager.getScale();
2546            data.mIgnoreHeight = mZoomManager.isFixedLengthAnimationInProgress()
2547                    && !mHeightCanMeasure;
2548            data.mAnchorX = mZoomManager.getDocumentAnchorX();
2549            data.mAnchorY = mZoomManager.getDocumentAnchorY();
2550            mWebViewCore.sendMessage(EventHub.VIEW_SIZE_CHANGED, data);
2551            mLastWidthSent = newWidth;
2552            mLastHeightSent = newHeight;
2553            mZoomManager.clearDocumentAnchor();
2554            return true;
2555        }
2556        return false;
2557    }
2558
2559    private int computeRealHorizontalScrollRange() {
2560        if (mDrawHistory) {
2561            return mHistoryWidth;
2562        } else if (mHorizontalScrollBarMode == SCROLLBAR_ALWAYSOFF
2563                && !mZoomManager.canZoomOut()) {
2564            // only honor the scrollbar mode when it is at minimum zoom level
2565            return computeHorizontalScrollExtent();
2566        } else {
2567            // to avoid rounding error caused unnecessary scrollbar, use floor
2568            return (int) Math.floor(mContentWidth * mZoomManager.getScale());
2569        }
2570    }
2571
2572    @Override
2573    protected int computeHorizontalScrollRange() {
2574        int range = computeRealHorizontalScrollRange();
2575
2576        // Adjust reported range if overscrolled to compress the scroll bars
2577        final int scrollX = mScrollX;
2578        final int overscrollRight = computeMaxScrollX();
2579        if (scrollX < 0) {
2580            range -= scrollX;
2581        } else if (scrollX > overscrollRight) {
2582            range += scrollX - overscrollRight;
2583        }
2584
2585        return range;
2586    }
2587
2588    @Override
2589    protected int computeHorizontalScrollOffset() {
2590        return Math.max(mScrollX, 0);
2591    }
2592
2593    private int computeRealVerticalScrollRange() {
2594        if (mDrawHistory) {
2595            return mHistoryHeight;
2596        } else if (mVerticalScrollBarMode == SCROLLBAR_ALWAYSOFF
2597                && !mZoomManager.canZoomOut()) {
2598            // only honor the scrollbar mode when it is at minimum zoom level
2599            return computeVerticalScrollExtent();
2600        } else {
2601            // to avoid rounding error caused unnecessary scrollbar, use floor
2602            return (int) Math.floor(mContentHeight * mZoomManager.getScale());
2603        }
2604    }
2605
2606    @Override
2607    protected int computeVerticalScrollRange() {
2608        int range = computeRealVerticalScrollRange();
2609
2610        // Adjust reported range if overscrolled to compress the scroll bars
2611        final int scrollY = mScrollY;
2612        final int overscrollBottom = computeMaxScrollY();
2613        if (scrollY < 0) {
2614            range -= scrollY;
2615        } else if (scrollY > overscrollBottom) {
2616            range += scrollY - overscrollBottom;
2617        }
2618
2619        return range;
2620    }
2621
2622    @Override
2623    protected int computeVerticalScrollOffset() {
2624        return Math.max(mScrollY - getTitleHeight(), 0);
2625    }
2626
2627    @Override
2628    protected int computeVerticalScrollExtent() {
2629        return getViewHeight();
2630    }
2631
2632    /** @hide */
2633    @Override
2634    protected void onDrawVerticalScrollBar(Canvas canvas,
2635                                           Drawable scrollBar,
2636                                           int l, int t, int r, int b) {
2637        if (mScrollY < 0) {
2638            t -= mScrollY;
2639        }
2640        scrollBar.setBounds(l, t + getVisibleTitleHeight(), r, b);
2641        scrollBar.draw(canvas);
2642    }
2643
2644    @Override
2645    protected void onOverScrolled(int scrollX, int scrollY, boolean clampedX,
2646            boolean clampedY) {
2647        // Special-case layer scrolling so that we do not trigger normal scroll
2648        // updating.
2649        if (mTouchMode == TOUCH_DRAG_LAYER_MODE) {
2650            nativeScrollLayer(mScrollingLayer, scrollX, scrollY);
2651            mScrollingLayerRect.left = scrollX;
2652            mScrollingLayerRect.top = scrollY;
2653            invalidate();
2654            return;
2655        }
2656        mInOverScrollMode = false;
2657        int maxX = computeMaxScrollX();
2658        int maxY = computeMaxScrollY();
2659        if (maxX == 0) {
2660            // do not over scroll x if the page just fits the screen
2661            scrollX = pinLocX(scrollX);
2662        } else if (scrollX < 0 || scrollX > maxX) {
2663            mInOverScrollMode = true;
2664        }
2665        if (scrollY < 0 || scrollY > maxY) {
2666            mInOverScrollMode = true;
2667        }
2668
2669        int oldX = mScrollX;
2670        int oldY = mScrollY;
2671
2672        super.scrollTo(scrollX, scrollY);
2673
2674        if (mOverScrollGlow != null) {
2675            mOverScrollGlow.pullGlow(mScrollX, mScrollY, oldX, oldY, maxX, maxY);
2676        }
2677    }
2678
2679    /**
2680     * Get the url for the current page. This is not always the same as the url
2681     * passed to WebViewClient.onPageStarted because although the load for
2682     * that url has begun, the current page may not have changed.
2683     * @return The url for the current page.
2684     */
2685    public String getUrl() {
2686        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
2687        return h != null ? h.getUrl() : null;
2688    }
2689
2690    /**
2691     * Get the original url for the current page. This is not always the same
2692     * as the url passed to WebViewClient.onPageStarted because although the
2693     * load for that url has begun, the current page may not have changed.
2694     * Also, there may have been redirects resulting in a different url to that
2695     * originally requested.
2696     * @return The url that was originally requested for the current page.
2697     */
2698    public String getOriginalUrl() {
2699        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
2700        return h != null ? h.getOriginalUrl() : null;
2701    }
2702
2703    /**
2704     * Get the title for the current page. This is the title of the current page
2705     * until WebViewClient.onReceivedTitle is called.
2706     * @return The title for the current page.
2707     */
2708    public String getTitle() {
2709        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
2710        return h != null ? h.getTitle() : null;
2711    }
2712
2713    /**
2714     * Get the favicon for the current page. This is the favicon of the current
2715     * page until WebViewClient.onReceivedIcon is called.
2716     * @return The favicon for the current page.
2717     */
2718    public Bitmap getFavicon() {
2719        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
2720        return h != null ? h.getFavicon() : null;
2721    }
2722
2723    /**
2724     * Get the touch icon url for the apple-touch-icon <link> element, or
2725     * a URL on this site's server pointing to the standard location of a
2726     * touch icon.
2727     * @hide
2728     */
2729    public String getTouchIconUrl() {
2730        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
2731        return h != null ? h.getTouchIconUrl() : null;
2732    }
2733
2734    /**
2735     * Get the progress for the current page.
2736     * @return The progress for the current page between 0 and 100.
2737     */
2738    public int getProgress() {
2739        return mCallbackProxy.getProgress();
2740    }
2741
2742    /**
2743     * @return the height of the HTML content.
2744     */
2745    public int getContentHeight() {
2746        return mContentHeight;
2747    }
2748
2749    /**
2750     * @return the width of the HTML content.
2751     * @hide
2752     */
2753    public int getContentWidth() {
2754        return mContentWidth;
2755    }
2756
2757    /**
2758     * Pause all layout, parsing, and JavaScript timers for all webviews. This
2759     * is a global requests, not restricted to just this webview. This can be
2760     * useful if the application has been paused.
2761     */
2762    public void pauseTimers() {
2763        mWebViewCore.sendMessage(EventHub.PAUSE_TIMERS);
2764    }
2765
2766    /**
2767     * Resume all layout, parsing, and JavaScript timers for all webviews.
2768     * This will resume dispatching all timers.
2769     */
2770    public void resumeTimers() {
2771        mWebViewCore.sendMessage(EventHub.RESUME_TIMERS);
2772    }
2773
2774    /**
2775     * Call this to pause any extra processing associated with this WebView and
2776     * its associated DOM, plugins, JavaScript etc. For example, if the WebView
2777     * is taken offscreen, this could be called to reduce unnecessary CPU or
2778     * network traffic. When the WebView is again "active", call onResume().
2779     *
2780     * Note that this differs from pauseTimers(), which affects all WebViews.
2781     */
2782    public void onPause() {
2783        if (!mIsPaused) {
2784            mIsPaused = true;
2785            mWebViewCore.sendMessage(EventHub.ON_PAUSE);
2786        }
2787    }
2788
2789    /**
2790     * Call this to resume a WebView after a previous call to onPause().
2791     */
2792    public void onResume() {
2793        if (mIsPaused) {
2794            mIsPaused = false;
2795            mWebViewCore.sendMessage(EventHub.ON_RESUME);
2796        }
2797    }
2798
2799    /**
2800     * Returns true if the view is paused, meaning onPause() was called. Calling
2801     * onResume() sets the paused state back to false.
2802     * @hide
2803     */
2804    public boolean isPaused() {
2805        return mIsPaused;
2806    }
2807
2808    /**
2809     * Call this to inform the view that memory is low so that it can
2810     * free any available memory.
2811     */
2812    public void freeMemory() {
2813        mWebViewCore.sendMessage(EventHub.FREE_MEMORY);
2814    }
2815
2816    /**
2817     * Clear the resource cache. Note that the cache is per-application, so
2818     * this will clear the cache for all WebViews used.
2819     *
2820     * @param includeDiskFiles If false, only the RAM cache is cleared.
2821     */
2822    public void clearCache(boolean includeDiskFiles) {
2823        // Note: this really needs to be a static method as it clears cache for all
2824        // WebView. But we need mWebViewCore to send message to WebCore thread, so
2825        // we can't make this static.
2826        mWebViewCore.sendMessage(EventHub.CLEAR_CACHE,
2827                includeDiskFiles ? 1 : 0, 0);
2828    }
2829
2830    /**
2831     * Make sure that clearing the form data removes the adapter from the
2832     * currently focused textfield if there is one.
2833     */
2834    public void clearFormData() {
2835        if (inEditingMode()) {
2836            AutoCompleteAdapter adapter = null;
2837            mWebTextView.setAdapterCustom(adapter);
2838        }
2839    }
2840
2841    /**
2842     * Tell the WebView to clear its internal back/forward list.
2843     */
2844    public void clearHistory() {
2845        mCallbackProxy.getBackForwardList().setClearPending();
2846        mWebViewCore.sendMessage(EventHub.CLEAR_HISTORY);
2847    }
2848
2849    /**
2850     * Clear the SSL preferences table stored in response to proceeding with SSL
2851     * certificate errors.
2852     */
2853    public void clearSslPreferences() {
2854        mWebViewCore.sendMessage(EventHub.CLEAR_SSL_PREF_TABLE);
2855    }
2856
2857    /**
2858     * Return the WebBackForwardList for this WebView. This contains the
2859     * back/forward list for use in querying each item in the history stack.
2860     * This is a copy of the private WebBackForwardList so it contains only a
2861     * snapshot of the current state. Multiple calls to this method may return
2862     * different objects. The object returned from this method will not be
2863     * updated to reflect any new state.
2864     */
2865    public WebBackForwardList copyBackForwardList() {
2866        return mCallbackProxy.getBackForwardList().clone();
2867    }
2868
2869    /*
2870     * Highlight and scroll to the next occurance of String in findAll.
2871     * Wraps the page infinitely, and scrolls.  Must be called after
2872     * calling findAll.
2873     *
2874     * @param forward Direction to search.
2875     */
2876    public void findNext(boolean forward) {
2877        if (0 == mNativeClass) return; // client isn't initialized
2878        nativeFindNext(forward);
2879    }
2880
2881    /*
2882     * Find all instances of find on the page and highlight them.
2883     * @param find  String to find.
2884     * @return int  The number of occurances of the String "find"
2885     *              that were found.
2886     */
2887    public int findAll(String find) {
2888        if (0 == mNativeClass) return 0; // client isn't initialized
2889        int result = find != null ? nativeFindAll(find.toLowerCase(),
2890                find.toUpperCase(), find.equalsIgnoreCase(mLastFind)) : 0;
2891        invalidate();
2892        mLastFind = find;
2893        return result;
2894    }
2895
2896    /**
2897     * Start an ActionMode for finding text in this WebView.
2898     * @param text If non-null, will be the initial text to search for.
2899     *             Otherwise, the last String searched for in this WebView will
2900     *             be used to start.
2901     */
2902    public void showFindDialog(String text) {
2903        mFindCallback = new FindActionModeCallback(mContext);
2904        setFindIsUp(true);
2905        mFindCallback.setWebView(this);
2906        View titleBar = mTitleBar;
2907        startActionMode(mFindCallback);
2908        if (text == null) {
2909            text = mLastFind;
2910        }
2911        if (text != null) {
2912            mFindCallback.setText(text);
2913        }
2914    }
2915
2916    /**
2917     * Keep track of the find callback so that we can remove its titlebar if
2918     * necessary.
2919     */
2920    private FindActionModeCallback mFindCallback;
2921
2922    /**
2923     * Toggle whether the find dialog is showing, for both native and Java.
2924     */
2925    private void setFindIsUp(boolean isUp) {
2926        mFindIsUp = isUp;
2927        if (0 == mNativeClass) return; // client isn't initialized
2928        nativeSetFindIsUp(isUp);
2929    }
2930
2931    /**
2932     * Return the index of the currently highlighted match.
2933     */
2934    int findIndex() {
2935        if (0 == mNativeClass) return -1;
2936        return nativeFindIndex();
2937    }
2938
2939    // Used to know whether the find dialog is open.  Affects whether
2940    // or not we draw the highlights for matches.
2941    private boolean mFindIsUp;
2942
2943    // Keep track of the last string sent, so we can search again when find is
2944    // reopened.
2945    private String mLastFind;
2946
2947    /**
2948     * Return the first substring consisting of the address of a physical
2949     * location. Currently, only addresses in the United States are detected,
2950     * and consist of:
2951     * - a house number
2952     * - a street name
2953     * - a street type (Road, Circle, etc), either spelled out or abbreviated
2954     * - a city name
2955     * - a state or territory, either spelled out or two-letter abbr.
2956     * - an optional 5 digit or 9 digit zip code.
2957     *
2958     * All names must be correctly capitalized, and the zip code, if present,
2959     * must be valid for the state. The street type must be a standard USPS
2960     * spelling or abbreviation. The state or territory must also be spelled
2961     * or abbreviated using USPS standards. The house number may not exceed
2962     * five digits.
2963     * @param addr The string to search for addresses.
2964     *
2965     * @return the address, or if no address is found, return null.
2966     */
2967    public static String findAddress(String addr) {
2968        return findAddress(addr, false);
2969    }
2970
2971    /**
2972     * @hide
2973     * Return the first substring consisting of the address of a physical
2974     * location. Currently, only addresses in the United States are detected,
2975     * and consist of:
2976     * - a house number
2977     * - a street name
2978     * - a street type (Road, Circle, etc), either spelled out or abbreviated
2979     * - a city name
2980     * - a state or territory, either spelled out or two-letter abbr.
2981     * - an optional 5 digit or 9 digit zip code.
2982     *
2983     * Names are optionally capitalized, and the zip code, if present,
2984     * must be valid for the state. The street type must be a standard USPS
2985     * spelling or abbreviation. The state or territory must also be spelled
2986     * or abbreviated using USPS standards. The house number may not exceed
2987     * five digits.
2988     * @param addr The string to search for addresses.
2989     * @param caseInsensitive addr Set to true to make search ignore case.
2990     *
2991     * @return the address, or if no address is found, return null.
2992     */
2993    public static String findAddress(String addr, boolean caseInsensitive) {
2994        return WebViewCore.nativeFindAddress(addr, caseInsensitive);
2995    }
2996
2997    /*
2998     * Clear the highlighting surrounding text matches created by findAll.
2999     */
3000    public void clearMatches() {
3001        if (mNativeClass == 0)
3002            return;
3003        nativeSetFindIsEmpty();
3004        invalidate();
3005    }
3006
3007    /**
3008     * Called when the find ActionMode ends.
3009     */
3010    void notifyFindDialogDismissed() {
3011        mFindCallback = null;
3012        if (mWebViewCore == null) {
3013            return;
3014        }
3015        clearMatches();
3016        setFindIsUp(false);
3017        // Now that the dialog has been removed, ensure that we scroll to a
3018        // location that is not beyond the end of the page.
3019        pinScrollTo(mScrollX, mScrollY, false, 0);
3020        invalidate();
3021    }
3022
3023    /**
3024     * Query the document to see if it contains any image references. The
3025     * message object will be dispatched with arg1 being set to 1 if images
3026     * were found and 0 if the document does not reference any images.
3027     * @param response The message that will be dispatched with the result.
3028     */
3029    public void documentHasImages(Message response) {
3030        if (response == null) {
3031            return;
3032        }
3033        mWebViewCore.sendMessage(EventHub.DOC_HAS_IMAGES, response);
3034    }
3035
3036    /**
3037     * Request the scroller to abort any ongoing animation
3038     *
3039     * @hide
3040     */
3041    public void stopScroll() {
3042        mScroller.forceFinished(true);
3043        mLastVelocity = 0;
3044    }
3045
3046    @Override
3047    public void computeScroll() {
3048        if (mScroller.computeScrollOffset()) {
3049            int oldX = mScrollX;
3050            int oldY = mScrollY;
3051            int x = mScroller.getCurrX();
3052            int y = mScroller.getCurrY();
3053            invalidate();  // So we draw again
3054
3055            if (!mScroller.isFinished()) {
3056                int rangeX = computeMaxScrollX();
3057                int rangeY = computeMaxScrollY();
3058                int overflingDistance = mOverflingDistance;
3059
3060                // Use the layer's scroll data if needed.
3061                if (mTouchMode == TOUCH_DRAG_LAYER_MODE) {
3062                    oldX = mScrollingLayerRect.left;
3063                    oldY = mScrollingLayerRect.top;
3064                    rangeX = mScrollingLayerRect.right;
3065                    rangeY = mScrollingLayerRect.bottom;
3066                    // No overscrolling for layers.
3067                    overflingDistance = 0;
3068                }
3069
3070                overScrollBy(x - oldX, y - oldY, oldX, oldY,
3071                        rangeX, rangeY,
3072                        overflingDistance, overflingDistance, false);
3073
3074                if (mOverScrollGlow != null) {
3075                    mOverScrollGlow.absorbGlow(x, y, oldX, oldY, rangeX, rangeY);
3076                }
3077            } else {
3078                if (mTouchMode != TOUCH_DRAG_LAYER_MODE) {
3079                    mScrollX = x;
3080                    mScrollY = y;
3081                } else {
3082                    // Update the layer position instead of WebView.
3083                    nativeScrollLayer(mScrollingLayer, x, y);
3084                    mScrollingLayerRect.left = x;
3085                    mScrollingLayerRect.top = y;
3086                }
3087                abortAnimation();
3088                mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY);
3089                WebViewCore.resumePriority();
3090                if (!mSelectingText) {
3091                    WebViewCore.resumeUpdatePicture(mWebViewCore);
3092                }
3093            }
3094        } else {
3095            super.computeScroll();
3096        }
3097    }
3098
3099    private static int computeDuration(int dx, int dy) {
3100        int distance = Math.max(Math.abs(dx), Math.abs(dy));
3101        int duration = distance * 1000 / STD_SPEED;
3102        return Math.min(duration, MAX_DURATION);
3103    }
3104
3105    // helper to pin the scrollBy parameters (already in view coordinates)
3106    // returns true if the scroll was changed
3107    private boolean pinScrollBy(int dx, int dy, boolean animate, int animationDuration) {
3108        return pinScrollTo(mScrollX + dx, mScrollY + dy, animate, animationDuration);
3109    }
3110    // helper to pin the scrollTo parameters (already in view coordinates)
3111    // returns true if the scroll was changed
3112    private boolean pinScrollTo(int x, int y, boolean animate, int animationDuration) {
3113        x = pinLocX(x);
3114        y = pinLocY(y);
3115        int dx = x - mScrollX;
3116        int dy = y - mScrollY;
3117
3118        if ((dx | dy) == 0) {
3119            return false;
3120        }
3121        abortAnimation();
3122        if (animate) {
3123            //        Log.d(LOGTAG, "startScroll: " + dx + " " + dy);
3124            mScroller.startScroll(mScrollX, mScrollY, dx, dy,
3125                    animationDuration > 0 ? animationDuration : computeDuration(dx, dy));
3126            awakenScrollBars(mScroller.getDuration());
3127            invalidate();
3128        } else {
3129            scrollTo(x, y);
3130        }
3131        return true;
3132    }
3133
3134    // Scale from content to view coordinates, and pin.
3135    // Also called by jni webview.cpp
3136    private boolean setContentScrollBy(int cx, int cy, boolean animate) {
3137        if (mDrawHistory) {
3138            // disallow WebView to change the scroll position as History Picture
3139            // is used in the view system.
3140            // TODO: as we switchOutDrawHistory when trackball or navigation
3141            // keys are hit, this should be safe. Right?
3142            return false;
3143        }
3144        cx = contentToViewDimension(cx);
3145        cy = contentToViewDimension(cy);
3146        if (mHeightCanMeasure) {
3147            // move our visible rect according to scroll request
3148            if (cy != 0) {
3149                Rect tempRect = new Rect();
3150                calcOurVisibleRect(tempRect);
3151                tempRect.offset(cx, cy);
3152                requestRectangleOnScreen(tempRect);
3153            }
3154            // FIXME: We scroll horizontally no matter what because currently
3155            // ScrollView and ListView will not scroll horizontally.
3156            // FIXME: Why do we only scroll horizontally if there is no
3157            // vertical scroll?
3158//                Log.d(LOGTAG, "setContentScrollBy cy=" + cy);
3159            return cy == 0 && cx != 0 && pinScrollBy(cx, 0, animate, 0);
3160        } else {
3161            return pinScrollBy(cx, cy, animate, 0);
3162        }
3163    }
3164
3165    /**
3166     * Called by CallbackProxy when the page starts loading.
3167     * @param url The URL of the page which has started loading.
3168     */
3169    /* package */ void onPageStarted(String url) {
3170        // every time we start a new page, we want to reset the
3171        // WebView certificate:  if the new site is secure, we
3172        // will reload it and get a new certificate set;
3173        // if the new site is not secure, the certificate must be
3174        // null, and that will be the case
3175        setCertificate(null);
3176
3177        // reset the flag since we set to true in if need after
3178        // loading is see onPageFinished(Url)
3179        mAccessibilityScriptInjected = false;
3180    }
3181
3182    /**
3183     * Called by CallbackProxy when the page finishes loading.
3184     * @param url The URL of the page which has finished loading.
3185     */
3186    /* package */ void onPageFinished(String url) {
3187        if (mPageThatNeedsToSlideTitleBarOffScreen != null) {
3188            // If the user is now on a different page, or has scrolled the page
3189            // past the point where the title bar is offscreen, ignore the
3190            // scroll request.
3191            if (mPageThatNeedsToSlideTitleBarOffScreen.equals(url)
3192                    && mScrollX == 0 && mScrollY == 0) {
3193                pinScrollTo(0, mYDistanceToSlideTitleOffScreen, true,
3194                        SLIDE_TITLE_DURATION);
3195            }
3196            mPageThatNeedsToSlideTitleBarOffScreen = null;
3197        }
3198
3199        injectAccessibilityForUrl(url);
3200    }
3201
3202    /**
3203     * This method injects accessibility in the loaded document if accessibility
3204     * is enabled. If JavaScript is enabled we try to inject a URL specific script.
3205     * If no URL specific script is found or JavaScript is disabled we fallback to
3206     * the default {@link AccessibilityInjector} implementation.
3207     * </p>
3208     * If the URL has the "axs" paramter set to 1 it has already done the
3209     * script injection so we do nothing. If the parameter is set to 0
3210     * the URL opts out accessibility script injection so we fall back to
3211     * the default {@link AccessibilityInjector}.
3212     * </p>
3213     * Note: If the user has not opted-in the accessibility script injection no scripts
3214     * are injected rather the default {@link AccessibilityInjector} implementation
3215     * is used.
3216     *
3217     * @param url The URL loaded by this {@link WebView}.
3218     */
3219    private void injectAccessibilityForUrl(String url) {
3220        AccessibilityManager accessibilityManager = AccessibilityManager.getInstance(mContext);
3221
3222        if (!accessibilityManager.isEnabled()) {
3223            // it is possible that accessibility was turned off between reloads
3224            ensureAccessibilityScriptInjectorInstance(false);
3225            return;
3226        }
3227
3228        if (!getSettings().getJavaScriptEnabled()) {
3229            // no JS so we fallback to the basic buil-in support
3230            ensureAccessibilityScriptInjectorInstance(true);
3231            return;
3232        }
3233
3234        // check the URL "axs" parameter to choose appropriate action
3235        int axsParameterValue = getAxsUrlParameterValue(url);
3236        if (axsParameterValue == ACCESSIBILITY_SCRIPT_INJECTION_UNDEFINED) {
3237            boolean onDeviceScriptInjectionEnabled = (Settings.Secure.getInt(mContext
3238                    .getContentResolver(), Settings.Secure.ACCESSIBILITY_SCRIPT_INJECTION, 0) == 1);
3239            if (onDeviceScriptInjectionEnabled) {
3240                ensureAccessibilityScriptInjectorInstance(false);
3241                // neither script injected nor script injection opted out => we inject
3242                loadUrl(ACCESSIBILITY_SCRIPT_CHOOSER_JAVASCRIPT);
3243                // TODO: Set this flag after successfull script injection. Maybe upon injection
3244                // the chooser should update the meta tag and we check it to declare success
3245                mAccessibilityScriptInjected = true;
3246            } else {
3247                // injection disabled so we fallback to the basic built-in support
3248                ensureAccessibilityScriptInjectorInstance(true);
3249            }
3250        } else if (axsParameterValue == ACCESSIBILITY_SCRIPT_INJECTION_OPTED_OUT) {
3251            // injection opted out so we fallback to the basic buil-in support
3252            ensureAccessibilityScriptInjectorInstance(true);
3253        } else if (axsParameterValue == ACCESSIBILITY_SCRIPT_INJECTION_PROVIDED) {
3254            ensureAccessibilityScriptInjectorInstance(false);
3255            // the URL provides accessibility but we still need to add our generic script
3256            loadUrl(ACCESSIBILITY_SCRIPT_CHOOSER_JAVASCRIPT);
3257        } else {
3258            Log.e(LOGTAG, "Unknown URL value for the \"axs\" URL parameter: " + axsParameterValue);
3259        }
3260    }
3261
3262    /**
3263     * Ensures the instance of the {@link AccessibilityInjector} to be present ot not.
3264     *
3265     * @param present True to ensure an insance, false to ensure no instance.
3266     */
3267    private void ensureAccessibilityScriptInjectorInstance(boolean present) {
3268        if (present && mAccessibilityInjector == null) {
3269            mAccessibilityInjector = new AccessibilityInjector(this);
3270        } else {
3271            mAccessibilityInjector = null;
3272        }
3273    }
3274
3275    /**
3276     * Gets the "axs" URL parameter value.
3277     *
3278     * @param url A url to fetch the paramter from.
3279     * @return The parameter value if such, -1 otherwise.
3280     */
3281    private int getAxsUrlParameterValue(String url) {
3282        if (mMatchAxsUrlParameterPattern == null) {
3283            mMatchAxsUrlParameterPattern = Pattern.compile(PATTERN_MATCH_AXS_URL_PARAMETER);
3284        }
3285        Matcher matcher = mMatchAxsUrlParameterPattern.matcher(url);
3286        if (matcher.find()) {
3287            String keyValuePair = url.substring(matcher.start(), matcher.end());
3288            return Integer.parseInt(keyValuePair.split("=")[1]);
3289        }
3290        return -1;
3291    }
3292
3293    /**
3294     * The URL of a page that sent a message to scroll the title bar off screen.
3295     *
3296     * Many mobile sites tell the page to scroll to (0,1) in order to scroll the
3297     * title bar off the screen.  Sometimes, the scroll position is set before
3298     * the page finishes loading.  Rather than scrolling while the page is still
3299     * loading, keep track of the URL and new scroll position so we can perform
3300     * the scroll once the page finishes loading.
3301     */
3302    private String mPageThatNeedsToSlideTitleBarOffScreen;
3303
3304    /**
3305     * The destination Y scroll position to be used when the page finishes
3306     * loading.  See mPageThatNeedsToSlideTitleBarOffScreen.
3307     */
3308    private int mYDistanceToSlideTitleOffScreen;
3309
3310    // scale from content to view coordinates, and pin
3311    // return true if pin caused the final x/y different than the request cx/cy,
3312    // and a future scroll may reach the request cx/cy after our size has
3313    // changed
3314    // return false if the view scroll to the exact position as it is requested,
3315    // where negative numbers are taken to mean 0
3316    private boolean setContentScrollTo(int cx, int cy) {
3317        if (mDrawHistory) {
3318            // disallow WebView to change the scroll position as History Picture
3319            // is used in the view system.
3320            // One known case where this is called is that WebCore tries to
3321            // restore the scroll position. As history Picture already uses the
3322            // saved scroll position, it is ok to skip this.
3323            return false;
3324        }
3325        int vx;
3326        int vy;
3327        if ((cx | cy) == 0) {
3328            // If the page is being scrolled to (0,0), do not add in the title
3329            // bar's height, and simply scroll to (0,0). (The only other work
3330            // in contentToView_ is to multiply, so this would not change 0.)
3331            vx = 0;
3332            vy = 0;
3333        } else {
3334            vx = contentToViewX(cx);
3335            vy = contentToViewY(cy);
3336        }
3337//        Log.d(LOGTAG, "content scrollTo [" + cx + " " + cy + "] view=[" +
3338//                      vx + " " + vy + "]");
3339        // Some mobile sites attempt to scroll the title bar off the page by
3340        // scrolling to (0,1).  If we are at the top left corner of the
3341        // page, assume this is an attempt to scroll off the title bar, and
3342        // animate the title bar off screen slowly enough that the user can see
3343        // it.
3344        if (cx == 0 && cy == 1 && mScrollX == 0 && mScrollY == 0
3345                && mTitleBar != null) {
3346            // FIXME: 100 should be defined somewhere as our max progress.
3347            if (getProgress() < 100) {
3348                // Wait to scroll the title bar off screen until the page has
3349                // finished loading.  Keep track of the URL and the destination
3350                // Y position
3351                mPageThatNeedsToSlideTitleBarOffScreen = getUrl();
3352                mYDistanceToSlideTitleOffScreen = vy;
3353            } else {
3354                pinScrollTo(vx, vy, true, SLIDE_TITLE_DURATION);
3355            }
3356            // Since we are animating, we have not yet reached the desired
3357            // scroll position.  Do not return true to request another attempt
3358            return false;
3359        }
3360        pinScrollTo(vx, vy, false, 0);
3361        // If the request was to scroll to a negative coordinate, treat it as if
3362        // it was a request to scroll to 0
3363        if ((mScrollX != vx && cx >= 0) || (mScrollY != vy && cy >= 0)) {
3364            return true;
3365        } else {
3366            return false;
3367        }
3368    }
3369
3370    // scale from content to view coordinates, and pin
3371    private void spawnContentScrollTo(int cx, int cy) {
3372        if (mDrawHistory) {
3373            // disallow WebView to change the scroll position as History Picture
3374            // is used in the view system.
3375            return;
3376        }
3377        int vx = contentToViewX(cx);
3378        int vy = contentToViewY(cy);
3379        pinScrollTo(vx, vy, true, 0);
3380    }
3381
3382    /**
3383     * These are from webkit, and are in content coordinate system (unzoomed)
3384     */
3385    private void contentSizeChanged(boolean updateLayout) {
3386        // suppress 0,0 since we usually see real dimensions soon after
3387        // this avoids drawing the prev content in a funny place. If we find a
3388        // way to consolidate these notifications, this check may become
3389        // obsolete
3390        if ((mContentWidth | mContentHeight) == 0) {
3391            return;
3392        }
3393
3394        if (mHeightCanMeasure) {
3395            if (getMeasuredHeight() != contentToViewDimension(mContentHeight)
3396                    || updateLayout) {
3397                requestLayout();
3398            }
3399        } else if (mWidthCanMeasure) {
3400            if (getMeasuredWidth() != contentToViewDimension(mContentWidth)
3401                    || updateLayout) {
3402                requestLayout();
3403            }
3404        } else {
3405            // If we don't request a layout, try to send our view size to the
3406            // native side to ensure that WebCore has the correct dimensions.
3407            sendViewSizeZoom(false);
3408        }
3409    }
3410
3411    /**
3412     * Set the WebViewClient that will receive various notifications and
3413     * requests. This will replace the current handler.
3414     * @param client An implementation of WebViewClient.
3415     */
3416    public void setWebViewClient(WebViewClient client) {
3417        mCallbackProxy.setWebViewClient(client);
3418    }
3419
3420    /**
3421     * Gets the WebViewClient
3422     * @return the current WebViewClient instance.
3423     *
3424     *@hide pending API council approval.
3425     */
3426    public WebViewClient getWebViewClient() {
3427        return mCallbackProxy.getWebViewClient();
3428    }
3429
3430    /**
3431     * Register the interface to be used when content can not be handled by
3432     * the rendering engine, and should be downloaded instead. This will replace
3433     * the current handler.
3434     * @param listener An implementation of DownloadListener.
3435     */
3436    public void setDownloadListener(DownloadListener listener) {
3437        mCallbackProxy.setDownloadListener(listener);
3438    }
3439
3440    /**
3441     * Set the chrome handler. This is an implementation of WebChromeClient for
3442     * use in handling JavaScript dialogs, favicons, titles, and the progress.
3443     * This will replace the current handler.
3444     * @param client An implementation of WebChromeClient.
3445     */
3446    public void setWebChromeClient(WebChromeClient client) {
3447        mCallbackProxy.setWebChromeClient(client);
3448    }
3449
3450    /**
3451     * Gets the chrome handler.
3452     * @return the current WebChromeClient instance.
3453     *
3454     * @hide API council approval.
3455     */
3456    public WebChromeClient getWebChromeClient() {
3457        return mCallbackProxy.getWebChromeClient();
3458    }
3459
3460    /**
3461     * Set the back/forward list client. This is an implementation of
3462     * WebBackForwardListClient for handling new items and changes in the
3463     * history index.
3464     * @param client An implementation of WebBackForwardListClient.
3465     * {@hide}
3466     */
3467    public void setWebBackForwardListClient(WebBackForwardListClient client) {
3468        mCallbackProxy.setWebBackForwardListClient(client);
3469    }
3470
3471    /**
3472     * Gets the WebBackForwardListClient.
3473     * {@hide}
3474     */
3475    public WebBackForwardListClient getWebBackForwardListClient() {
3476        return mCallbackProxy.getWebBackForwardListClient();
3477    }
3478
3479    /**
3480     * Set the Picture listener. This is an interface used to receive
3481     * notifications of a new Picture.
3482     * @param listener An implementation of WebView.PictureListener.
3483     */
3484    public void setPictureListener(PictureListener listener) {
3485        mPictureListener = listener;
3486    }
3487
3488    /**
3489     * {@hide}
3490     */
3491    /* FIXME: Debug only! Remove for SDK! */
3492    public void externalRepresentation(Message callback) {
3493        mWebViewCore.sendMessage(EventHub.REQUEST_EXT_REPRESENTATION, callback);
3494    }
3495
3496    /**
3497     * {@hide}
3498     */
3499    /* FIXME: Debug only! Remove for SDK! */
3500    public void documentAsText(Message callback) {
3501        mWebViewCore.sendMessage(EventHub.REQUEST_DOC_AS_TEXT, callback);
3502    }
3503
3504    /**
3505     * Use this function to bind an object to JavaScript so that the
3506     * methods can be accessed from JavaScript.
3507     * <p><strong>IMPORTANT:</strong>
3508     * <ul>
3509     * <li> Using addJavascriptInterface() allows JavaScript to control your
3510     * application. This can be a very useful feature or a dangerous security
3511     * issue. When the HTML in the WebView is untrustworthy (for example, part
3512     * or all of the HTML is provided by some person or process), then an
3513     * attacker could inject HTML that will execute your code and possibly any
3514     * code of the attacker's choosing.<br>
3515     * Do not use addJavascriptInterface() unless all of the HTML in this
3516     * WebView was written by you.</li>
3517     * <li> The Java object that is bound runs in another thread and not in
3518     * the thread that it was constructed in.</li>
3519     * </ul></p>
3520     * @param obj The class instance to bind to JavaScript, null instances are
3521     *            ignored.
3522     * @param interfaceName The name to used to expose the instance in
3523     *                      JavaScript.
3524     */
3525    public void addJavascriptInterface(Object obj, String interfaceName) {
3526        if (obj == null) {
3527            return;
3528        }
3529        WebViewCore.JSInterfaceData arg = new WebViewCore.JSInterfaceData();
3530        arg.mObject = obj;
3531        arg.mInterfaceName = interfaceName;
3532        mWebViewCore.sendMessage(EventHub.ADD_JS_INTERFACE, arg);
3533    }
3534
3535    /**
3536     * Removes a previously added JavaScript interface with the given name.
3537     * @param interfaceName The name of the interface to remove.
3538     */
3539    public void removeJavascriptInterface(String interfaceName) {
3540        WebViewCore.JSInterfaceData arg = new WebViewCore.JSInterfaceData();
3541        arg.mInterfaceName = interfaceName;
3542        mWebViewCore.sendMessage(EventHub.REMOVE_JS_INTERFACE, arg);
3543    }
3544
3545    /**
3546     * Return the WebSettings object used to control the settings for this
3547     * WebView.
3548     * @return A WebSettings object that can be used to control this WebView's
3549     *         settings.
3550     */
3551    public WebSettings getSettings() {
3552        return (mWebViewCore != null) ? mWebViewCore.getSettings() : null;
3553    }
3554
3555   /**
3556    * Return the list of currently loaded plugins.
3557    * @return The list of currently loaded plugins.
3558    *
3559    * @deprecated This was used for Gears, which has been deprecated.
3560    */
3561    @Deprecated
3562    public static synchronized PluginList getPluginList() {
3563        return new PluginList();
3564    }
3565
3566   /**
3567    * @deprecated This was used for Gears, which has been deprecated.
3568    */
3569    @Deprecated
3570    public void refreshPlugins(boolean reloadOpenPages) { }
3571
3572    //-------------------------------------------------------------------------
3573    // Override View methods
3574    //-------------------------------------------------------------------------
3575
3576    @Override
3577    protected void finalize() throws Throwable {
3578        try {
3579            destroy();
3580        } finally {
3581            super.finalize();
3582        }
3583    }
3584
3585    @Override
3586    protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
3587        if (child == mTitleBar) {
3588            // When drawing the title bar, move it horizontally to always show
3589            // at the top of the WebView.
3590            mTitleBar.offsetLeftAndRight(mScrollX - mTitleBar.getLeft());
3591            int newTop = Math.min(0, mScrollY);
3592            mTitleBar.setBottom(newTop + getTitleHeight());
3593            mTitleBar.setTop(newTop);
3594        }
3595        return super.drawChild(canvas, child, drawingTime);
3596    }
3597
3598    private void drawContent(Canvas canvas) {
3599        // Update the buttons in the picture, so when we draw the picture
3600        // to the screen, they are in the correct state.
3601        // Tell the native side if user is a) touching the screen,
3602        // b) pressing the trackball down, or c) pressing the enter key
3603        // If the cursor is on a button, we need to draw it in the pressed
3604        // state.
3605        // If mNativeClass is 0, we should not reach here, so we do not
3606        // need to check it again.
3607        nativeRecordButtons(hasFocus() && hasWindowFocus(),
3608                            mTouchMode == TOUCH_SHORTPRESS_START_MODE
3609                            || mTrackballDown || mGotCenterDown, false);
3610        drawCoreAndCursorRing(canvas, mBackgroundColor, mDrawCursorRing);
3611    }
3612
3613    /**
3614     * Draw the background when beyond bounds
3615     * @param canvas Canvas to draw into
3616     */
3617    private void drawOverScrollBackground(Canvas canvas) {
3618        if (mOverScrollBackground == null) {
3619            mOverScrollBackground = new Paint();
3620            Bitmap bm = BitmapFactory.decodeResource(
3621                    mContext.getResources(),
3622                    com.android.internal.R.drawable.status_bar_background);
3623            mOverScrollBackground.setShader(new BitmapShader(bm,
3624                    Shader.TileMode.REPEAT, Shader.TileMode.REPEAT));
3625            mOverScrollBorder = new Paint();
3626            mOverScrollBorder.setStyle(Paint.Style.STROKE);
3627            mOverScrollBorder.setStrokeWidth(0);
3628            mOverScrollBorder.setColor(0xffbbbbbb);
3629        }
3630
3631        int top = 0;
3632        int right = computeRealHorizontalScrollRange();
3633        int bottom = top + computeRealVerticalScrollRange();
3634        // first draw the background and anchor to the top of the view
3635        canvas.save();
3636        canvas.translate(mScrollX, mScrollY);
3637        canvas.clipRect(-mScrollX, top - mScrollY, right - mScrollX, bottom
3638                - mScrollY, Region.Op.DIFFERENCE);
3639        canvas.drawPaint(mOverScrollBackground);
3640        canvas.restore();
3641        // then draw the border
3642        canvas.drawRect(-1, top - 1, right, bottom, mOverScrollBorder);
3643        // next clip the region for the content
3644        canvas.clipRect(0, top, right, bottom);
3645    }
3646
3647    @Override
3648    protected void onDraw(Canvas canvas) {
3649        // if mNativeClass is 0, the WebView has been destroyed. Do nothing.
3650        if (mNativeClass == 0) {
3651            return;
3652        }
3653
3654        // if both mContentWidth and mContentHeight are 0, it means there is no
3655        // valid Picture passed to WebView yet. This can happen when WebView
3656        // just starts. Draw the background and return.
3657        if ((mContentWidth | mContentHeight) == 0 && mHistoryPicture == null) {
3658            canvas.drawColor(mBackgroundColor);
3659            return;
3660        }
3661
3662        int saveCount = canvas.save();
3663        if (mInOverScrollMode && !getSettings()
3664                .getUseWebViewBackgroundForOverscrollBackground()) {
3665            drawOverScrollBackground(canvas);
3666        }
3667        if (mTitleBar != null) {
3668            canvas.translate(0, (int) mTitleBar.getHeight());
3669        }
3670        drawContent(canvas);
3671        canvas.restoreToCount(saveCount);
3672
3673        if (AUTO_REDRAW_HACK && mAutoRedraw) {
3674            invalidate();
3675        }
3676        if (inEditingMode()) {
3677            mWebTextView.onDrawSubstitute();
3678        }
3679        mWebViewCore.signalRepaintDone();
3680
3681        if (mOverScrollGlow != null && mOverScrollGlow.drawEdgeGlows(canvas)) {
3682            invalidate();
3683        }
3684
3685        // paint the highlight in the end
3686        if (!mTouchHighlightRegion.isEmpty()) {
3687            if (mTouchHightlightPaint == null) {
3688                mTouchHightlightPaint = new Paint();
3689                mTouchHightlightPaint.setColor(mHightlightColor);
3690                mTouchHightlightPaint.setAntiAlias(true);
3691                mTouchHightlightPaint.setPathEffect(new CornerPathEffect(
3692                        TOUCH_HIGHLIGHT_ARC));
3693            }
3694            canvas.drawPath(mTouchHighlightRegion.getBoundaryPath(),
3695                    mTouchHightlightPaint);
3696        }
3697        if (DEBUG_TOUCH_HIGHLIGHT) {
3698            if (getSettings().getNavDump()) {
3699                if ((mTouchHighlightX | mTouchHighlightY) != 0) {
3700                    if (mTouchCrossHairColor == null) {
3701                        mTouchCrossHairColor = new Paint();
3702                        mTouchCrossHairColor.setColor(Color.RED);
3703                    }
3704                    canvas.drawLine(mTouchHighlightX - mNavSlop,
3705                            mTouchHighlightY - mNavSlop, mTouchHighlightX
3706                                    + mNavSlop + 1, mTouchHighlightY + mNavSlop
3707                                    + 1, mTouchCrossHairColor);
3708                    canvas.drawLine(mTouchHighlightX + mNavSlop + 1,
3709                            mTouchHighlightY - mNavSlop, mTouchHighlightX
3710                                    - mNavSlop,
3711                            mTouchHighlightY + mNavSlop + 1,
3712                            mTouchCrossHairColor);
3713                }
3714            }
3715        }
3716    }
3717
3718    private void removeTouchHighlight(boolean removePendingMessage) {
3719        if (removePendingMessage) {
3720            mWebViewCore.removeMessages(EventHub.GET_TOUCH_HIGHLIGHT_RECTS);
3721        }
3722        mWebViewCore.sendMessage(EventHub.REMOVE_TOUCH_HIGHLIGHT_RECTS);
3723    }
3724
3725    @Override
3726    public void setLayoutParams(ViewGroup.LayoutParams params) {
3727        if (params.height == LayoutParams.WRAP_CONTENT) {
3728            mWrapContent = true;
3729        }
3730        super.setLayoutParams(params);
3731    }
3732
3733    @Override
3734    public boolean performLongClick() {
3735        // performLongClick() is the result of a delayed message. If we switch
3736        // to windows overview, the WebView will be temporarily removed from the
3737        // view system. In that case, do nothing.
3738        if (getParent() == null) return false;
3739
3740        // A multi-finger gesture can look like a long press; make sure we don't take
3741        // long press actions if we're scaling.
3742        final ScaleGestureDetector detector = mZoomManager.getMultiTouchGestureDetector();
3743        if (detector != null && detector.isInProgress()) {
3744            return false;
3745        }
3746
3747        if (mNativeClass != 0 && nativeCursorIsTextInput()) {
3748            // Send the click so that the textfield is in focus
3749            centerKeyPressOnTextField();
3750            rebuildWebTextView();
3751        } else {
3752            clearTextEntry();
3753        }
3754        if (inEditingMode()) {
3755            // Since we just called rebuildWebTextView, the layout is not set
3756            // properly.  Update it so it can correctly find the word to select.
3757            mWebTextView.ensureLayout();
3758            // Provide a touch down event to WebTextView, which will allow it
3759            // to store the location to use in performLongClick.
3760            AbsoluteLayout.LayoutParams params
3761                    = (AbsoluteLayout.LayoutParams) mWebTextView.getLayoutParams();
3762            MotionEvent fake = MotionEvent.obtain(mLastTouchTime,
3763                    mLastTouchTime, MotionEvent.ACTION_DOWN,
3764                    mLastTouchX - params.x + mScrollX,
3765                    mLastTouchY - params.y + mScrollY, 0);
3766            mWebTextView.dispatchTouchEvent(fake);
3767            return mWebTextView.performLongClick();
3768        }
3769        if (mSelectingText) return false; // long click does nothing on selection
3770        /* if long click brings up a context menu, the super function
3771         * returns true and we're done. Otherwise, nothing happened when
3772         * the user clicked. */
3773        if (super.performLongClick()) {
3774            return true;
3775        }
3776        /* In the case where the application hasn't already handled the long
3777         * click action, look for a word under the  click. If one is found,
3778         * animate the text selection into view.
3779         * FIXME: no animation code yet */
3780        return selectText();
3781    }
3782
3783    /**
3784     * Select the word at the last click point.
3785     *
3786     * @hide pending API council approval
3787     */
3788    public boolean selectText() {
3789        int x = viewToContentX((int) mLastTouchX + mScrollX);
3790        int y = viewToContentY((int) mLastTouchY + mScrollY);
3791        setUpSelect();
3792        if (mNativeClass != 0 && nativeWordSelection(x, y)) {
3793            nativeSetExtendSelection();
3794            mDrawSelectionPointer = false;
3795            mSelectionStarted = true;
3796            mTouchMode = TOUCH_DRAG_MODE;
3797            return true;
3798        }
3799        selectionDone();
3800        return false;
3801    }
3802
3803    private int mOrientation = Configuration.ORIENTATION_UNDEFINED;
3804
3805    @Override
3806    protected void onConfigurationChanged(Configuration newConfig) {
3807        if (mSelectingText && mOrientation != newConfig.orientation) {
3808            selectionDone();
3809        }
3810        mOrientation = newConfig.orientation;
3811    }
3812
3813    /**
3814     * Keep track of the Callback so we can end its ActionMode or remove its
3815     * titlebar.
3816     */
3817    private SelectActionModeCallback mSelectCallback;
3818
3819    /**
3820     * Check to see if the focused textfield/textarea is still on screen.  If it
3821     * is, update the the dimensions and location of WebTextView.  Otherwise,
3822     * remove the WebTextView.  Should be called when the zoom level changes.
3823     * @param allowIntersect Whether to consider the textfield/textarea on
3824     *         screen if it only intersects the screen (as opposed to being
3825     *         completely on screen).
3826     * @return boolean True if the textfield/textarea is still on screen and the
3827     *         dimensions/location of WebTextView have been updated.
3828     */
3829    private boolean didUpdateWebTextViewDimensions(boolean allowIntersect) {
3830        Rect contentBounds = nativeFocusCandidateNodeBounds();
3831        Rect vBox = contentToViewRect(contentBounds);
3832        Rect visibleRect = new Rect();
3833        calcOurVisibleRect(visibleRect);
3834        // If the textfield is on screen, place the WebTextView in
3835        // its new place, accounting for our new scroll/zoom values,
3836        // and adjust its textsize.
3837        if (allowIntersect ? Rect.intersects(visibleRect, vBox)
3838                : visibleRect.contains(vBox)) {
3839            mWebTextView.setRect(vBox.left, vBox.top, vBox.width(),
3840                    vBox.height());
3841            mWebTextView.updateTextSize();
3842            updateWebTextViewPadding();
3843            return true;
3844        } else {
3845            // The textfield is now off screen.  The user probably
3846            // was not zooming to see the textfield better.  Remove
3847            // the WebTextView.  If the user types a key, and the
3848            // textfield is still in focus, we will reconstruct
3849            // the WebTextView and scroll it back on screen.
3850            mWebTextView.remove();
3851            return false;
3852        }
3853    }
3854
3855    void setBaseLayer(int layer, Rect invalRect) {
3856        if (mNativeClass == 0)
3857            return;
3858        if (invalRect == null) {
3859            Rect rect = new Rect(0, 0, mContentWidth, mContentHeight);
3860            nativeSetBaseLayer(layer, rect);
3861        } else {
3862            nativeSetBaseLayer(layer, invalRect);
3863        }
3864    }
3865
3866    private void onZoomAnimationStart() {
3867        // If it is in password mode, turn it off so it does not draw misplaced.
3868        if (inEditingMode() && nativeFocusCandidateIsPassword()) {
3869            mWebTextView.setInPassword(false);
3870        }
3871    }
3872
3873    private void onZoomAnimationEnd() {
3874        // adjust the edit text view if needed
3875        if (inEditingMode() && didUpdateWebTextViewDimensions(false)
3876                && nativeFocusCandidateIsPassword()) {
3877            // If it is a password field, start drawing the WebTextView once
3878            // again.
3879            mWebTextView.setInPassword(true);
3880        }
3881    }
3882
3883    void onFixedLengthZoomAnimationStart() {
3884        WebViewCore.pauseUpdatePicture(getWebViewCore());
3885        onZoomAnimationStart();
3886    }
3887
3888    void onFixedLengthZoomAnimationEnd() {
3889        if (!mSelectingText) {
3890            WebViewCore.resumeUpdatePicture(mWebViewCore);
3891        }
3892        onZoomAnimationEnd();
3893    }
3894
3895    private static final int ZOOM_BITS = Paint.FILTER_BITMAP_FLAG |
3896                                         Paint.DITHER_FLAG |
3897                                         Paint.SUBPIXEL_TEXT_FLAG;
3898    private static final int SCROLL_BITS = Paint.FILTER_BITMAP_FLAG |
3899                                           Paint.DITHER_FLAG;
3900
3901    private final DrawFilter mZoomFilter =
3902            new PaintFlagsDrawFilter(ZOOM_BITS, Paint.LINEAR_TEXT_FLAG);
3903    // If we need to trade better quality for speed, set mScrollFilter to null
3904    private final DrawFilter mScrollFilter =
3905            new PaintFlagsDrawFilter(SCROLL_BITS, 0);
3906
3907    private void drawCoreAndCursorRing(Canvas canvas, int color,
3908        boolean drawCursorRing) {
3909        if (mDrawHistory) {
3910            canvas.scale(mZoomManager.getScale(), mZoomManager.getScale());
3911            canvas.drawPicture(mHistoryPicture);
3912            return;
3913        }
3914        if (mNativeClass == 0) return;
3915
3916        boolean animateZoom = mZoomManager.isFixedLengthAnimationInProgress();
3917        boolean animateScroll = ((!mScroller.isFinished()
3918                || mVelocityTracker != null)
3919                && (mTouchMode != TOUCH_DRAG_MODE ||
3920                mHeldMotionless != MOTIONLESS_TRUE))
3921                || mDeferTouchMode == TOUCH_DRAG_MODE;
3922        if (mTouchMode == TOUCH_DRAG_MODE) {
3923            if (mHeldMotionless == MOTIONLESS_PENDING) {
3924                mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
3925                mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS);
3926                mHeldMotionless = MOTIONLESS_FALSE;
3927            }
3928            if (mHeldMotionless == MOTIONLESS_FALSE) {
3929                mPrivateHandler.sendMessageDelayed(mPrivateHandler
3930                        .obtainMessage(DRAG_HELD_MOTIONLESS), MOTIONLESS_TIME);
3931                mHeldMotionless = MOTIONLESS_PENDING;
3932            }
3933        }
3934        if (animateZoom) {
3935            mZoomManager.animateZoom(canvas);
3936        } else {
3937            canvas.scale(mZoomManager.getScale(), mZoomManager.getScale());
3938        }
3939
3940        boolean UIAnimationsRunning = false;
3941        // Currently for each draw we compute the animation values;
3942        // We may in the future decide to do that independently.
3943        if (mNativeClass != 0 && nativeEvaluateLayersAnimations()) {
3944            UIAnimationsRunning = true;
3945            // If we have unfinished (or unstarted) animations,
3946            // we ask for a repaint.
3947            invalidate();
3948        }
3949
3950        // decide which adornments to draw
3951        int extras = DRAW_EXTRAS_NONE;
3952        if (mFindIsUp) {
3953            extras = DRAW_EXTRAS_FIND;
3954        } else if (mSelectingText) {
3955            extras = DRAW_EXTRAS_SELECTION;
3956            nativeSetSelectionPointer(mDrawSelectionPointer,
3957                    mZoomManager.getInvScale(),
3958                    mSelectX, mSelectY - getTitleHeight());
3959        } else if (drawCursorRing) {
3960            extras = DRAW_EXTRAS_CURSOR_RING;
3961        }
3962        if (DebugFlags.WEB_VIEW) {
3963            Log.v(LOGTAG, "mFindIsUp=" + mFindIsUp
3964                    + " mSelectingText=" + mSelectingText
3965                    + " nativePageShouldHandleShiftAndArrows()="
3966                    + nativePageShouldHandleShiftAndArrows()
3967                    + " animateZoom=" + animateZoom
3968                    + " extras=" + extras);
3969        }
3970
3971        if (canvas.isHardwareAccelerated()) {
3972            try {
3973                if (canvas.acquireContext()) {
3974                      Rect rect = new Rect(mGLRectViewport.left,
3975                                           mGLRectViewport.top,
3976                                           mGLRectViewport.right,
3977                                           mGLRectViewport.bottom
3978                                           - getVisibleTitleHeight());
3979                      if (nativeDrawGL(rect, getScale(), extras)) {
3980                          invalidate();
3981                      }
3982                }
3983            } finally {
3984                canvas.releaseContext();
3985            }
3986        } else {
3987            DrawFilter df = null;
3988            if (mZoomManager.isZoomAnimating() || UIAnimationsRunning) {
3989                df = mZoomFilter;
3990            } else if (animateScroll) {
3991                df = mScrollFilter;
3992            }
3993            canvas.setDrawFilter(df);
3994            int content = nativeDraw(canvas, color, extras, true);
3995            canvas.setDrawFilter(null);
3996            if (content != 0) {
3997                mWebViewCore.sendMessage(EventHub.SPLIT_PICTURE_SET, content, 0);
3998            }
3999        }
4000
4001        if (extras == DRAW_EXTRAS_CURSOR_RING) {
4002            if (mTouchMode == TOUCH_SHORTPRESS_START_MODE) {
4003                mTouchMode = TOUCH_SHORTPRESS_MODE;
4004            }
4005        }
4006        if (mFocusSizeChanged) {
4007            mFocusSizeChanged = false;
4008            // If we are zooming, this will get handled above, when the zoom
4009            // finishes.  We also do not need to do this unless the WebTextView
4010            // is showing.
4011            if (!animateZoom && inEditingMode()) {
4012                didUpdateWebTextViewDimensions(true);
4013            }
4014        }
4015    }
4016
4017    // draw history
4018    private boolean mDrawHistory = false;
4019    private Picture mHistoryPicture = null;
4020    private int mHistoryWidth = 0;
4021    private int mHistoryHeight = 0;
4022
4023    // Only check the flag, can be called from WebCore thread
4024    boolean drawHistory() {
4025        return mDrawHistory;
4026    }
4027
4028    int getHistoryPictureWidth() {
4029        return (mHistoryPicture != null) ? mHistoryPicture.getWidth() : 0;
4030    }
4031
4032    // Should only be called in UI thread
4033    void switchOutDrawHistory() {
4034        if (null == mWebViewCore) return; // CallbackProxy may trigger this
4035        if (mDrawHistory && (getProgress() == 100 || nativeHasContent())) {
4036            mDrawHistory = false;
4037            mHistoryPicture = null;
4038            invalidate();
4039            int oldScrollX = mScrollX;
4040            int oldScrollY = mScrollY;
4041            mScrollX = pinLocX(mScrollX);
4042            mScrollY = pinLocY(mScrollY);
4043            if (oldScrollX != mScrollX || oldScrollY != mScrollY) {
4044                mUserScroll = false;
4045                mWebViewCore.sendMessage(EventHub.SYNC_SCROLL, oldScrollX,
4046                        oldScrollY);
4047                onScrollChanged(mScrollX, mScrollY, oldScrollX, oldScrollY);
4048            } else {
4049                sendOurVisibleRect();
4050            }
4051        }
4052    }
4053
4054    WebViewCore.CursorData cursorData() {
4055        WebViewCore.CursorData result = new WebViewCore.CursorData();
4056        result.mMoveGeneration = nativeMoveGeneration();
4057        result.mFrame = nativeCursorFramePointer();
4058        Point position = nativeCursorPosition();
4059        result.mX = position.x;
4060        result.mY = position.y;
4061        return result;
4062    }
4063
4064    /**
4065     *  Delete text from start to end in the focused textfield. If there is no
4066     *  focus, or if start == end, silently fail.  If start and end are out of
4067     *  order, swap them.
4068     *  @param  start   Beginning of selection to delete.
4069     *  @param  end     End of selection to delete.
4070     */
4071    /* package */ void deleteSelection(int start, int end) {
4072        mTextGeneration++;
4073        WebViewCore.TextSelectionData data
4074                = new WebViewCore.TextSelectionData(start, end);
4075        mWebViewCore.sendMessage(EventHub.DELETE_SELECTION, mTextGeneration, 0,
4076                data);
4077    }
4078
4079    /**
4080     *  Set the selection to (start, end) in the focused textfield. If start and
4081     *  end are out of order, swap them.
4082     *  @param  start   Beginning of selection.
4083     *  @param  end     End of selection.
4084     */
4085    /* package */ void setSelection(int start, int end) {
4086        if (mWebViewCore != null) {
4087            mWebViewCore.sendMessage(EventHub.SET_SELECTION, start, end);
4088        }
4089    }
4090
4091    @Override
4092    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
4093      InputConnection connection = super.onCreateInputConnection(outAttrs);
4094      outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_FULLSCREEN;
4095      return connection;
4096    }
4097
4098    /**
4099     * Called in response to a message from webkit telling us that the soft
4100     * keyboard should be launched.
4101     */
4102    private void displaySoftKeyboard(boolean isTextView) {
4103        InputMethodManager imm = (InputMethodManager)
4104                getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
4105
4106        // bring it back to the default level scale so that user can enter text
4107        boolean zoom = mZoomManager.getScale() < mZoomManager.getDefaultScale();
4108        if (zoom) {
4109            mZoomManager.setZoomCenter(mLastTouchX, mLastTouchY);
4110            mZoomManager.setZoomScale(mZoomManager.getDefaultScale(), false);
4111        }
4112        if (isTextView) {
4113            rebuildWebTextView();
4114            if (inEditingMode()) {
4115                imm.showSoftInput(mWebTextView, 0);
4116                if (zoom) {
4117                    didUpdateWebTextViewDimensions(true);
4118                }
4119                return;
4120            }
4121        }
4122        // Used by plugins and contentEditable.
4123        // Also used if the navigation cache is out of date, and
4124        // does not recognize that a textfield is in focus.  In that
4125        // case, use WebView as the targeted view.
4126        // see http://b/issue?id=2457459
4127        imm.showSoftInput(this, 0);
4128    }
4129
4130    // Called by WebKit to instruct the UI to hide the keyboard
4131    private void hideSoftKeyboard() {
4132        InputMethodManager imm = InputMethodManager.peekInstance();
4133        if (imm != null && (imm.isActive(this)
4134                || (inEditingMode() && imm.isActive(mWebTextView)))) {
4135            imm.hideSoftInputFromWindow(this.getWindowToken(), 0);
4136        }
4137    }
4138
4139    /*
4140     * This method checks the current focus and cursor and potentially rebuilds
4141     * mWebTextView to have the appropriate properties, such as password,
4142     * multiline, and what text it contains.  It also removes it if necessary.
4143     */
4144    /* package */ void rebuildWebTextView() {
4145        // If the WebView does not have focus, do nothing until it gains focus.
4146        if (!hasFocus() && (null == mWebTextView || !mWebTextView.hasFocus())) {
4147            return;
4148        }
4149        boolean alreadyThere = inEditingMode();
4150        // inEditingMode can only return true if mWebTextView is non-null,
4151        // so we can safely call remove() if (alreadyThere)
4152        if (0 == mNativeClass || !nativeFocusCandidateIsTextInput()) {
4153            if (alreadyThere) {
4154                mWebTextView.remove();
4155            }
4156            return;
4157        }
4158        // At this point, we know we have found an input field, so go ahead
4159        // and create the WebTextView if necessary.
4160        if (mWebTextView == null) {
4161            mWebTextView = new WebTextView(mContext, WebView.this, mAutoFillData.getQueryId());
4162            // Initialize our generation number.
4163            mTextGeneration = 0;
4164        }
4165        mWebTextView.updateTextSize();
4166        Rect visibleRect = new Rect();
4167        calcOurContentVisibleRect(visibleRect);
4168        // Note that sendOurVisibleRect calls viewToContent, so the coordinates
4169        // should be in content coordinates.
4170        Rect bounds = nativeFocusCandidateNodeBounds();
4171        Rect vBox = contentToViewRect(bounds);
4172        mWebTextView.setRect(vBox.left, vBox.top, vBox.width(), vBox.height());
4173        if (!Rect.intersects(bounds, visibleRect)) {
4174            mWebTextView.bringIntoView();
4175        }
4176        String text = nativeFocusCandidateText();
4177        int nodePointer = nativeFocusCandidatePointer();
4178        if (alreadyThere && mWebTextView.isSameTextField(nodePointer)) {
4179            // It is possible that we have the same textfield, but it has moved,
4180            // i.e. In the case of opening/closing the screen.
4181            // In that case, we need to set the dimensions, but not the other
4182            // aspects.
4183            // If the text has been changed by webkit, update it.  However, if
4184            // there has been more UI text input, ignore it.  We will receive
4185            // another update when that text is recognized.
4186            if (text != null && !text.equals(mWebTextView.getText().toString())
4187                    && nativeTextGeneration() == mTextGeneration) {
4188                mWebTextView.setTextAndKeepSelection(text);
4189            }
4190        } else {
4191            mWebTextView.setGravity(nativeFocusCandidateIsRtlText() ?
4192                    Gravity.RIGHT : Gravity.NO_GRAVITY);
4193            // This needs to be called before setType, which may call
4194            // requestFormData, and it needs to have the correct nodePointer.
4195            mWebTextView.setNodePointer(nodePointer);
4196            mWebTextView.setType(nativeFocusCandidateType());
4197            updateWebTextViewPadding();
4198            if (null == text) {
4199                if (DebugFlags.WEB_VIEW) {
4200                    Log.v(LOGTAG, "rebuildWebTextView null == text");
4201                }
4202                text = "";
4203            }
4204            mWebTextView.setTextAndKeepSelection(text);
4205            InputMethodManager imm = InputMethodManager.peekInstance();
4206            if (imm != null && imm.isActive(mWebTextView)) {
4207                imm.restartInput(mWebTextView);
4208            }
4209        }
4210        if (isFocused()) {
4211            mWebTextView.requestFocus();
4212        }
4213    }
4214
4215    /**
4216     * Update the padding of mWebTextView based on the native textfield/textarea
4217     */
4218    void updateWebTextViewPadding() {
4219        Rect paddingRect = nativeFocusCandidatePaddingRect();
4220        if (paddingRect != null) {
4221            // Use contentToViewDimension since these are the dimensions of
4222            // the padding.
4223            mWebTextView.setPadding(
4224                    contentToViewDimension(paddingRect.left),
4225                    contentToViewDimension(paddingRect.top),
4226                    contentToViewDimension(paddingRect.right),
4227                    contentToViewDimension(paddingRect.bottom));
4228        }
4229    }
4230
4231    /**
4232     * Tell webkit to put the cursor on screen.
4233     */
4234    /* package */ void revealSelection() {
4235        if (mWebViewCore != null) {
4236            mWebViewCore.sendMessage(EventHub.REVEAL_SELECTION);
4237        }
4238    }
4239
4240    /**
4241     * Called by WebTextView to find saved form data associated with the
4242     * textfield
4243     * @param name Name of the textfield.
4244     * @param nodePointer Pointer to the node of the textfield, so it can be
4245     *          compared to the currently focused textfield when the data is
4246     *          retrieved.
4247     * @param autoFillable true if WebKit has determined this field is part of
4248     *          a form that can be auto filled.
4249     */
4250    /* package */ void requestFormData(String name, int nodePointer, boolean autoFillable) {
4251        if (mWebViewCore.getSettings().getSaveFormData()) {
4252            Message update = mPrivateHandler.obtainMessage(REQUEST_FORM_DATA);
4253            update.arg1 = nodePointer;
4254            RequestFormData updater = new RequestFormData(name, getUrl(),
4255                    update, autoFillable);
4256            Thread t = new Thread(updater);
4257            t.start();
4258        }
4259    }
4260
4261    /**
4262     * Pass a message to find out the <label> associated with the <input>
4263     * identified by nodePointer
4264     * @param framePointer Pointer to the frame containing the <input> node
4265     * @param nodePointer Pointer to the node for which a <label> is desired.
4266     */
4267    /* package */ void requestLabel(int framePointer, int nodePointer) {
4268        mWebViewCore.sendMessage(EventHub.REQUEST_LABEL, framePointer,
4269                nodePointer);
4270    }
4271
4272    /*
4273     * This class requests an Adapter for the WebTextView which shows past
4274     * entries stored in the database.  It is a Runnable so that it can be done
4275     * in its own thread, without slowing down the UI.
4276     */
4277    private class RequestFormData implements Runnable {
4278        private String mName;
4279        private String mUrl;
4280        private Message mUpdateMessage;
4281        private boolean mAutoFillable;
4282
4283        public RequestFormData(String name, String url, Message msg, boolean autoFillable) {
4284            mName = name;
4285            mUrl = url;
4286            mUpdateMessage = msg;
4287            mAutoFillable = autoFillable;
4288        }
4289
4290        public void run() {
4291            ArrayList<String> pastEntries = new ArrayList();
4292
4293            if (mAutoFillable) {
4294                // Note that code inside the adapter click handler in WebTextView depends
4295                // on the AutoFill item being at the top of the drop down list. If you change
4296                // the order, make sure to do it there too!
4297                WebSettings settings = getSettings();
4298                if (settings != null && settings.getAutoFillProfile() != null) {
4299                    pastEntries.add(getResources().getText(
4300                            com.android.internal.R.string.autofill_this_form).toString() +
4301                            " " +
4302                            mAutoFillData.getPreviewString());
4303                    mWebTextView.setAutoFillProfileIsSet(true);
4304                } else {
4305                    // There is no autofill profile set up yet, so add an option that
4306                    // will invite the user to set their profile up.
4307                    pastEntries.add(getResources().getText(
4308                            com.android.internal.R.string.setup_autofill).toString());
4309                    mWebTextView.setAutoFillProfileIsSet(false);
4310                }
4311            }
4312
4313            pastEntries.addAll(mDatabase.getFormData(mUrl, mName));
4314
4315            if (pastEntries.size() > 0) {
4316                AutoCompleteAdapter adapter = new
4317                        AutoCompleteAdapter(mContext, pastEntries);
4318                mUpdateMessage.obj = adapter;
4319                mUpdateMessage.sendToTarget();
4320            }
4321        }
4322    }
4323
4324    /**
4325     * Dump the display tree to "/sdcard/displayTree.txt"
4326     *
4327     * @hide debug only
4328     */
4329    public void dumpDisplayTree() {
4330        nativeDumpDisplayTree(getUrl());
4331    }
4332
4333    /**
4334     * Dump the dom tree to adb shell if "toFile" is False, otherwise dump it to
4335     * "/sdcard/domTree.txt"
4336     *
4337     * @hide debug only
4338     */
4339    public void dumpDomTree(boolean toFile) {
4340        mWebViewCore.sendMessage(EventHub.DUMP_DOMTREE, toFile ? 1 : 0, 0);
4341    }
4342
4343    /**
4344     * Dump the render tree to adb shell if "toFile" is False, otherwise dump it
4345     * to "/sdcard/renderTree.txt"
4346     *
4347     * @hide debug only
4348     */
4349    public void dumpRenderTree(boolean toFile) {
4350        mWebViewCore.sendMessage(EventHub.DUMP_RENDERTREE, toFile ? 1 : 0, 0);
4351    }
4352
4353    /**
4354     * Called by DRT on UI thread, need to proxy to WebCore thread.
4355     *
4356     * @hide debug only
4357     */
4358    public void useMockDeviceOrientation() {
4359        mWebViewCore.sendMessage(EventHub.USE_MOCK_DEVICE_ORIENTATION);
4360    }
4361
4362    /**
4363     * Called by DRT on WebCore thread.
4364     *
4365     * @hide debug only
4366     */
4367    public void setMockDeviceOrientation(boolean canProvideAlpha, double alpha,
4368            boolean canProvideBeta, double beta, boolean canProvideGamma, double gamma) {
4369        mWebViewCore.setMockDeviceOrientation(canProvideAlpha, alpha, canProvideBeta, beta,
4370                canProvideGamma, gamma);
4371    }
4372
4373    /**
4374     * Dump the V8 counters to standard output.
4375     * Note that you need a build with V8 and WEBCORE_INSTRUMENTATION set to
4376     * true. Otherwise, this will do nothing.
4377     *
4378     * @hide debug only
4379     */
4380    public void dumpV8Counters() {
4381        mWebViewCore.sendMessage(EventHub.DUMP_V8COUNTERS);
4382    }
4383
4384    // This is used to determine long press with the center key.  Does not
4385    // affect long press with the trackball/touch.
4386    private boolean mGotCenterDown = false;
4387
4388    @Override
4389    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
4390        // send complex characters to webkit for use by JS and plugins
4391        if (keyCode == KeyEvent.KEYCODE_UNKNOWN && event.getCharacters() != null) {
4392            // pass the key to DOM
4393            mWebViewCore.sendMessage(EventHub.KEY_DOWN, event);
4394            mWebViewCore.sendMessage(EventHub.KEY_UP, event);
4395            // return true as DOM handles the key
4396            return true;
4397        }
4398        return false;
4399    }
4400
4401    @Override
4402    public boolean onKeyDown(int keyCode, KeyEvent event) {
4403        if (DebugFlags.WEB_VIEW) {
4404            Log.v(LOGTAG, "keyDown at " + System.currentTimeMillis()
4405                    + ", " + event + ", unicode=" + event.getUnicodeChar());
4406        }
4407
4408        if (mNativeClass == 0) {
4409            return false;
4410        }
4411
4412        // do this hack up front, so it always works, regardless of touch-mode
4413        if (AUTO_REDRAW_HACK && (keyCode == KeyEvent.KEYCODE_CALL)) {
4414            mAutoRedraw = !mAutoRedraw;
4415            if (mAutoRedraw) {
4416                invalidate();
4417            }
4418            return true;
4419        }
4420
4421        // Bubble up the key event if
4422        // 1. it is a system key; or
4423        // 2. the host application wants to handle it;
4424        // 3. the accessibility injector is present and wants to handle it;
4425        if (event.isSystem()
4426                || mCallbackProxy.uiOverrideKeyEvent(event)
4427                || (mAccessibilityInjector != null && mAccessibilityInjector.onKeyEvent(event))) {
4428            return false;
4429        }
4430
4431        if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT
4432                || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT) {
4433            if (!pageShouldHandleShiftAndArrows() && !nativeCursorWantsKeyEvents()
4434                    && !mSelectingText) {
4435                setUpSelect();
4436            }
4437        }
4438
4439        if (keyCode == KeyEvent.KEYCODE_PAGE_UP) {
4440            pageUp(false);
4441            return true;
4442        }
4443
4444        if (keyCode == KeyEvent.KEYCODE_PAGE_DOWN) {
4445            pageDown(false);
4446            return true;
4447        }
4448
4449        if (keyCode >= KeyEvent.KEYCODE_DPAD_UP
4450                && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) {
4451            switchOutDrawHistory();
4452            if (pageShouldHandleShiftAndArrows()) {
4453                letPageHandleNavKey(keyCode, event.getEventTime(), true, event.getMetaState());
4454                return true;
4455            }
4456            if (mSelectingText) {
4457                int xRate = keyCode == KeyEvent.KEYCODE_DPAD_LEFT
4458                    ? -1 : keyCode == KeyEvent.KEYCODE_DPAD_RIGHT ? 1 : 0;
4459                int yRate = keyCode == KeyEvent.KEYCODE_DPAD_UP ?
4460                    -1 : keyCode == KeyEvent.KEYCODE_DPAD_DOWN ? 1 : 0;
4461                int multiplier = event.getRepeatCount() + 1;
4462                moveSelection(xRate * multiplier, yRate * multiplier);
4463                return true;
4464            }
4465            if (navHandledKey(keyCode, 1, false, event.getEventTime())) {
4466                playSoundEffect(keyCodeToSoundsEffect(keyCode));
4467                return true;
4468            }
4469            // Bubble up the key event as WebView doesn't handle it
4470            return false;
4471        }
4472
4473        if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
4474            switchOutDrawHistory();
4475            if (event.getRepeatCount() == 0) {
4476                if (mSelectingText) {
4477                    return true; // discard press if copy in progress
4478                }
4479                mGotCenterDown = true;
4480                mPrivateHandler.sendMessageDelayed(mPrivateHandler
4481                        .obtainMessage(LONG_PRESS_CENTER), LONG_PRESS_TIMEOUT);
4482                // Already checked mNativeClass, so we do not need to check it
4483                // again.
4484                nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true);
4485                return true;
4486            }
4487            // Bubble up the key event as WebView doesn't handle it
4488            return false;
4489        }
4490
4491        if (keyCode != KeyEvent.KEYCODE_SHIFT_LEFT
4492                && keyCode != KeyEvent.KEYCODE_SHIFT_RIGHT) {
4493            // turn off copy select if a shift-key combo is pressed
4494            selectionDone();
4495        }
4496
4497        if (getSettings().getNavDump()) {
4498            switch (keyCode) {
4499                case KeyEvent.KEYCODE_4:
4500                    dumpDisplayTree();
4501                    break;
4502                case KeyEvent.KEYCODE_5:
4503                case KeyEvent.KEYCODE_6:
4504                    dumpDomTree(keyCode == KeyEvent.KEYCODE_5);
4505                    break;
4506                case KeyEvent.KEYCODE_7:
4507                case KeyEvent.KEYCODE_8:
4508                    dumpRenderTree(keyCode == KeyEvent.KEYCODE_7);
4509                    break;
4510                case KeyEvent.KEYCODE_9:
4511                    nativeInstrumentReport();
4512                    return true;
4513            }
4514        }
4515
4516        if (nativeCursorIsTextInput()) {
4517            // This message will put the node in focus, for the DOM's notion
4518            // of focus, and make the focuscontroller active
4519            mWebViewCore.sendMessage(EventHub.CLICK, nativeCursorFramePointer(),
4520                    nativeCursorNodePointer());
4521            // This will bring up the WebTextView and put it in focus, for
4522            // our view system's notion of focus
4523            rebuildWebTextView();
4524            // Now we need to pass the event to it
4525            if (inEditingMode()) {
4526                mWebTextView.setDefaultSelection();
4527                return mWebTextView.dispatchKeyEvent(event);
4528            }
4529        } else if (nativeHasFocusNode()) {
4530            // In this case, the cursor is not on a text input, but the focus
4531            // might be.  Check it, and if so, hand over to the WebTextView.
4532            rebuildWebTextView();
4533            if (inEditingMode()) {
4534                mWebTextView.setDefaultSelection();
4535                return mWebTextView.dispatchKeyEvent(event);
4536            }
4537        }
4538
4539        // TODO: should we pass all the keys to DOM or check the meta tag
4540        if (nativeCursorWantsKeyEvents() || true) {
4541            // pass the key to DOM
4542            mWebViewCore.sendMessage(EventHub.KEY_DOWN, event);
4543            // return true as DOM handles the key
4544            return true;
4545        }
4546
4547        // Bubble up the key event as WebView doesn't handle it
4548        return false;
4549    }
4550
4551    @Override
4552    public boolean onKeyUp(int keyCode, KeyEvent event) {
4553        if (DebugFlags.WEB_VIEW) {
4554            Log.v(LOGTAG, "keyUp at " + System.currentTimeMillis()
4555                    + ", " + event + ", unicode=" + event.getUnicodeChar());
4556        }
4557
4558        if (mNativeClass == 0) {
4559            return false;
4560        }
4561
4562        // special CALL handling when cursor node's href is "tel:XXX"
4563        if (keyCode == KeyEvent.KEYCODE_CALL && nativeHasCursorNode()) {
4564            String text = nativeCursorText();
4565            if (!nativeCursorIsTextInput() && text != null
4566                    && text.startsWith(SCHEME_TEL)) {
4567                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(text));
4568                getContext().startActivity(intent);
4569                return true;
4570            }
4571        }
4572
4573        // Bubble up the key event if
4574        // 1. it is a system key; or
4575        // 2. the host application wants to handle it;
4576        // 3. the accessibility injector is present and wants to handle it;
4577        if (event.isSystem()
4578                || mCallbackProxy.uiOverrideKeyEvent(event)
4579                || (mAccessibilityInjector != null && mAccessibilityInjector.onKeyEvent(event))) {
4580            return false;
4581        }
4582
4583        if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT
4584                || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT) {
4585            if (!pageShouldHandleShiftAndArrows() && copySelection()) {
4586                selectionDone();
4587                return true;
4588            }
4589        }
4590
4591        if (keyCode >= KeyEvent.KEYCODE_DPAD_UP
4592                && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) {
4593            if (pageShouldHandleShiftAndArrows()) {
4594                letPageHandleNavKey(keyCode, event.getEventTime(), false, event.getMetaState());
4595                return true;
4596            }
4597            // always handle the navigation keys in the UI thread
4598            // Bubble up the key event as WebView doesn't handle it
4599            return false;
4600        }
4601
4602        if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
4603            // remove the long press message first
4604            mPrivateHandler.removeMessages(LONG_PRESS_CENTER);
4605            mGotCenterDown = false;
4606
4607            if (mSelectingText) {
4608                if (mExtendSelection) {
4609                    copySelection();
4610                    selectionDone();
4611                } else {
4612                    mExtendSelection = true;
4613                    nativeSetExtendSelection();
4614                    invalidate(); // draw the i-beam instead of the arrow
4615                }
4616                return true; // discard press if copy in progress
4617            }
4618
4619            // perform the single click
4620            Rect visibleRect = sendOurVisibleRect();
4621            // Note that sendOurVisibleRect calls viewToContent, so the
4622            // coordinates should be in content coordinates.
4623            if (!nativeCursorIntersects(visibleRect)) {
4624                return false;
4625            }
4626            WebViewCore.CursorData data = cursorData();
4627            mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE, data);
4628            playSoundEffect(SoundEffectConstants.CLICK);
4629            if (nativeCursorIsTextInput()) {
4630                rebuildWebTextView();
4631                centerKeyPressOnTextField();
4632                if (inEditingMode()) {
4633                    mWebTextView.setDefaultSelection();
4634                }
4635                return true;
4636            }
4637            clearTextEntry();
4638            nativeShowCursorTimed();
4639            if (!mCallbackProxy.uiOverrideUrlLoading(nativeCursorText())) {
4640                mWebViewCore.sendMessage(EventHub.CLICK, data.mFrame,
4641                        nativeCursorNodePointer());
4642            }
4643            return true;
4644        }
4645
4646        // TODO: should we pass all the keys to DOM or check the meta tag
4647        if (nativeCursorWantsKeyEvents() || true) {
4648            // pass the key to DOM
4649            mWebViewCore.sendMessage(EventHub.KEY_UP, event);
4650            // return true as DOM handles the key
4651            return true;
4652        }
4653
4654        // Bubble up the key event as WebView doesn't handle it
4655        return false;
4656    }
4657
4658    private void setUpSelect() {
4659        if (0 == mNativeClass) return; // client isn't initialized
4660        if (inFullScreenMode()) return;
4661        if (mSelectingText) return;
4662        mExtendSelection = false;
4663        mSelectingText = mDrawSelectionPointer = true;
4664        // don't let the picture change during text selection
4665        WebViewCore.pauseUpdatePicture(mWebViewCore);
4666        nativeResetSelection();
4667        if (nativeHasCursorNode()) {
4668            Rect rect = nativeCursorNodeBounds();
4669            mSelectX = contentToViewX(rect.left);
4670            mSelectY = contentToViewY(rect.top);
4671        } else if (mLastTouchY > getVisibleTitleHeight()) {
4672            mSelectX = mScrollX + (int) mLastTouchX;
4673            mSelectY = mScrollY + (int) mLastTouchY;
4674        } else {
4675            mSelectX = mScrollX + getViewWidth() / 2;
4676            mSelectY = mScrollY + getViewHeightWithTitle() / 2;
4677        }
4678        nativeHideCursor();
4679        mSelectCallback = new SelectActionModeCallback();
4680        mSelectCallback.setWebView(this);
4681        startActionMode(mSelectCallback);
4682    }
4683
4684    /**
4685     * Use this method to put the WebView into text selection mode.
4686     * Do not rely on this functionality; it will be deprecated in the future.
4687     */
4688    public void emulateShiftHeld() {
4689        setUpSelect();
4690    }
4691
4692    /**
4693     * Select all of the text in this WebView.
4694     */
4695    void selectAll() {
4696        if (0 == mNativeClass) return; // client isn't initialized
4697        if (inFullScreenMode()) return;
4698        if (!mSelectingText) setUpSelect();
4699        nativeSelectAll();
4700        mDrawSelectionPointer = false;
4701        mExtendSelection = true;
4702        invalidate();
4703    }
4704
4705    /**
4706     * Called when the selection has been removed.
4707     */
4708    void selectionDone() {
4709        if (mSelectingText) {
4710            mSelectingText = false;
4711            // finish is idempotent, so this is fine even if selectionDone was
4712            // called by mSelectCallback.onDestroyActionMode
4713            mSelectCallback.finish();
4714            mSelectCallback = null;
4715            WebViewCore.resumePriority();
4716            WebViewCore.resumeUpdatePicture(mWebViewCore);
4717            invalidate(); // redraw without selection
4718            mAutoScrollX = 0;
4719            mAutoScrollY = 0;
4720            mSentAutoScrollMessage = false;
4721        }
4722    }
4723
4724    /**
4725     * Copy the selection to the clipboard
4726     */
4727    boolean copySelection() {
4728        boolean copiedSomething = false;
4729        String selection = getSelection();
4730        if (selection != "") {
4731            if (DebugFlags.WEB_VIEW) {
4732                Log.v(LOGTAG, "copySelection \"" + selection + "\"");
4733            }
4734            Toast.makeText(mContext
4735                    , com.android.internal.R.string.text_copied
4736                    , Toast.LENGTH_SHORT).show();
4737            copiedSomething = true;
4738            ClipboardManager cm = (ClipboardManager)getContext()
4739                    .getSystemService(Context.CLIPBOARD_SERVICE);
4740            cm.setText(selection);
4741        }
4742        invalidate(); // remove selection region and pointer
4743        return copiedSomething;
4744    }
4745
4746    /**
4747     * Returns the currently highlighted text as a string.
4748     */
4749    String getSelection() {
4750        if (mNativeClass == 0) return "";
4751        return nativeGetSelection();
4752    }
4753
4754    @Override
4755    protected void onAttachedToWindow() {
4756        super.onAttachedToWindow();
4757        if (hasWindowFocus()) setActive(true);
4758        final ViewTreeObserver treeObserver = getViewTreeObserver();
4759        if (treeObserver != null) {
4760            if (mGlobalLayoutListener == null) {
4761                mGlobalLayoutListener = new InnerGlobalLayoutListener();
4762                treeObserver.addOnGlobalLayoutListener(mGlobalLayoutListener);
4763            }
4764            if (mScrollChangedListener == null) {
4765                mScrollChangedListener = new InnerScrollChangedListener();
4766                treeObserver.addOnScrollChangedListener(mScrollChangedListener);
4767            }
4768        }
4769    }
4770
4771    @Override
4772    protected void onDetachedFromWindow() {
4773        clearHelpers();
4774        mZoomManager.dismissZoomPicker();
4775        if (hasWindowFocus()) setActive(false);
4776
4777        final ViewTreeObserver treeObserver = getViewTreeObserver();
4778        if (treeObserver != null) {
4779            if (mGlobalLayoutListener != null) {
4780                treeObserver.removeGlobalOnLayoutListener(mGlobalLayoutListener);
4781                mGlobalLayoutListener = null;
4782            }
4783            if (mScrollChangedListener != null) {
4784                treeObserver.removeOnScrollChangedListener(mScrollChangedListener);
4785                mScrollChangedListener = null;
4786            }
4787        }
4788
4789        super.onDetachedFromWindow();
4790    }
4791
4792    @Override
4793    protected void onVisibilityChanged(View changedView, int visibility) {
4794        super.onVisibilityChanged(changedView, visibility);
4795        // The zoomManager may be null if the webview is created from XML that
4796        // specifies the view's visibility param as not visible (see http://b/2794841)
4797        if (visibility != View.VISIBLE && mZoomManager != null) {
4798            mZoomManager.dismissZoomPicker();
4799        }
4800    }
4801
4802    /**
4803     * @deprecated WebView no longer needs to implement
4804     * ViewGroup.OnHierarchyChangeListener.  This method does nothing now.
4805     */
4806    @Deprecated
4807    public void onChildViewAdded(View parent, View child) {}
4808
4809    /**
4810     * @deprecated WebView no longer needs to implement
4811     * ViewGroup.OnHierarchyChangeListener.  This method does nothing now.
4812     */
4813    @Deprecated
4814    public void onChildViewRemoved(View p, View child) {}
4815
4816    /**
4817     * @deprecated WebView should not have implemented
4818     * ViewTreeObserver.OnGlobalFocusChangeListener.  This method
4819     * does nothing now.
4820     */
4821    @Deprecated
4822    public void onGlobalFocusChanged(View oldFocus, View newFocus) {
4823    }
4824
4825    private void setActive(boolean active) {
4826        if (active) {
4827            if (hasFocus()) {
4828                // If our window regained focus, and we have focus, then begin
4829                // drawing the cursor ring
4830                mDrawCursorRing = true;
4831                setFocusControllerActive(true);
4832                if (mNativeClass != 0) {
4833                    nativeRecordButtons(true, false, true);
4834                }
4835            } else {
4836                if (!inEditingMode()) {
4837                    // If our window gained focus, but we do not have it, do not
4838                    // draw the cursor ring.
4839                    mDrawCursorRing = false;
4840                    setFocusControllerActive(false);
4841                }
4842                // We do not call nativeRecordButtons here because we assume
4843                // that when we lost focus, or window focus, it got called with
4844                // false for the first parameter
4845            }
4846        } else {
4847            if (!mZoomManager.isZoomPickerVisible()) {
4848                /*
4849                 * The external zoom controls come in their own window, so our
4850                 * window loses focus. Our policy is to not draw the cursor ring
4851                 * if our window is not focused, but this is an exception since
4852                 * the user can still navigate the web page with the zoom
4853                 * controls showing.
4854                 */
4855                mDrawCursorRing = false;
4856            }
4857            mGotKeyDown = false;
4858            mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
4859            mTouchMode = TOUCH_DONE_MODE;
4860            if (mNativeClass != 0) {
4861                nativeRecordButtons(false, false, true);
4862            }
4863            setFocusControllerActive(false);
4864        }
4865        invalidate();
4866    }
4867
4868    // To avoid drawing the cursor ring, and remove the TextView when our window
4869    // loses focus.
4870    @Override
4871    public void onWindowFocusChanged(boolean hasWindowFocus) {
4872        setActive(hasWindowFocus);
4873        if (hasWindowFocus) {
4874            JWebCoreJavaBridge.setActiveWebView(this);
4875        } else {
4876            JWebCoreJavaBridge.removeActiveWebView(this);
4877        }
4878        super.onWindowFocusChanged(hasWindowFocus);
4879    }
4880
4881    /*
4882     * Pass a message to WebCore Thread, telling the WebCore::Page's
4883     * FocusController to be  "inactive" so that it will
4884     * not draw the blinking cursor.  It gets set to "active" to draw the cursor
4885     * in WebViewCore.cpp, when the WebCore thread receives key events/clicks.
4886     */
4887    /* package */ void setFocusControllerActive(boolean active) {
4888        if (mWebViewCore == null) return;
4889        mWebViewCore.sendMessage(EventHub.SET_ACTIVE, active ? 1 : 0, 0);
4890        // Need to send this message after the document regains focus.
4891        if (active && mListBoxMessage != null) {
4892            mWebViewCore.sendMessage(mListBoxMessage);
4893            mListBoxMessage = null;
4894        }
4895    }
4896
4897    @Override
4898    protected void onFocusChanged(boolean focused, int direction,
4899            Rect previouslyFocusedRect) {
4900        if (DebugFlags.WEB_VIEW) {
4901            Log.v(LOGTAG, "MT focusChanged " + focused + ", " + direction);
4902        }
4903        if (focused) {
4904            // When we regain focus, if we have window focus, resume drawing
4905            // the cursor ring
4906            if (hasWindowFocus()) {
4907                mDrawCursorRing = true;
4908                if (mNativeClass != 0) {
4909                    nativeRecordButtons(true, false, true);
4910                }
4911                setFocusControllerActive(true);
4912            //} else {
4913                // The WebView has gained focus while we do not have
4914                // windowfocus.  When our window lost focus, we should have
4915                // called nativeRecordButtons(false...)
4916            }
4917        } else {
4918            // When we lost focus, unless focus went to the TextView (which is
4919            // true if we are in editing mode), stop drawing the cursor ring.
4920            if (!inEditingMode()) {
4921                mDrawCursorRing = false;
4922                if (mNativeClass != 0) {
4923                    nativeRecordButtons(false, false, true);
4924                }
4925                setFocusControllerActive(false);
4926            }
4927            mGotKeyDown = false;
4928        }
4929
4930        super.onFocusChanged(focused, direction, previouslyFocusedRect);
4931    }
4932
4933    void setGLRectViewport() {
4934        // Use the getGlobalVisibleRect() to get the intersection among the parents
4935        Rect webViewRect = new Rect();
4936        boolean visible = getGlobalVisibleRect(webViewRect);
4937
4938        // Then need to invert the Y axis, just for GL
4939        View rootView = getRootView();
4940        int rootViewHeight = rootView.getHeight();
4941        int savedWebViewBottom = webViewRect.bottom;
4942        webViewRect.bottom = rootViewHeight - webViewRect.top;
4943        webViewRect.top = rootViewHeight - savedWebViewBottom;
4944
4945        // Store the viewport
4946        mGLRectViewport = webViewRect;
4947    }
4948
4949    /**
4950     * @hide
4951     */
4952    @Override
4953    protected boolean setFrame(int left, int top, int right, int bottom) {
4954        boolean changed = super.setFrame(left, top, right, bottom);
4955        if (!changed && mHeightCanMeasure) {
4956            // When mHeightCanMeasure is true, we will set mLastHeightSent to 0
4957            // in WebViewCore after we get the first layout. We do call
4958            // requestLayout() when we get contentSizeChanged(). But the View
4959            // system won't call onSizeChanged if the dimension is not changed.
4960            // In this case, we need to call sendViewSizeZoom() explicitly to
4961            // notify the WebKit about the new dimensions.
4962            sendViewSizeZoom(false);
4963        }
4964        setGLRectViewport();
4965        return changed;
4966    }
4967
4968    @Override
4969    protected void onSizeChanged(int w, int h, int ow, int oh) {
4970        super.onSizeChanged(w, h, ow, oh);
4971
4972        // adjust the max viewport width depending on the view dimensions. This
4973        // is to ensure the scaling is not going insane. So do not shrink it if
4974        // the view size is temporarily smaller, e.g. when soft keyboard is up.
4975        int newMaxViewportWidth = (int) (Math.max(w, h) / mZoomManager.getDefaultMinZoomScale());
4976        if (newMaxViewportWidth > sMaxViewportWidth) {
4977            sMaxViewportWidth = newMaxViewportWidth;
4978        }
4979
4980        mZoomManager.onSizeChanged(w, h, ow, oh);
4981    }
4982
4983    @Override
4984    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
4985        super.onScrollChanged(l, t, oldl, oldt);
4986        if (!mInOverScrollMode) {
4987            sendOurVisibleRect();
4988            // update WebKit if visible title bar height changed. The logic is same
4989            // as getVisibleTitleHeight.
4990            int titleHeight = getTitleHeight();
4991            if (Math.max(titleHeight - t, 0) != Math.max(titleHeight - oldt, 0)) {
4992                sendViewSizeZoom(false);
4993            }
4994        }
4995    }
4996
4997    @Override
4998    public boolean dispatchKeyEvent(KeyEvent event) {
4999        boolean dispatch = true;
5000
5001        // Textfields, plugins, and contentEditable nodes need to receive the
5002        // shift up key even if another key was released while the shift key
5003        // was held down.
5004        if (!inEditingMode() && (mNativeClass == 0
5005                || !nativePageShouldHandleShiftAndArrows())) {
5006            if (event.getAction() == KeyEvent.ACTION_DOWN) {
5007                mGotKeyDown = true;
5008            } else {
5009                if (!mGotKeyDown) {
5010                    /*
5011                     * We got a key up for which we were not the recipient of
5012                     * the original key down. Don't give it to the view.
5013                     */
5014                    dispatch = false;
5015                }
5016                mGotKeyDown = false;
5017            }
5018        }
5019
5020        if (dispatch) {
5021            return super.dispatchKeyEvent(event);
5022        } else {
5023            // We didn't dispatch, so let something else handle the key
5024            return false;
5025        }
5026    }
5027
5028    // Here are the snap align logic:
5029    // 1. If it starts nearly horizontally or vertically, snap align;
5030    // 2. If there is a dramitic direction change, let it go;
5031    // 3. If there is a same direction back and forth, lock it.
5032
5033    // adjustable parameters
5034    private int mMinLockSnapReverseDistance;
5035    private static final float MAX_SLOPE_FOR_DIAG = 1.5f;
5036    private static final int MIN_BREAK_SNAP_CROSS_DISTANCE = 80;
5037
5038    private boolean hitFocusedPlugin(int contentX, int contentY) {
5039        if (DebugFlags.WEB_VIEW) {
5040            Log.v(LOGTAG, "nativeFocusIsPlugin()=" + nativeFocusIsPlugin());
5041            Rect r = nativeFocusNodeBounds();
5042            Log.v(LOGTAG, "nativeFocusNodeBounds()=(" + r.left + ", " + r.top
5043                    + ", " + r.right + ", " + r.bottom + ")");
5044        }
5045        return nativeFocusIsPlugin()
5046                && nativeFocusNodeBounds().contains(contentX, contentY);
5047    }
5048
5049    private boolean shouldForwardTouchEvent() {
5050        return mFullScreenHolder != null || (mForwardTouchEvents
5051                && !mSelectingText
5052                && mPreventDefault != PREVENT_DEFAULT_IGNORE);
5053    }
5054
5055    private boolean inFullScreenMode() {
5056        return mFullScreenHolder != null;
5057    }
5058
5059    private void dismissFullScreenMode() {
5060        if (inFullScreenMode()) {
5061            mFullScreenHolder.dismiss();
5062            mFullScreenHolder = null;
5063        }
5064    }
5065
5066    void onPinchToZoomAnimationStart() {
5067        // cancel the single touch handling
5068        cancelTouch();
5069        onZoomAnimationStart();
5070    }
5071
5072    void onPinchToZoomAnimationEnd(ScaleGestureDetector detector) {
5073        onZoomAnimationEnd();
5074        // start a drag, TOUCH_PINCH_DRAG, can't use TOUCH_INIT_MODE as
5075        // it may trigger the unwanted click, can't use TOUCH_DRAG_MODE
5076        // as it may trigger the unwanted fling.
5077        mTouchMode = TOUCH_PINCH_DRAG;
5078        mConfirmMove = true;
5079        startTouch(detector.getFocusX(), detector.getFocusY(), mLastTouchTime);
5080    }
5081
5082    // See if there is a layer at x, y and switch to TOUCH_DRAG_LAYER_MODE if a
5083    // layer is found.
5084    private void startScrollingLayer(float x, float y) {
5085        int contentX = viewToContentX((int) x + mScrollX);
5086        int contentY = viewToContentY((int) y + mScrollY);
5087        mScrollingLayer = nativeScrollableLayer(contentX, contentY,
5088                mScrollingLayerRect);
5089        if (mScrollingLayer != 0) {
5090            mTouchMode = TOUCH_DRAG_LAYER_MODE;
5091        }
5092    }
5093
5094    // 1/(density * density) used to compute the distance between points.
5095    // Computed in init().
5096    private float DRAG_LAYER_INVERSE_DENSITY_SQUARED;
5097
5098    // The distance between two points reported in onTouchEvent scaled by the
5099    // density of the screen.
5100    private static final int DRAG_LAYER_FINGER_DISTANCE = 20000;
5101
5102    @Override
5103    public boolean onTouchEvent(MotionEvent ev) {
5104        if (mNativeClass == 0 || (!isClickable() && !isLongClickable())) {
5105            return false;
5106        }
5107
5108        if (DebugFlags.WEB_VIEW) {
5109            Log.v(LOGTAG, ev + " at " + ev.getEventTime()
5110                + " mTouchMode=" + mTouchMode
5111                + " numPointers=" + ev.getPointerCount());
5112        }
5113
5114        int action = ev.getAction();
5115        float x = ev.getX();
5116        float y = ev.getY();
5117        long eventTime = ev.getEventTime();
5118
5119        // mDeferMultitouch is a hack for layout tests, where it is used to
5120        // force passing multi-touch events to webkit.
5121        // FIXME: always pass multi-touch events to webkit and remove everything
5122        // related to mDeferMultitouch.
5123        if (ev.getPointerCount() > 1 &&
5124                (mDeferMultitouch || mZoomManager.isZoomScaleFixed())) {
5125            if (DebugFlags.WEB_VIEW) {
5126                Log.v(LOGTAG, "passing " + ev.getPointerCount() + " points to webkit");
5127            }
5128            passMultiTouchToWebKit(ev);
5129            return true;
5130        }
5131
5132        final ScaleGestureDetector detector =
5133                mZoomManager.getMultiTouchGestureDetector();
5134
5135        if (mZoomManager.supportsMultiTouchZoom() && ev.getPointerCount() > 1) {
5136            if (!detector.isInProgress() &&
5137                    ev.getActionMasked() != MotionEvent.ACTION_POINTER_DOWN) {
5138                // Insert a fake pointer down event in order to start
5139                // the zoom scale detector.
5140                MotionEvent temp = MotionEvent.obtain(ev);
5141                // Clear the original event and set it to
5142                // ACTION_POINTER_DOWN.
5143                try {
5144                    temp.setAction(temp.getAction() &
5145                            ~MotionEvent.ACTION_MASK |
5146                            MotionEvent.ACTION_POINTER_DOWN);
5147                    detector.onTouchEvent(temp);
5148                } finally {
5149                    temp.recycle();
5150                }
5151            }
5152
5153            detector.onTouchEvent(ev);
5154
5155            if (detector.isInProgress()) {
5156                mLastTouchTime = eventTime;
5157                cancelLongPress();
5158                mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
5159                if (!mZoomManager.supportsPanDuringZoom()) {
5160                    return true;
5161                }
5162                mTouchMode = TOUCH_DRAG_MODE;
5163                if (mVelocityTracker == null) {
5164                    mVelocityTracker = VelocityTracker.obtain();
5165                }
5166            }
5167
5168            x = detector.getFocusX();
5169            y = detector.getFocusY();
5170            action = ev.getAction() & MotionEvent.ACTION_MASK;
5171            if (action == MotionEvent.ACTION_POINTER_DOWN) {
5172                cancelTouch();
5173                action = MotionEvent.ACTION_DOWN;
5174            } else if (action == MotionEvent.ACTION_POINTER_UP) {
5175                // set mLastTouchX/Y to the remaining point
5176                mLastTouchX = x;
5177                mLastTouchY = y;
5178            } else if (action == MotionEvent.ACTION_MOVE) {
5179                // negative x or y indicate it is on the edge, skip it.
5180                if (x < 0 || y < 0) {
5181                    return true;
5182                }
5183            }
5184        }
5185
5186        // Due to the touch screen edge effect, a touch closer to the edge
5187        // always snapped to the edge. As getViewWidth() can be different from
5188        // getWidth() due to the scrollbar, adjusting the point to match
5189        // getViewWidth(). Same applied to the height.
5190        x = Math.min(x, getViewWidth() - 1);
5191        y = Math.min(y, getViewHeightWithTitle() - 1);
5192
5193        float fDeltaX = mLastTouchX - x;
5194        float fDeltaY = mLastTouchY - y;
5195        int deltaX = (int) fDeltaX;
5196        int deltaY = (int) fDeltaY;
5197        int contentX = viewToContentX((int) x + mScrollX);
5198        int contentY = viewToContentY((int) y + mScrollY);
5199
5200        switch (action) {
5201            case MotionEvent.ACTION_DOWN: {
5202                mPreventDefault = PREVENT_DEFAULT_NO;
5203                mConfirmMove = false;
5204                mInitialHitTestResult = null;
5205                if (!mScroller.isFinished()) {
5206                    // stop the current scroll animation, but if this is
5207                    // the start of a fling, allow it to add to the current
5208                    // fling's velocity
5209                    mScroller.abortAnimation();
5210                    mTouchMode = TOUCH_DRAG_START_MODE;
5211                    mConfirmMove = true;
5212                    mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY);
5213                } else if (mPrivateHandler.hasMessages(RELEASE_SINGLE_TAP)) {
5214                    mPrivateHandler.removeMessages(RELEASE_SINGLE_TAP);
5215                    if (getSettings().supportTouchOnly()) {
5216                        removeTouchHighlight(true);
5217                    }
5218                    if (deltaX * deltaX + deltaY * deltaY < mDoubleTapSlopSquare) {
5219                        mTouchMode = TOUCH_DOUBLE_TAP_MODE;
5220                    } else {
5221                        // commit the short press action for the previous tap
5222                        doShortPress();
5223                        mTouchMode = TOUCH_INIT_MODE;
5224                        mDeferTouchProcess = (!inFullScreenMode()
5225                                && mForwardTouchEvents) ? hitFocusedPlugin(
5226                                contentX, contentY) : false;
5227                    }
5228                } else { // the normal case
5229                    mTouchMode = TOUCH_INIT_MODE;
5230                    mDeferTouchProcess = (!inFullScreenMode()
5231                            && mForwardTouchEvents) ? hitFocusedPlugin(
5232                            contentX, contentY) : false;
5233                    mWebViewCore.sendMessage(
5234                            EventHub.UPDATE_FRAME_CACHE_IF_LOADING);
5235                    if (getSettings().supportTouchOnly()) {
5236                        TouchHighlightData data = new TouchHighlightData();
5237                        data.mX = contentX;
5238                        data.mY = contentY;
5239                        data.mSlop = viewToContentDimension(mNavSlop);
5240                        mWebViewCore.sendMessageDelayed(
5241                                EventHub.GET_TOUCH_HIGHLIGHT_RECTS, data,
5242                                ViewConfiguration.getTapTimeout());
5243                        if (DEBUG_TOUCH_HIGHLIGHT) {
5244                            if (getSettings().getNavDump()) {
5245                                mTouchHighlightX = (int) x + mScrollX;
5246                                mTouchHighlightY = (int) y + mScrollY;
5247                                mPrivateHandler.postDelayed(new Runnable() {
5248                                    public void run() {
5249                                        mTouchHighlightX = mTouchHighlightY = 0;
5250                                        invalidate();
5251                                    }
5252                                }, TOUCH_HIGHLIGHT_ELAPSE_TIME);
5253                            }
5254                        }
5255                    }
5256                    if (mLogEvent && eventTime - mLastTouchUpTime < 1000) {
5257                        EventLog.writeEvent(EventLogTags.BROWSER_DOUBLE_TAP_DURATION,
5258                                (eventTime - mLastTouchUpTime), eventTime);
5259                    }
5260                    if (mSelectingText) {
5261                        mDrawSelectionPointer = false;
5262                        mSelectionStarted = nativeStartSelection(contentX, contentY);
5263                        if (DebugFlags.WEB_VIEW) {
5264                            Log.v(LOGTAG, "select=" + contentX + "," + contentY);
5265                        }
5266                        invalidate();
5267                    }
5268                }
5269                // Trigger the link
5270                if (mTouchMode == TOUCH_INIT_MODE
5271                        || mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
5272                    mPrivateHandler.sendEmptyMessageDelayed(
5273                            SWITCH_TO_SHORTPRESS, TAP_TIMEOUT);
5274                    mPrivateHandler.sendEmptyMessageDelayed(
5275                            SWITCH_TO_LONGPRESS, LONG_PRESS_TIMEOUT);
5276                    if (inFullScreenMode() || mDeferTouchProcess) {
5277                        mPreventDefault = PREVENT_DEFAULT_YES;
5278                    } else if (mForwardTouchEvents) {
5279                        mPreventDefault = PREVENT_DEFAULT_MAYBE_YES;
5280                    } else {
5281                        mPreventDefault = PREVENT_DEFAULT_NO;
5282                    }
5283                    // pass the touch events from UI thread to WebCore thread
5284                    if (shouldForwardTouchEvent()) {
5285                        TouchEventData ted = new TouchEventData();
5286                        ted.mAction = action;
5287                        ted.mPoints = new Point[1];
5288                        ted.mPoints[0] = new Point(contentX, contentY);
5289                        ted.mMetaState = ev.getMetaState();
5290                        ted.mReprocess = mDeferTouchProcess;
5291                        mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
5292                        if (mDeferTouchProcess) {
5293                            // still needs to set them for compute deltaX/Y
5294                            mLastTouchX = x;
5295                            mLastTouchY = y;
5296                            break;
5297                        }
5298                        if (!inFullScreenMode()) {
5299                            mPrivateHandler.removeMessages(PREVENT_DEFAULT_TIMEOUT);
5300                            mPrivateHandler.sendMessageDelayed(mPrivateHandler
5301                                    .obtainMessage(PREVENT_DEFAULT_TIMEOUT,
5302                                            action, 0), TAP_TIMEOUT);
5303                        }
5304                    }
5305                }
5306                startTouch(x, y, eventTime);
5307                break;
5308            }
5309            case MotionEvent.ACTION_MOVE: {
5310                boolean firstMove = false;
5311                if (!mConfirmMove && (deltaX * deltaX + deltaY * deltaY)
5312                        >= mTouchSlopSquare) {
5313                    mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
5314                    mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
5315                    mConfirmMove = true;
5316                    firstMove = true;
5317                    if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
5318                        mTouchMode = TOUCH_INIT_MODE;
5319                    }
5320                    if (getSettings().supportTouchOnly()) {
5321                        removeTouchHighlight(true);
5322                    }
5323                }
5324                // pass the touch events from UI thread to WebCore thread
5325                if (shouldForwardTouchEvent() && mConfirmMove && (firstMove
5326                        || eventTime - mLastSentTouchTime > mCurrentTouchInterval)) {
5327                    TouchEventData ted = new TouchEventData();
5328                    ted.mAction = action;
5329                    ted.mPoints = new Point[1];
5330                    ted.mPoints[0] = new Point(contentX, contentY);
5331                    ted.mMetaState = ev.getMetaState();
5332                    ted.mReprocess = mDeferTouchProcess;
5333                    mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
5334                    mLastSentTouchTime = eventTime;
5335                    if (mDeferTouchProcess) {
5336                        break;
5337                    }
5338                    if (firstMove && !inFullScreenMode()) {
5339                        mPrivateHandler.sendMessageDelayed(mPrivateHandler
5340                                .obtainMessage(PREVENT_DEFAULT_TIMEOUT,
5341                                        action, 0), TAP_TIMEOUT);
5342                    }
5343                }
5344                if (mTouchMode == TOUCH_DONE_MODE
5345                        || mPreventDefault == PREVENT_DEFAULT_YES) {
5346                    // no dragging during scroll zoom animation, or when prevent
5347                    // default is yes
5348                    break;
5349                }
5350                if (mVelocityTracker == null) {
5351                    Log.e(LOGTAG, "Got null mVelocityTracker when "
5352                            + "mPreventDefault = " + mPreventDefault
5353                            + " mDeferTouchProcess = " + mDeferTouchProcess
5354                            + " mTouchMode = " + mTouchMode);
5355                }
5356                mVelocityTracker.addMovement(ev);
5357                if (mSelectingText && mSelectionStarted) {
5358                    if (DebugFlags.WEB_VIEW) {
5359                        Log.v(LOGTAG, "extend=" + contentX + "," + contentY);
5360                    }
5361                    ViewParent parent = getParent();
5362                    if (parent != null) {
5363                        parent.requestDisallowInterceptTouchEvent(true);
5364                    }
5365                    int layer = nativeScrollableLayer(contentX, contentY, mScrollingLayerRect);
5366                    if (layer == 0) {
5367                        mAutoScrollX = x <= SELECT_SCROLL ? -SELECT_SCROLL
5368                            : x >= getViewWidth() - SELECT_SCROLL
5369                            ? SELECT_SCROLL : 0;
5370                        mAutoScrollY = y <= SELECT_SCROLL ? -SELECT_SCROLL
5371                            : y >= getViewHeightWithTitle() - SELECT_SCROLL
5372                            ? SELECT_SCROLL : 0;
5373                        if (!mSentAutoScrollMessage) {
5374                            mSentAutoScrollMessage = true;
5375                            mPrivateHandler.sendEmptyMessageDelayed(
5376                                    SCROLL_SELECT_TEXT, SELECT_SCROLL_INTERVAL);
5377                        }
5378                    } else {
5379                        // TODO: allow scrollable overflow div to autoscroll
5380                    }
5381                    nativeExtendSelection(contentX, contentY);
5382                    invalidate();
5383                    break;
5384                }
5385
5386                if (mTouchMode != TOUCH_DRAG_MODE &&
5387                        mTouchMode != TOUCH_DRAG_LAYER_MODE) {
5388
5389                    if (!mConfirmMove) {
5390                        break;
5391                    }
5392
5393                    if (mPreventDefault == PREVENT_DEFAULT_MAYBE_YES
5394                            || mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN) {
5395                        // track mLastTouchTime as we may need to do fling at
5396                        // ACTION_UP
5397                        mLastTouchTime = eventTime;
5398                        break;
5399                    }
5400
5401                    // Only lock dragging to one axis if we don't have a scale in progress.
5402                    // Scaling implies free-roaming movement. Note this is only ever a question
5403                    // if mZoomManager.supportsPanDuringZoom() is true.
5404                    if (detector != null && !detector.isInProgress()) {
5405                        // if it starts nearly horizontal or vertical, enforce it
5406                        int ax = Math.abs(deltaX);
5407                        int ay = Math.abs(deltaY);
5408                        if (ax > MAX_SLOPE_FOR_DIAG * ay) {
5409                            mSnapScrollMode = SNAP_X;
5410                            mSnapPositive = deltaX > 0;
5411                        } else if (ay > MAX_SLOPE_FOR_DIAG * ax) {
5412                            mSnapScrollMode = SNAP_Y;
5413                            mSnapPositive = deltaY > 0;
5414                        }
5415                    }
5416
5417                    mTouchMode = TOUCH_DRAG_MODE;
5418                    mLastTouchX = x;
5419                    mLastTouchY = y;
5420                    fDeltaX = 0.0f;
5421                    fDeltaY = 0.0f;
5422                    deltaX = 0;
5423                    deltaY = 0;
5424
5425                    startScrollingLayer(x, y);
5426                    startDrag();
5427                }
5428
5429                // do pan
5430                boolean done = false;
5431                boolean keepScrollBarsVisible = false;
5432                if (Math.abs(fDeltaX) < 1.0f && Math.abs(fDeltaY) < 1.0f) {
5433                    mLastTouchX = x;
5434                    mLastTouchY = y;
5435                    keepScrollBarsVisible = done = true;
5436                } else {
5437                    if (mSnapScrollMode == SNAP_X || mSnapScrollMode == SNAP_Y) {
5438                        int ax = Math.abs(deltaX);
5439                        int ay = Math.abs(deltaY);
5440                        if (mSnapScrollMode == SNAP_X) {
5441                            // radical change means getting out of snap mode
5442                            if (ay > MAX_SLOPE_FOR_DIAG * ax
5443                                    && ay > MIN_BREAK_SNAP_CROSS_DISTANCE) {
5444                                mSnapScrollMode = SNAP_NONE;
5445                            }
5446                            // reverse direction means lock in the snap mode
5447                            if (ax > MAX_SLOPE_FOR_DIAG * ay &&
5448                                    (mSnapPositive
5449                                    ? deltaX < -mMinLockSnapReverseDistance
5450                                    : deltaX > mMinLockSnapReverseDistance)) {
5451                                mSnapScrollMode |= SNAP_LOCK;
5452                            }
5453                        } else {
5454                            // radical change means getting out of snap mode
5455                            if (ax > MAX_SLOPE_FOR_DIAG * ay
5456                                    && ax > MIN_BREAK_SNAP_CROSS_DISTANCE) {
5457                                mSnapScrollMode = SNAP_NONE;
5458                            }
5459                            // reverse direction means lock in the snap mode
5460                            if (ay > MAX_SLOPE_FOR_DIAG * ax &&
5461                                    (mSnapPositive
5462                                    ? deltaY < -mMinLockSnapReverseDistance
5463                                    : deltaY > mMinLockSnapReverseDistance)) {
5464                                mSnapScrollMode |= SNAP_LOCK;
5465                            }
5466                        }
5467                    }
5468                    if (mSnapScrollMode != SNAP_NONE) {
5469                        if ((mSnapScrollMode & SNAP_X) == SNAP_X) {
5470                            deltaY = 0;
5471                        } else {
5472                            deltaX = 0;
5473                        }
5474                    }
5475                    if ((deltaX | deltaY) != 0) {
5476                        if (deltaX != 0) {
5477                            mLastTouchX = x;
5478                        }
5479                        if (deltaY != 0) {
5480                            mLastTouchY = y;
5481                        }
5482                        mHeldMotionless = MOTIONLESS_FALSE;
5483                    } else {
5484                        // keep the scrollbar on the screen even there is no
5485                        // scroll
5486                        mLastTouchX = x;
5487                        mLastTouchY = y;
5488                        keepScrollBarsVisible = true;
5489                    }
5490                    mLastTouchTime = eventTime;
5491                    mUserScroll = true;
5492                }
5493
5494                doDrag(deltaX, deltaY);
5495
5496                // Turn off scrollbars when dragging a layer.
5497                if (keepScrollBarsVisible &&
5498                        mTouchMode != TOUCH_DRAG_LAYER_MODE) {
5499                    if (mHeldMotionless != MOTIONLESS_TRUE) {
5500                        mHeldMotionless = MOTIONLESS_TRUE;
5501                        invalidate();
5502                    }
5503                    // keep the scrollbar on the screen even there is no scroll
5504                    awakenScrollBars(ViewConfiguration.getScrollDefaultDelay(),
5505                            false);
5506                    // return false to indicate that we can't pan out of the
5507                    // view space
5508                    return !done;
5509                }
5510                break;
5511            }
5512            case MotionEvent.ACTION_UP: {
5513                if (!isFocused()) requestFocus();
5514                // pass the touch events from UI thread to WebCore thread
5515                if (shouldForwardTouchEvent()) {
5516                    TouchEventData ted = new TouchEventData();
5517                    ted.mAction = action;
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                }
5524                mLastTouchUpTime = eventTime;
5525                switch (mTouchMode) {
5526                    case TOUCH_DOUBLE_TAP_MODE: // double tap
5527                        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
5528                        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
5529                        if (inFullScreenMode() || mDeferTouchProcess) {
5530                            TouchEventData ted = new TouchEventData();
5531                            ted.mAction = WebViewCore.ACTION_DOUBLETAP;
5532                            ted.mPoints = new Point[1];
5533                            ted.mPoints[0] = new Point(contentX, contentY);
5534                            ted.mMetaState = ev.getMetaState();
5535                            ted.mReprocess = mDeferTouchProcess;
5536                            mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
5537                        } else if (mPreventDefault != PREVENT_DEFAULT_YES){
5538                            mZoomManager.handleDoubleTap(mLastTouchX, mLastTouchY);
5539                            mTouchMode = TOUCH_DONE_MODE;
5540                        }
5541                        break;
5542                    case TOUCH_INIT_MODE: // tap
5543                    case TOUCH_SHORTPRESS_START_MODE:
5544                    case TOUCH_SHORTPRESS_MODE:
5545                        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
5546                        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
5547                        if (mConfirmMove) {
5548                            Log.w(LOGTAG, "Miss a drag as we are waiting for" +
5549                                    " WebCore's response for touch down.");
5550                            if (mPreventDefault != PREVENT_DEFAULT_YES
5551                                    && (computeMaxScrollX() > 0
5552                                            || computeMaxScrollY() > 0)) {
5553                                // If the user has performed a very quick touch
5554                                // sequence it is possible that we may get here
5555                                // before WebCore has had a chance to process the events.
5556                                // In this case, any call to preventDefault in the
5557                                // JS touch handler will not have been executed yet.
5558                                // Hence we will see both the UI (now) and WebCore
5559                                // (when context switches) handling the event,
5560                                // regardless of whether the web developer actually
5561                                // doeses preventDefault in their touch handler. This
5562                                // is the nature of our asynchronous touch model.
5563
5564                                // we will not rewrite drag code here, but we
5565                                // will try fling if it applies.
5566                                WebViewCore.reducePriority();
5567                                // to get better performance, pause updating the
5568                                // picture
5569                                WebViewCore.pauseUpdatePicture(mWebViewCore);
5570                                // fall through to TOUCH_DRAG_MODE
5571                            } else {
5572                                // WebKit may consume the touch event and modify
5573                                // DOM. drawContentPicture() will be called with
5574                                // animateSroll as true for better performance.
5575                                // Force redraw in high-quality.
5576                                invalidate();
5577                                break;
5578                            }
5579                        } else {
5580                            if (mSelectingText) {
5581                                // tapping on selection or controls does nothing
5582                                if (!nativeHitSelection(contentX, contentY)) {
5583                                    selectionDone();
5584                                }
5585                                break;
5586                            }
5587                            // only trigger double tap if the WebView is
5588                            // scalable
5589                            if (mTouchMode == TOUCH_INIT_MODE
5590                                    && (canZoomIn() || canZoomOut())) {
5591                                mPrivateHandler.sendEmptyMessageDelayed(
5592                                        RELEASE_SINGLE_TAP, ViewConfiguration
5593                                                .getDoubleTapTimeout());
5594                            } else {
5595                                doShortPress();
5596                            }
5597                            break;
5598                        }
5599                    case TOUCH_DRAG_MODE:
5600                    case TOUCH_DRAG_LAYER_MODE:
5601                        mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
5602                        mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS);
5603                        // if the user waits a while w/o moving before the
5604                        // up, we don't want to do a fling
5605                        if (eventTime - mLastTouchTime <= MIN_FLING_TIME) {
5606                            if (mVelocityTracker == null) {
5607                                Log.e(LOGTAG, "Got null mVelocityTracker when "
5608                                        + "mPreventDefault = "
5609                                        + mPreventDefault
5610                                        + " mDeferTouchProcess = "
5611                                        + mDeferTouchProcess);
5612                            }
5613                            mVelocityTracker.addMovement(ev);
5614                            // set to MOTIONLESS_IGNORE so that it won't keep
5615                            // removing and sending message in
5616                            // drawCoreAndCursorRing()
5617                            mHeldMotionless = MOTIONLESS_IGNORE;
5618                            doFling();
5619                            break;
5620                        } else {
5621                            if (mScroller.springBack(mScrollX, mScrollY, 0,
5622                                    computeMaxScrollX(), 0,
5623                                    computeMaxScrollY())) {
5624                                invalidate();
5625                            }
5626                        }
5627                        // redraw in high-quality, as we're done dragging
5628                        mHeldMotionless = MOTIONLESS_TRUE;
5629                        invalidate();
5630                        // fall through
5631                    case TOUCH_DRAG_START_MODE:
5632                        // TOUCH_DRAG_START_MODE should not happen for the real
5633                        // device as we almost certain will get a MOVE. But this
5634                        // is possible on emulator.
5635                        mLastVelocity = 0;
5636                        WebViewCore.resumePriority();
5637                        if (!mSelectingText) {
5638                            WebViewCore.resumeUpdatePicture(mWebViewCore);
5639                        }
5640                        break;
5641                }
5642                stopTouch();
5643                break;
5644            }
5645            case MotionEvent.ACTION_CANCEL: {
5646                if (mTouchMode == TOUCH_DRAG_MODE) {
5647                    mScroller.springBack(mScrollX, mScrollY, 0,
5648                            computeMaxScrollX(), 0, computeMaxScrollY());
5649                    invalidate();
5650                }
5651                cancelWebCoreTouchEvent(contentX, contentY, false);
5652                cancelTouch();
5653                break;
5654            }
5655        }
5656        return true;
5657    }
5658
5659    private void passMultiTouchToWebKit(MotionEvent ev) {
5660        TouchEventData ted = new TouchEventData();
5661        ted.mAction = ev.getAction() & MotionEvent.ACTION_MASK;
5662        final int count = ev.getPointerCount();
5663        ted.mPoints = new Point[count];
5664        for (int c = 0; c < count; c++) {
5665            int x = viewToContentX((int) ev.getX(c) + mScrollX);
5666            int y = viewToContentY((int) ev.getY(c) + mScrollY);
5667            ted.mPoints[c] = new Point(x, y);
5668        }
5669        ted.mMetaState = ev.getMetaState();
5670        ted.mReprocess = mDeferTouchProcess;
5671        mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
5672        cancelLongPress();
5673        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
5674        mPreventDefault = PREVENT_DEFAULT_IGNORE;
5675    }
5676
5677    private void cancelWebCoreTouchEvent(int x, int y, boolean removeEvents) {
5678        if (shouldForwardTouchEvent()) {
5679            if (removeEvents) {
5680                mWebViewCore.removeMessages(EventHub.TOUCH_EVENT);
5681            }
5682            TouchEventData ted = new TouchEventData();
5683            ted.mPoints = new Point[1];
5684            ted.mPoints[0] = new Point(x, y);
5685            ted.mAction = MotionEvent.ACTION_CANCEL;
5686            mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
5687            mPreventDefault = PREVENT_DEFAULT_IGNORE;
5688        }
5689    }
5690
5691    private void startTouch(float x, float y, long eventTime) {
5692        // Remember where the motion event started
5693        mLastTouchX = x;
5694        mLastTouchY = y;
5695        mLastTouchTime = eventTime;
5696        mVelocityTracker = VelocityTracker.obtain();
5697        mSnapScrollMode = SNAP_NONE;
5698    }
5699
5700    private void startDrag() {
5701        WebViewCore.reducePriority();
5702        // to get better performance, pause updating the picture
5703        WebViewCore.pauseUpdatePicture(mWebViewCore);
5704        if (!mDragFromTextInput) {
5705            nativeHideCursor();
5706        }
5707
5708        if (mHorizontalScrollBarMode != SCROLLBAR_ALWAYSOFF
5709                || mVerticalScrollBarMode != SCROLLBAR_ALWAYSOFF) {
5710            mZoomManager.invokeZoomPicker();
5711        }
5712    }
5713
5714    private void doDrag(int deltaX, int deltaY) {
5715        if ((deltaX | deltaY) != 0) {
5716            int oldX = mScrollX;
5717            int oldY = mScrollY;
5718            int rangeX = computeMaxScrollX();
5719            int rangeY = computeMaxScrollY();
5720            int overscrollDistance = mOverscrollDistance;
5721
5722            // Check for the original scrolling layer in case we change
5723            // directions.  mTouchMode might be TOUCH_DRAG_MODE if we have
5724            // reached the edge of a layer but mScrollingLayer will be non-zero
5725            // if we initiated the drag on a layer.
5726            if (mScrollingLayer != 0) {
5727                final int contentX = viewToContentDimension(deltaX);
5728                final int contentY = viewToContentDimension(deltaY);
5729
5730                // Check the scrolling bounds to see if we will actually do any
5731                // scrolling.  The rectangle is in document coordinates.
5732                final int maxX = mScrollingLayerRect.right;
5733                final int maxY = mScrollingLayerRect.bottom;
5734                final int resultX = Math.max(0,
5735                        Math.min(mScrollingLayerRect.left + contentX, maxX));
5736                final int resultY = Math.max(0,
5737                        Math.min(mScrollingLayerRect.top + contentY, maxY));
5738
5739                if (resultX != mScrollingLayerRect.left ||
5740                        resultY != mScrollingLayerRect.top) {
5741                    // In case we switched to dragging the page.
5742                    mTouchMode = TOUCH_DRAG_LAYER_MODE;
5743                    deltaX = contentX;
5744                    deltaY = contentY;
5745                    oldX = mScrollingLayerRect.left;
5746                    oldY = mScrollingLayerRect.top;
5747                    rangeX = maxX;
5748                    rangeY = maxY;
5749                } else {
5750                    // Scroll the main page if we are not going to scroll the
5751                    // layer.  This does not reset mScrollingLayer in case the
5752                    // user changes directions and the layer can scroll the
5753                    // other way.
5754                    mTouchMode = TOUCH_DRAG_MODE;
5755                }
5756            }
5757
5758            if (mOverScrollGlow != null) {
5759                mOverScrollGlow.setOverScrollDeltas(deltaX, deltaY);
5760            }
5761
5762            overScrollBy(deltaX, deltaY, oldX, oldY,
5763                    rangeX, rangeY,
5764                    mOverscrollDistance, mOverscrollDistance, true);
5765            if (mOverScrollGlow != null && mOverScrollGlow.isAnimating()) {
5766                invalidate();
5767            }
5768        }
5769        mZoomManager.keepZoomPickerVisible();
5770    }
5771
5772    private void stopTouch() {
5773        // we also use mVelocityTracker == null to tell us that we are
5774        // not "moving around", so we can take the slower/prettier
5775        // mode in the drawing code
5776        if (mVelocityTracker != null) {
5777            mVelocityTracker.recycle();
5778            mVelocityTracker = null;
5779        }
5780
5781        // Release any pulled glows
5782        if (mOverScrollGlow != null) {
5783            mOverScrollGlow.releaseAll();
5784        }
5785    }
5786
5787    private void cancelTouch() {
5788        // we also use mVelocityTracker == null to tell us that we are
5789        // not "moving around", so we can take the slower/prettier
5790        // mode in the drawing code
5791        if (mVelocityTracker != null) {
5792            mVelocityTracker.recycle();
5793            mVelocityTracker = null;
5794        }
5795
5796        if ((mTouchMode == TOUCH_DRAG_MODE
5797                || mTouchMode == TOUCH_DRAG_LAYER_MODE) && !mSelectingText) {
5798            WebViewCore.resumePriority();
5799            WebViewCore.resumeUpdatePicture(mWebViewCore);
5800        }
5801        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
5802        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
5803        mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
5804        mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS);
5805        if (getSettings().supportTouchOnly()) {
5806            removeTouchHighlight(true);
5807        }
5808        mHeldMotionless = MOTIONLESS_TRUE;
5809        mTouchMode = TOUCH_DONE_MODE;
5810        nativeHideCursor();
5811    }
5812
5813    private long mTrackballFirstTime = 0;
5814    private long mTrackballLastTime = 0;
5815    private float mTrackballRemainsX = 0.0f;
5816    private float mTrackballRemainsY = 0.0f;
5817    private int mTrackballXMove = 0;
5818    private int mTrackballYMove = 0;
5819    private boolean mSelectingText = false;
5820    private boolean mSelectionStarted = false;
5821    private boolean mExtendSelection = false;
5822    private boolean mDrawSelectionPointer = false;
5823    private static final int TRACKBALL_KEY_TIMEOUT = 1000;
5824    private static final int TRACKBALL_TIMEOUT = 200;
5825    private static final int TRACKBALL_WAIT = 100;
5826    private static final int TRACKBALL_SCALE = 400;
5827    private static final int TRACKBALL_SCROLL_COUNT = 5;
5828    private static final int TRACKBALL_MOVE_COUNT = 10;
5829    private static final int TRACKBALL_MULTIPLIER = 3;
5830    private static final int SELECT_CURSOR_OFFSET = 16;
5831    private static final int SELECT_SCROLL = 5;
5832    private int mSelectX = 0;
5833    private int mSelectY = 0;
5834    private boolean mFocusSizeChanged = false;
5835    private boolean mTrackballDown = false;
5836    private long mTrackballUpTime = 0;
5837    private long mLastCursorTime = 0;
5838    private Rect mLastCursorBounds;
5839
5840    // Set by default; BrowserActivity clears to interpret trackball data
5841    // directly for movement. Currently, the framework only passes
5842    // arrow key events, not trackball events, from one child to the next
5843    private boolean mMapTrackballToArrowKeys = true;
5844
5845    public void setMapTrackballToArrowKeys(boolean setMap) {
5846        mMapTrackballToArrowKeys = setMap;
5847    }
5848
5849    void resetTrackballTime() {
5850        mTrackballLastTime = 0;
5851    }
5852
5853    @Override
5854    public boolean onTrackballEvent(MotionEvent ev) {
5855        long time = ev.getEventTime();
5856        if ((ev.getMetaState() & KeyEvent.META_ALT_ON) != 0) {
5857            if (ev.getY() > 0) pageDown(true);
5858            if (ev.getY() < 0) pageUp(true);
5859            return true;
5860        }
5861        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
5862            if (mSelectingText) {
5863                return true; // discard press if copy in progress
5864            }
5865            mTrackballDown = true;
5866            if (mNativeClass == 0) {
5867                return false;
5868            }
5869            nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true);
5870            if (time - mLastCursorTime <= TRACKBALL_TIMEOUT
5871                    && !mLastCursorBounds.equals(nativeGetCursorRingBounds())) {
5872                nativeSelectBestAt(mLastCursorBounds);
5873            }
5874            if (DebugFlags.WEB_VIEW) {
5875                Log.v(LOGTAG, "onTrackballEvent down ev=" + ev
5876                        + " time=" + time
5877                        + " mLastCursorTime=" + mLastCursorTime);
5878            }
5879            if (isInTouchMode()) requestFocusFromTouch();
5880            return false; // let common code in onKeyDown at it
5881        }
5882        if (ev.getAction() == MotionEvent.ACTION_UP) {
5883            // LONG_PRESS_CENTER is set in common onKeyDown
5884            mPrivateHandler.removeMessages(LONG_PRESS_CENTER);
5885            mTrackballDown = false;
5886            mTrackballUpTime = time;
5887            if (mSelectingText) {
5888                if (mExtendSelection) {
5889                    copySelection();
5890                    selectionDone();
5891                } else {
5892                    mExtendSelection = true;
5893                    nativeSetExtendSelection();
5894                    invalidate(); // draw the i-beam instead of the arrow
5895                }
5896                return true; // discard press if copy in progress
5897            }
5898            if (DebugFlags.WEB_VIEW) {
5899                Log.v(LOGTAG, "onTrackballEvent up ev=" + ev
5900                        + " time=" + time
5901                );
5902            }
5903            return false; // let common code in onKeyUp at it
5904        }
5905        if ((mMapTrackballToArrowKeys && (ev.getMetaState() & KeyEvent.META_SHIFT_ON) == 0) ||
5906                (mAccessibilityInjector != null || mAccessibilityScriptInjected)) {
5907            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent gmail quit");
5908            return false;
5909        }
5910        if (mTrackballDown) {
5911            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent down quit");
5912            return true; // discard move if trackball is down
5913        }
5914        if (time - mTrackballUpTime < TRACKBALL_TIMEOUT) {
5915            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent up timeout quit");
5916            return true;
5917        }
5918        // TODO: alternatively we can do panning as touch does
5919        switchOutDrawHistory();
5920        if (time - mTrackballLastTime > TRACKBALL_TIMEOUT) {
5921            if (DebugFlags.WEB_VIEW) {
5922                Log.v(LOGTAG, "onTrackballEvent time="
5923                        + time + " last=" + mTrackballLastTime);
5924            }
5925            mTrackballFirstTime = time;
5926            mTrackballXMove = mTrackballYMove = 0;
5927        }
5928        mTrackballLastTime = time;
5929        if (DebugFlags.WEB_VIEW) {
5930            Log.v(LOGTAG, "onTrackballEvent ev=" + ev + " time=" + time);
5931        }
5932        mTrackballRemainsX += ev.getX();
5933        mTrackballRemainsY += ev.getY();
5934        doTrackball(time, ev.getMetaState());
5935        return true;
5936    }
5937
5938    void moveSelection(float xRate, float yRate) {
5939        if (mNativeClass == 0)
5940            return;
5941        int width = getViewWidth();
5942        int height = getViewHeight();
5943        mSelectX += xRate;
5944        mSelectY += yRate;
5945        int maxX = width + mScrollX;
5946        int maxY = height + mScrollY;
5947        mSelectX = Math.min(maxX, Math.max(mScrollX - SELECT_CURSOR_OFFSET
5948                , mSelectX));
5949        mSelectY = Math.min(maxY, Math.max(mScrollY - SELECT_CURSOR_OFFSET
5950                , mSelectY));
5951        if (DebugFlags.WEB_VIEW) {
5952            Log.v(LOGTAG, "moveSelection"
5953                    + " mSelectX=" + mSelectX
5954                    + " mSelectY=" + mSelectY
5955                    + " mScrollX=" + mScrollX
5956                    + " mScrollY=" + mScrollY
5957                    + " xRate=" + xRate
5958                    + " yRate=" + yRate
5959                    );
5960        }
5961        nativeMoveSelection(viewToContentX(mSelectX), viewToContentY(mSelectY));
5962        int scrollX = mSelectX < mScrollX ? -SELECT_CURSOR_OFFSET
5963                : mSelectX > maxX - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET
5964                : 0;
5965        int scrollY = mSelectY < mScrollY ? -SELECT_CURSOR_OFFSET
5966                : mSelectY > maxY - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET
5967                : 0;
5968        pinScrollBy(scrollX, scrollY, true, 0);
5969        Rect select = new Rect(mSelectX, mSelectY, mSelectX + 1, mSelectY + 1);
5970        requestRectangleOnScreen(select);
5971        invalidate();
5972   }
5973
5974    private int scaleTrackballX(float xRate, int width) {
5975        int xMove = (int) (xRate / TRACKBALL_SCALE * width);
5976        int nextXMove = xMove;
5977        if (xMove > 0) {
5978            if (xMove > mTrackballXMove) {
5979                xMove -= mTrackballXMove;
5980            }
5981        } else if (xMove < mTrackballXMove) {
5982            xMove -= mTrackballXMove;
5983        }
5984        mTrackballXMove = nextXMove;
5985        return xMove;
5986    }
5987
5988    private int scaleTrackballY(float yRate, int height) {
5989        int yMove = (int) (yRate / TRACKBALL_SCALE * height);
5990        int nextYMove = yMove;
5991        if (yMove > 0) {
5992            if (yMove > mTrackballYMove) {
5993                yMove -= mTrackballYMove;
5994            }
5995        } else if (yMove < mTrackballYMove) {
5996            yMove -= mTrackballYMove;
5997        }
5998        mTrackballYMove = nextYMove;
5999        return yMove;
6000    }
6001
6002    private int keyCodeToSoundsEffect(int keyCode) {
6003        switch(keyCode) {
6004            case KeyEvent.KEYCODE_DPAD_UP:
6005                return SoundEffectConstants.NAVIGATION_UP;
6006            case KeyEvent.KEYCODE_DPAD_RIGHT:
6007                return SoundEffectConstants.NAVIGATION_RIGHT;
6008            case KeyEvent.KEYCODE_DPAD_DOWN:
6009                return SoundEffectConstants.NAVIGATION_DOWN;
6010            case KeyEvent.KEYCODE_DPAD_LEFT:
6011                return SoundEffectConstants.NAVIGATION_LEFT;
6012        }
6013        throw new IllegalArgumentException("keyCode must be one of " +
6014                "{KEYCODE_DPAD_UP, KEYCODE_DPAD_RIGHT, KEYCODE_DPAD_DOWN, " +
6015                "KEYCODE_DPAD_LEFT}.");
6016    }
6017
6018    private void doTrackball(long time, int metaState) {
6019        int elapsed = (int) (mTrackballLastTime - mTrackballFirstTime);
6020        if (elapsed == 0) {
6021            elapsed = TRACKBALL_TIMEOUT;
6022        }
6023        float xRate = mTrackballRemainsX * 1000 / elapsed;
6024        float yRate = mTrackballRemainsY * 1000 / elapsed;
6025        int viewWidth = getViewWidth();
6026        int viewHeight = getViewHeight();
6027        if (mSelectingText) {
6028            if (!mDrawSelectionPointer) {
6029                // The last selection was made by touch, disabling drawing the
6030                // selection pointer. Allow the trackball to adjust the
6031                // position of the touch control.
6032                mSelectX = contentToViewX(nativeSelectionX());
6033                mSelectY = contentToViewY(nativeSelectionY());
6034                mDrawSelectionPointer = mExtendSelection = true;
6035                nativeSetExtendSelection();
6036            }
6037            moveSelection(scaleTrackballX(xRate, viewWidth),
6038                    scaleTrackballY(yRate, viewHeight));
6039            mTrackballRemainsX = mTrackballRemainsY = 0;
6040            return;
6041        }
6042        float ax = Math.abs(xRate);
6043        float ay = Math.abs(yRate);
6044        float maxA = Math.max(ax, ay);
6045        if (DebugFlags.WEB_VIEW) {
6046            Log.v(LOGTAG, "doTrackball elapsed=" + elapsed
6047                    + " xRate=" + xRate
6048                    + " yRate=" + yRate
6049                    + " mTrackballRemainsX=" + mTrackballRemainsX
6050                    + " mTrackballRemainsY=" + mTrackballRemainsY);
6051        }
6052        int width = mContentWidth - viewWidth;
6053        int height = mContentHeight - viewHeight;
6054        if (width < 0) width = 0;
6055        if (height < 0) height = 0;
6056        ax = Math.abs(mTrackballRemainsX * TRACKBALL_MULTIPLIER);
6057        ay = Math.abs(mTrackballRemainsY * TRACKBALL_MULTIPLIER);
6058        maxA = Math.max(ax, ay);
6059        int count = Math.max(0, (int) maxA);
6060        int oldScrollX = mScrollX;
6061        int oldScrollY = mScrollY;
6062        if (count > 0) {
6063            int selectKeyCode = ax < ay ? mTrackballRemainsY < 0 ?
6064                    KeyEvent.KEYCODE_DPAD_UP : KeyEvent.KEYCODE_DPAD_DOWN :
6065                    mTrackballRemainsX < 0 ? KeyEvent.KEYCODE_DPAD_LEFT :
6066                    KeyEvent.KEYCODE_DPAD_RIGHT;
6067            count = Math.min(count, TRACKBALL_MOVE_COUNT);
6068            if (DebugFlags.WEB_VIEW) {
6069                Log.v(LOGTAG, "doTrackball keyCode=" + selectKeyCode
6070                        + " count=" + count
6071                        + " mTrackballRemainsX=" + mTrackballRemainsX
6072                        + " mTrackballRemainsY=" + mTrackballRemainsY);
6073            }
6074            if (mNativeClass != 0 && nativePageShouldHandleShiftAndArrows()) {
6075                for (int i = 0; i < count; i++) {
6076                    letPageHandleNavKey(selectKeyCode, time, true, metaState);
6077                }
6078                letPageHandleNavKey(selectKeyCode, time, false, metaState);
6079            } else if (navHandledKey(selectKeyCode, count, false, time)) {
6080                playSoundEffect(keyCodeToSoundsEffect(selectKeyCode));
6081            }
6082            mTrackballRemainsX = mTrackballRemainsY = 0;
6083        }
6084        if (count >= TRACKBALL_SCROLL_COUNT) {
6085            int xMove = scaleTrackballX(xRate, width);
6086            int yMove = scaleTrackballY(yRate, height);
6087            if (DebugFlags.WEB_VIEW) {
6088                Log.v(LOGTAG, "doTrackball pinScrollBy"
6089                        + " count=" + count
6090                        + " xMove=" + xMove + " yMove=" + yMove
6091                        + " mScrollX-oldScrollX=" + (mScrollX-oldScrollX)
6092                        + " mScrollY-oldScrollY=" + (mScrollY-oldScrollY)
6093                        );
6094            }
6095            if (Math.abs(mScrollX - oldScrollX) > Math.abs(xMove)) {
6096                xMove = 0;
6097            }
6098            if (Math.abs(mScrollY - oldScrollY) > Math.abs(yMove)) {
6099                yMove = 0;
6100            }
6101            if (xMove != 0 || yMove != 0) {
6102                pinScrollBy(xMove, yMove, true, 0);
6103            }
6104            mUserScroll = true;
6105        }
6106    }
6107
6108    /**
6109     * Compute the maximum horizontal scroll position. Used by {@link OverScrollGlow}.
6110     * @return Maximum horizontal scroll position within real content
6111     */
6112    int computeMaxScrollX() {
6113        return Math.max(computeRealHorizontalScrollRange() - getViewWidth(), 0);
6114    }
6115
6116    /**
6117     * Compute the maximum vertical scroll position. Used by {@link OverScrollGlow}.
6118     * @return Maximum vertical scroll position within real content
6119     */
6120    int computeMaxScrollY() {
6121        return Math.max(computeRealVerticalScrollRange() + getTitleHeight()
6122                - getViewHeightWithTitle(), 0);
6123    }
6124
6125    boolean updateScrollCoordinates(int x, int y) {
6126        int oldX = mScrollX;
6127        int oldY = mScrollY;
6128        mScrollX = x;
6129        mScrollY = y;
6130        if (oldX != mScrollX || oldY != mScrollY) {
6131            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
6132            return true;
6133        } else {
6134            return false;
6135        }
6136    }
6137
6138    public void flingScroll(int vx, int vy) {
6139        mScroller.fling(mScrollX, mScrollY, vx, vy, 0, computeMaxScrollX(), 0,
6140                computeMaxScrollY(), mOverflingDistance, mOverflingDistance);
6141        invalidate();
6142    }
6143
6144    private void doFling() {
6145        if (mVelocityTracker == null) {
6146            return;
6147        }
6148        int maxX = computeMaxScrollX();
6149        int maxY = computeMaxScrollY();
6150
6151        mVelocityTracker.computeCurrentVelocity(1000, mMaximumFling);
6152        int vx = (int) mVelocityTracker.getXVelocity();
6153        int vy = (int) mVelocityTracker.getYVelocity();
6154
6155        int scrollX = mScrollX;
6156        int scrollY = mScrollY;
6157        int overscrollDistance = mOverscrollDistance;
6158        int overflingDistance = mOverflingDistance;
6159
6160        // Use the layer's scroll data if applicable.
6161        if (mTouchMode == TOUCH_DRAG_LAYER_MODE) {
6162            scrollX = mScrollingLayerRect.left;
6163            scrollY = mScrollingLayerRect.top;
6164            maxX = mScrollingLayerRect.right;
6165            maxY = mScrollingLayerRect.bottom;
6166            // No overscrolling for layers.
6167            overscrollDistance = overflingDistance = 0;
6168        }
6169
6170        if (mSnapScrollMode != SNAP_NONE) {
6171            if ((mSnapScrollMode & SNAP_X) == SNAP_X) {
6172                vy = 0;
6173            } else {
6174                vx = 0;
6175            }
6176        }
6177        if (true /* EMG release: make our fling more like Maps' */) {
6178            // maps cuts their velocity in half
6179            vx = vx * 3 / 4;
6180            vy = vy * 3 / 4;
6181        }
6182        if ((maxX == 0 && vy == 0) || (maxY == 0 && vx == 0)) {
6183            WebViewCore.resumePriority();
6184            if (!mSelectingText) {
6185                WebViewCore.resumeUpdatePicture(mWebViewCore);
6186            }
6187            if (mScroller.springBack(scrollX, scrollY, 0, maxX, 0, maxY)) {
6188                invalidate();
6189            }
6190            return;
6191        }
6192        float currentVelocity = mScroller.getCurrVelocity();
6193        float velocity = (float) Math.hypot(vx, vy);
6194        if (mLastVelocity > 0 && currentVelocity > 0 && velocity
6195                > mLastVelocity * MINIMUM_VELOCITY_RATIO_FOR_ACCELERATION) {
6196            float deltaR = (float) (Math.abs(Math.atan2(mLastVelY, mLastVelX)
6197                    - Math.atan2(vy, vx)));
6198            final float circle = (float) (Math.PI) * 2.0f;
6199            if (deltaR > circle * 0.9f || deltaR < circle * 0.1f) {
6200                vx += currentVelocity * mLastVelX / mLastVelocity;
6201                vy += currentVelocity * mLastVelY / mLastVelocity;
6202                velocity = (float) Math.hypot(vx, vy);
6203                if (DebugFlags.WEB_VIEW) {
6204                    Log.v(LOGTAG, "doFling vx= " + vx + " vy=" + vy);
6205                }
6206            } else if (DebugFlags.WEB_VIEW) {
6207                Log.v(LOGTAG, "doFling missed " + deltaR / circle);
6208            }
6209        } else if (DebugFlags.WEB_VIEW) {
6210            Log.v(LOGTAG, "doFling start last=" + mLastVelocity
6211                    + " current=" + currentVelocity
6212                    + " vx=" + vx + " vy=" + vy
6213                    + " maxX=" + maxX + " maxY=" + maxY
6214                    + " scrollX=" + scrollX + " scrollY=" + scrollY
6215                    + " layer=" + mScrollingLayer);
6216        }
6217
6218        // Allow sloppy flings without overscrolling at the edges.
6219        if ((scrollX == 0 || scrollX == maxX) && Math.abs(vx) < Math.abs(vy)) {
6220            vx = 0;
6221        }
6222        if ((scrollY == 0 || scrollY == maxY) && Math.abs(vy) < Math.abs(vx)) {
6223            vy = 0;
6224        }
6225
6226        if (overscrollDistance < overflingDistance) {
6227            if ((vx > 0 && scrollX == -overscrollDistance) ||
6228                    (vx < 0 && scrollX == maxX + overscrollDistance)) {
6229                vx = 0;
6230            }
6231            if ((vy > 0 && scrollY == -overscrollDistance) ||
6232                    (vy < 0 && scrollY == maxY + overscrollDistance)) {
6233                vy = 0;
6234            }
6235        }
6236
6237        mLastVelX = vx;
6238        mLastVelY = vy;
6239        mLastVelocity = velocity;
6240
6241        // no horizontal overscroll if the content just fits
6242        mScroller.fling(scrollX, scrollY, -vx, -vy, 0, maxX, 0, maxY,
6243                maxX == 0 ? 0 : overflingDistance, overflingDistance);
6244        // Duration is calculated based on velocity. With range boundaries and overscroll
6245        // we may not know how long the final animation will take. (Hence the deprecation
6246        // warning on the call below.) It's not a big deal for scroll bars but if webcore
6247        // resumes during this effect we will take a performance hit. See computeScroll;
6248        // we resume webcore there when the animation is finished.
6249        final int time = mScroller.getDuration();
6250
6251        // Suppress scrollbars for layer scrolling.
6252        if (mTouchMode != TOUCH_DRAG_LAYER_MODE) {
6253            awakenScrollBars(time);
6254        }
6255
6256        invalidate();
6257    }
6258
6259    /**
6260     * Returns a view containing zoom controls i.e. +/- buttons. The caller is
6261     * in charge of installing this view to the view hierarchy. This view will
6262     * become visible when the user starts scrolling via touch and fade away if
6263     * the user does not interact with it.
6264     * <p/>
6265     * API version 3 introduces a built-in zoom mechanism that is shown
6266     * automatically by the MapView. This is the preferred approach for
6267     * showing the zoom UI.
6268     *
6269     * @deprecated The built-in zoom mechanism is preferred, see
6270     *             {@link WebSettings#setBuiltInZoomControls(boolean)}.
6271     */
6272    @Deprecated
6273    public View getZoomControls() {
6274        if (!getSettings().supportZoom()) {
6275            Log.w(LOGTAG, "This WebView doesn't support zoom.");
6276            return null;
6277        }
6278        return mZoomManager.getExternalZoomPicker();
6279    }
6280
6281    void dismissZoomControl() {
6282        mZoomManager.dismissZoomPicker();
6283    }
6284
6285    float getDefaultZoomScale() {
6286        return mZoomManager.getDefaultScale();
6287    }
6288
6289    /**
6290     * @return TRUE if the WebView can be zoomed in.
6291     */
6292    public boolean canZoomIn() {
6293        return mZoomManager.canZoomIn();
6294    }
6295
6296    /**
6297     * @return TRUE if the WebView can be zoomed out.
6298     */
6299    public boolean canZoomOut() {
6300        return mZoomManager.canZoomOut();
6301    }
6302
6303    /**
6304     * Perform zoom in in the webview
6305     * @return TRUE if zoom in succeeds. FALSE if no zoom changes.
6306     */
6307    public boolean zoomIn() {
6308        return mZoomManager.zoomIn();
6309    }
6310
6311    /**
6312     * Perform zoom out in the webview
6313     * @return TRUE if zoom out succeeds. FALSE if no zoom changes.
6314     */
6315    public boolean zoomOut() {
6316        return mZoomManager.zoomOut();
6317    }
6318
6319    private void updateSelection() {
6320        if (mNativeClass == 0) {
6321            return;
6322        }
6323        // mLastTouchX and mLastTouchY are the point in the current viewport
6324        int contentX = viewToContentX((int) mLastTouchX + mScrollX);
6325        int contentY = viewToContentY((int) mLastTouchY + mScrollY);
6326        Rect rect = new Rect(contentX - mNavSlop, contentY - mNavSlop,
6327                contentX + mNavSlop, contentY + mNavSlop);
6328        nativeSelectBestAt(rect);
6329        mInitialHitTestResult = hitTestResult(null);
6330    }
6331
6332    /**
6333     * Scroll the focused text field/area to match the WebTextView
6334     * @param xPercent New x position of the WebTextView from 0 to 1.
6335     * @param y New y position of the WebTextView in view coordinates
6336     */
6337    /*package*/ void scrollFocusedTextInput(float xPercent, int y) {
6338        if (!inEditingMode() || mWebViewCore == null) {
6339            return;
6340        }
6341        mWebViewCore.sendMessage(EventHub.SCROLL_TEXT_INPUT,
6342                // Since this position is relative to the top of the text input
6343                // field, we do not need to take the title bar's height into
6344                // consideration.
6345                viewToContentDimension(y),
6346                new Float(xPercent));
6347    }
6348
6349    /**
6350     * Set our starting point and time for a drag from the WebTextView.
6351     */
6352    /*package*/ void initiateTextFieldDrag(float x, float y, long eventTime) {
6353        if (!inEditingMode()) {
6354            return;
6355        }
6356        mLastTouchX = x + (float) (mWebTextView.getLeft() - mScrollX);
6357        mLastTouchY = y + (float) (mWebTextView.getTop() - mScrollY);
6358        mLastTouchTime = eventTime;
6359        if (!mScroller.isFinished()) {
6360            abortAnimation();
6361            mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY);
6362        }
6363        mSnapScrollMode = SNAP_NONE;
6364        mVelocityTracker = VelocityTracker.obtain();
6365        mTouchMode = TOUCH_DRAG_START_MODE;
6366    }
6367
6368    /**
6369     * Given a motion event from the WebTextView, set its location to our
6370     * coordinates, and handle the event.
6371     */
6372    /*package*/ boolean textFieldDrag(MotionEvent event) {
6373        if (!inEditingMode()) {
6374            return false;
6375        }
6376        mDragFromTextInput = true;
6377        event.offsetLocation((float) (mWebTextView.getLeft() - mScrollX),
6378                (float) (mWebTextView.getTop() - mScrollY));
6379        boolean result = onTouchEvent(event);
6380        mDragFromTextInput = false;
6381        return result;
6382    }
6383
6384    /**
6385     * Due a touch up from a WebTextView.  This will be handled by webkit to
6386     * change the selection.
6387     * @param event MotionEvent in the WebTextView's coordinates.
6388     */
6389    /*package*/ void touchUpOnTextField(MotionEvent event) {
6390        if (!inEditingMode()) {
6391            return;
6392        }
6393        int x = viewToContentX((int) event.getX() + mWebTextView.getLeft());
6394        int y = viewToContentY((int) event.getY() + mWebTextView.getTop());
6395        nativeMotionUp(x, y, mNavSlop);
6396    }
6397
6398    /**
6399     * Called when pressing the center key or trackball on a textfield.
6400     */
6401    /*package*/ void centerKeyPressOnTextField() {
6402        mWebViewCore.sendMessage(EventHub.CLICK, nativeCursorFramePointer(),
6403                    nativeCursorNodePointer());
6404    }
6405
6406    private void doShortPress() {
6407        if (mNativeClass == 0) {
6408            return;
6409        }
6410        if (mPreventDefault == PREVENT_DEFAULT_YES) {
6411            return;
6412        }
6413        mTouchMode = TOUCH_DONE_MODE;
6414        switchOutDrawHistory();
6415        // mLastTouchX and mLastTouchY are the point in the current viewport
6416        int contentX = viewToContentX((int) mLastTouchX + mScrollX);
6417        int contentY = viewToContentY((int) mLastTouchY + mScrollY);
6418        if (getSettings().supportTouchOnly()) {
6419            removeTouchHighlight(false);
6420            WebViewCore.TouchUpData touchUpData = new WebViewCore.TouchUpData();
6421            // use "0" as generation id to inform WebKit to use the same x/y as
6422            // it used when processing GET_TOUCH_HIGHLIGHT_RECTS
6423            touchUpData.mMoveGeneration = 0;
6424            mWebViewCore.sendMessage(EventHub.TOUCH_UP, touchUpData);
6425        } else if (nativePointInNavCache(contentX, contentY, mNavSlop)) {
6426            WebViewCore.MotionUpData motionUpData = new WebViewCore
6427                    .MotionUpData();
6428            motionUpData.mFrame = nativeCacheHitFramePointer();
6429            motionUpData.mNode = nativeCacheHitNodePointer();
6430            motionUpData.mBounds = nativeCacheHitNodeBounds();
6431            motionUpData.mX = contentX;
6432            motionUpData.mY = contentY;
6433            mWebViewCore.sendMessageAtFrontOfQueue(EventHub.VALID_NODE_BOUNDS,
6434                    motionUpData);
6435        } else {
6436            doMotionUp(contentX, contentY);
6437        }
6438    }
6439
6440    private void doMotionUp(int contentX, int contentY) {
6441        if (nativeMotionUp(contentX, contentY, mNavSlop) && mLogEvent) {
6442            EventLog.writeEvent(EventLogTags.BROWSER_SNAP_CENTER);
6443        }
6444        if (nativeHasCursorNode() && !nativeCursorIsTextInput()) {
6445            playSoundEffect(SoundEffectConstants.CLICK);
6446        }
6447    }
6448
6449    /*
6450     * Return true if the view (Plugin) is fully visible and maximized inside
6451     * the WebView.
6452     */
6453    boolean isPluginFitOnScreen(ViewManager.ChildView view) {
6454        final int viewWidth = getViewWidth();
6455        final int viewHeight = getViewHeightWithTitle();
6456        float scale = Math.min((float) viewWidth / view.width, (float) viewHeight / view.height);
6457        scale = mZoomManager.computeScaleWithLimits(scale);
6458        return !mZoomManager.willScaleTriggerZoom(scale)
6459                && contentToViewX(view.x) >= mScrollX
6460                && contentToViewX(view.x + view.width) <= mScrollX + viewWidth
6461                && contentToViewY(view.y) >= mScrollY
6462                && contentToViewY(view.y + view.height) <= mScrollY + viewHeight;
6463    }
6464
6465    /*
6466     * Maximize and center the rectangle, specified in the document coordinate
6467     * space, inside the WebView. If the zoom doesn't need to be changed, do an
6468     * animated scroll to center it. If the zoom needs to be changed, find the
6469     * zoom center and do a smooth zoom transition.
6470     */
6471    void centerFitRect(int docX, int docY, int docWidth, int docHeight) {
6472        int viewWidth = getViewWidth();
6473        int viewHeight = getViewHeightWithTitle();
6474        float scale = Math.min((float) viewWidth / docWidth, (float) viewHeight
6475                / docHeight);
6476        scale = mZoomManager.computeScaleWithLimits(scale);
6477        if (!mZoomManager.willScaleTriggerZoom(scale)) {
6478            pinScrollTo(contentToViewX(docX + docWidth / 2) - viewWidth / 2,
6479                    contentToViewY(docY + docHeight / 2) - viewHeight / 2,
6480                    true, 0);
6481        } else {
6482            float actualScale = mZoomManager.getScale();
6483            float oldScreenX = docX * actualScale - mScrollX;
6484            float rectViewX = docX * scale;
6485            float rectViewWidth = docWidth * scale;
6486            float newMaxWidth = mContentWidth * scale;
6487            float newScreenX = (viewWidth - rectViewWidth) / 2;
6488            // pin the newX to the WebView
6489            if (newScreenX > rectViewX) {
6490                newScreenX = rectViewX;
6491            } else if (newScreenX > (newMaxWidth - rectViewX - rectViewWidth)) {
6492                newScreenX = viewWidth - (newMaxWidth - rectViewX);
6493            }
6494            float zoomCenterX = (oldScreenX * scale - newScreenX * actualScale)
6495                    / (scale - actualScale);
6496            float oldScreenY = docY * actualScale + getTitleHeight()
6497                    - mScrollY;
6498            float rectViewY = docY * scale + getTitleHeight();
6499            float rectViewHeight = docHeight * scale;
6500            float newMaxHeight = mContentHeight * scale + getTitleHeight();
6501            float newScreenY = (viewHeight - rectViewHeight) / 2;
6502            // pin the newY to the WebView
6503            if (newScreenY > rectViewY) {
6504                newScreenY = rectViewY;
6505            } else if (newScreenY > (newMaxHeight - rectViewY - rectViewHeight)) {
6506                newScreenY = viewHeight - (newMaxHeight - rectViewY);
6507            }
6508            float zoomCenterY = (oldScreenY * scale - newScreenY * actualScale)
6509                    / (scale - actualScale);
6510            mZoomManager.setZoomCenter(zoomCenterX, zoomCenterY);
6511            mZoomManager.startZoomAnimation(scale, false);
6512        }
6513    }
6514
6515    // Called by JNI to handle a touch on a node representing an email address,
6516    // address, or phone number
6517    private void overrideLoading(String url) {
6518        mCallbackProxy.uiOverrideUrlLoading(url);
6519    }
6520
6521    @Override
6522    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
6523        // FIXME: If a subwindow is showing find, and the user touches the
6524        // background window, it can steal focus.
6525        if (mFindIsUp) return false;
6526        boolean result = false;
6527        if (inEditingMode()) {
6528            result = mWebTextView.requestFocus(direction,
6529                    previouslyFocusedRect);
6530        } else {
6531            result = super.requestFocus(direction, previouslyFocusedRect);
6532            if (mWebViewCore.getSettings().getNeedInitialFocus()) {
6533                // For cases such as GMail, where we gain focus from a direction,
6534                // we want to move to the first available link.
6535                // FIXME: If there are no visible links, we may not want to
6536                int fakeKeyDirection = 0;
6537                switch(direction) {
6538                    case View.FOCUS_UP:
6539                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_UP;
6540                        break;
6541                    case View.FOCUS_DOWN:
6542                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_DOWN;
6543                        break;
6544                    case View.FOCUS_LEFT:
6545                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_LEFT;
6546                        break;
6547                    case View.FOCUS_RIGHT:
6548                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_RIGHT;
6549                        break;
6550                    default:
6551                        return result;
6552                }
6553                if (mNativeClass != 0 && !nativeHasCursorNode()) {
6554                    navHandledKey(fakeKeyDirection, 1, true, 0);
6555                }
6556            }
6557        }
6558        return result;
6559    }
6560
6561    @Override
6562    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
6563        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
6564
6565        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
6566        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
6567        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
6568        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
6569
6570        int measuredHeight = heightSize;
6571        int measuredWidth = widthSize;
6572
6573        // Grab the content size from WebViewCore.
6574        int contentHeight = contentToViewDimension(mContentHeight);
6575        int contentWidth = contentToViewDimension(mContentWidth);
6576
6577//        Log.d(LOGTAG, "------- measure " + heightMode);
6578
6579        if (heightMode != MeasureSpec.EXACTLY) {
6580            mHeightCanMeasure = true;
6581            measuredHeight = contentHeight;
6582            if (heightMode == MeasureSpec.AT_MOST) {
6583                // If we are larger than the AT_MOST height, then our height can
6584                // no longer be measured and we should scroll internally.
6585                if (measuredHeight > heightSize) {
6586                    measuredHeight = heightSize;
6587                    mHeightCanMeasure = false;
6588                } else if (measuredHeight < heightSize) {
6589                    measuredHeight |= MEASURED_STATE_TOO_SMALL;
6590                }
6591            }
6592        } else {
6593            mHeightCanMeasure = false;
6594        }
6595        if (mNativeClass != 0) {
6596            nativeSetHeightCanMeasure(mHeightCanMeasure);
6597        }
6598        // For the width, always use the given size unless unspecified.
6599        if (widthMode == MeasureSpec.UNSPECIFIED) {
6600            mWidthCanMeasure = true;
6601            measuredWidth = contentWidth;
6602        } else {
6603            if (measuredWidth < contentWidth) {
6604                measuredWidth |= MEASURED_STATE_TOO_SMALL;
6605            }
6606            mWidthCanMeasure = false;
6607        }
6608
6609        synchronized (this) {
6610            setMeasuredDimension(measuredWidth, measuredHeight);
6611        }
6612    }
6613
6614    @Override
6615    public boolean requestChildRectangleOnScreen(View child,
6616                                                 Rect rect,
6617                                                 boolean immediate) {
6618        if (mNativeClass == 0) {
6619            return false;
6620        }
6621        // don't scroll while in zoom animation. When it is done, we will adjust
6622        // the necessary components (e.g., WebTextView if it is in editing mode)
6623        if (mZoomManager.isFixedLengthAnimationInProgress()) {
6624            return false;
6625        }
6626
6627        rect.offset(child.getLeft() - child.getScrollX(),
6628                child.getTop() - child.getScrollY());
6629
6630        Rect content = new Rect(viewToContentX(mScrollX),
6631                viewToContentY(mScrollY),
6632                viewToContentX(mScrollX + getWidth()
6633                - getVerticalScrollbarWidth()),
6634                viewToContentY(mScrollY + getViewHeightWithTitle()));
6635        content = nativeSubtractLayers(content);
6636        int screenTop = contentToViewY(content.top);
6637        int screenBottom = contentToViewY(content.bottom);
6638        int height = screenBottom - screenTop;
6639        int scrollYDelta = 0;
6640
6641        if (rect.bottom > screenBottom) {
6642            int oneThirdOfScreenHeight = height / 3;
6643            if (rect.height() > 2 * oneThirdOfScreenHeight) {
6644                // If the rectangle is too tall to fit in the bottom two thirds
6645                // of the screen, place it at the top.
6646                scrollYDelta = rect.top - screenTop;
6647            } else {
6648                // If the rectangle will still fit on screen, we want its
6649                // top to be in the top third of the screen.
6650                scrollYDelta = rect.top - (screenTop + oneThirdOfScreenHeight);
6651            }
6652        } else if (rect.top < screenTop) {
6653            scrollYDelta = rect.top - screenTop;
6654        }
6655
6656        int screenLeft = contentToViewX(content.left);
6657        int screenRight = contentToViewX(content.right);
6658        int width = screenRight - screenLeft;
6659        int scrollXDelta = 0;
6660
6661        if (rect.right > screenRight && rect.left > screenLeft) {
6662            if (rect.width() > width) {
6663                scrollXDelta += (rect.left - screenLeft);
6664            } else {
6665                scrollXDelta += (rect.right - screenRight);
6666            }
6667        } else if (rect.left < screenLeft) {
6668            scrollXDelta -= (screenLeft - rect.left);
6669        }
6670
6671        if ((scrollYDelta | scrollXDelta) != 0) {
6672            return pinScrollBy(scrollXDelta, scrollYDelta, !immediate, 0);
6673        }
6674
6675        return false;
6676    }
6677
6678    /* package */ void replaceTextfieldText(int oldStart, int oldEnd,
6679            String replace, int newStart, int newEnd) {
6680        WebViewCore.ReplaceTextData arg = new WebViewCore.ReplaceTextData();
6681        arg.mReplace = replace;
6682        arg.mNewStart = newStart;
6683        arg.mNewEnd = newEnd;
6684        mTextGeneration++;
6685        arg.mTextGeneration = mTextGeneration;
6686        mWebViewCore.sendMessage(EventHub.REPLACE_TEXT, oldStart, oldEnd, arg);
6687    }
6688
6689    /* package */ void passToJavaScript(String currentText, KeyEvent event) {
6690        WebViewCore.JSKeyData arg = new WebViewCore.JSKeyData();
6691        arg.mEvent = event;
6692        arg.mCurrentText = currentText;
6693        // Increase our text generation number, and pass it to webcore thread
6694        mTextGeneration++;
6695        mWebViewCore.sendMessage(EventHub.PASS_TO_JS, mTextGeneration, 0, arg);
6696        // WebKit's document state is not saved until about to leave the page.
6697        // To make sure the host application, like Browser, has the up to date
6698        // document state when it goes to background, we force to save the
6699        // document state.
6700        mWebViewCore.removeMessages(EventHub.SAVE_DOCUMENT_STATE);
6701        mWebViewCore.sendMessageDelayed(EventHub.SAVE_DOCUMENT_STATE,
6702                cursorData(), 1000);
6703    }
6704
6705    /* package */ synchronized WebViewCore getWebViewCore() {
6706        return mWebViewCore;
6707    }
6708
6709    //-------------------------------------------------------------------------
6710    // Methods can be called from a separate thread, like WebViewCore
6711    // If it needs to call the View system, it has to send message.
6712    //-------------------------------------------------------------------------
6713
6714    /**
6715     * General handler to receive message coming from webkit thread
6716     */
6717    class PrivateHandler extends Handler {
6718        @Override
6719        public void handleMessage(Message msg) {
6720            // exclude INVAL_RECT_MSG_ID since it is frequently output
6721            if (DebugFlags.WEB_VIEW && msg.what != INVAL_RECT_MSG_ID) {
6722                if (msg.what >= FIRST_PRIVATE_MSG_ID
6723                        && msg.what <= LAST_PRIVATE_MSG_ID) {
6724                    Log.v(LOGTAG, HandlerPrivateDebugString[msg.what
6725                            - FIRST_PRIVATE_MSG_ID]);
6726                } else if (msg.what >= FIRST_PACKAGE_MSG_ID
6727                        && msg.what <= LAST_PACKAGE_MSG_ID) {
6728                    Log.v(LOGTAG, HandlerPackageDebugString[msg.what
6729                            - FIRST_PACKAGE_MSG_ID]);
6730                } else {
6731                    Log.v(LOGTAG, Integer.toString(msg.what));
6732                }
6733            }
6734            if (mWebViewCore == null) {
6735                // after WebView's destroy() is called, skip handling messages.
6736                return;
6737            }
6738            switch (msg.what) {
6739                case REMEMBER_PASSWORD: {
6740                    mDatabase.setUsernamePassword(
6741                            msg.getData().getString("host"),
6742                            msg.getData().getString("username"),
6743                            msg.getData().getString("password"));
6744                    ((Message) msg.obj).sendToTarget();
6745                    break;
6746                }
6747                case NEVER_REMEMBER_PASSWORD: {
6748                    mDatabase.setUsernamePassword(
6749                            msg.getData().getString("host"), null, null);
6750                    ((Message) msg.obj).sendToTarget();
6751                    break;
6752                }
6753                case PREVENT_DEFAULT_TIMEOUT: {
6754                    // if timeout happens, cancel it so that it won't block UI
6755                    // to continue handling touch events
6756                    if ((msg.arg1 == MotionEvent.ACTION_DOWN
6757                            && mPreventDefault == PREVENT_DEFAULT_MAYBE_YES)
6758                            || (msg.arg1 == MotionEvent.ACTION_MOVE
6759                            && mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN)) {
6760                        cancelWebCoreTouchEvent(
6761                                viewToContentX((int) mLastTouchX + mScrollX),
6762                                viewToContentY((int) mLastTouchY + mScrollY),
6763                                true);
6764                    }
6765                    break;
6766                }
6767                case SCROLL_SELECT_TEXT: {
6768                    if (mAutoScrollX == 0 && mAutoScrollY == 0) {
6769                        mSentAutoScrollMessage = false;
6770                        break;
6771                    }
6772                    pinScrollBy(mAutoScrollX, mAutoScrollY, true, 0);
6773                    sendEmptyMessageDelayed(
6774                            SCROLL_SELECT_TEXT, SELECT_SCROLL_INTERVAL);
6775                    break;
6776                }
6777                case SWITCH_TO_SHORTPRESS: {
6778                    mInitialHitTestResult = null; // set by updateSelection()
6779                    if (mTouchMode == TOUCH_INIT_MODE) {
6780                        if (!getSettings().supportTouchOnly()
6781                                && mPreventDefault != PREVENT_DEFAULT_YES) {
6782                            mTouchMode = TOUCH_SHORTPRESS_START_MODE;
6783                            updateSelection();
6784                        } else {
6785                            // set to TOUCH_SHORTPRESS_MODE so that it won't
6786                            // trigger double tap any more
6787                            mTouchMode = TOUCH_SHORTPRESS_MODE;
6788                        }
6789                    } else if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
6790                        mTouchMode = TOUCH_DONE_MODE;
6791                    }
6792                    break;
6793                }
6794                case SWITCH_TO_LONGPRESS: {
6795                    if (getSettings().supportTouchOnly()) {
6796                        removeTouchHighlight(false);
6797                    }
6798                    if (inFullScreenMode() || mDeferTouchProcess) {
6799                        TouchEventData ted = new TouchEventData();
6800                        ted.mAction = WebViewCore.ACTION_LONGPRESS;
6801                        ted.mPoints = new Point[1];
6802                        ted.mPoints[0] = new Point(viewToContentX((int) mLastTouchX + mScrollX),
6803                                                   viewToContentY((int) mLastTouchY + mScrollY));
6804                        // metaState for long press is tricky. Should it be the
6805                        // state when the press started or when the press was
6806                        // released? Or some intermediary key state? For
6807                        // simplicity for now, we don't set it.
6808                        ted.mMetaState = 0;
6809                        ted.mReprocess = mDeferTouchProcess;
6810                        mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
6811                    } else if (mPreventDefault != PREVENT_DEFAULT_YES) {
6812                        mTouchMode = TOUCH_DONE_MODE;
6813                        performLongClick();
6814                    }
6815                    break;
6816                }
6817                case RELEASE_SINGLE_TAP: {
6818                    doShortPress();
6819                    break;
6820                }
6821                case SCROLL_BY_MSG_ID:
6822                    setContentScrollBy(msg.arg1, msg.arg2, (Boolean) msg.obj);
6823                    break;
6824                case SYNC_SCROLL_TO_MSG_ID:
6825                    if (mUserScroll) {
6826                        // if user has scrolled explicitly, don't sync the
6827                        // scroll position any more
6828                        mUserScroll = false;
6829                        break;
6830                    }
6831                    setContentScrollTo(msg.arg1, msg.arg2);
6832                    break;
6833                case SCROLL_TO_MSG_ID:
6834                    if (setContentScrollTo(msg.arg1, msg.arg2)) {
6835                        // if we can't scroll to the exact position due to pin,
6836                        // send a message to WebCore to re-scroll when we get a
6837                        // new picture
6838                        mUserScroll = false;
6839                        mWebViewCore.sendMessage(EventHub.SYNC_SCROLL,
6840                                msg.arg1, msg.arg2);
6841                    }
6842                    break;
6843                case SPAWN_SCROLL_TO_MSG_ID:
6844                    spawnContentScrollTo(msg.arg1, msg.arg2);
6845                    break;
6846                case UPDATE_ZOOM_RANGE: {
6847                    WebViewCore.ViewState viewState = (WebViewCore.ViewState) msg.obj;
6848                    // mScrollX contains the new minPrefWidth
6849                    mZoomManager.updateZoomRange(viewState, getViewWidth(), viewState.mScrollX);
6850                    break;
6851                }
6852                case REPLACE_BASE_CONTENT: {
6853                    nativeReplaceBaseContent(msg.arg1);
6854                    break;
6855                }
6856                case NEW_PICTURE_MSG_ID: {
6857                    // called for new content
6858                    mUserScroll = false;
6859                    final WebViewCore.DrawData draw = (WebViewCore.DrawData) msg.obj;
6860                    setBaseLayer(draw.mBaseLayer, draw.mInvalRegion.getBounds());
6861                    final Point viewSize = draw.mViewSize;
6862                    WebViewCore.ViewState viewState = draw.mViewState;
6863                    boolean isPictureAfterFirstLayout = viewState != null;
6864                    if (isPictureAfterFirstLayout) {
6865                        // Reset the last sent data here since dealing with new page.
6866                        mLastWidthSent = 0;
6867                        mZoomManager.onFirstLayout(draw);
6868                        if (!mDrawHistory) {
6869                            setContentScrollTo(viewState.mScrollX, viewState.mScrollY);
6870                            // As we are on a new page, remove the WebTextView. This
6871                            // is necessary for page loads driven by webkit, and in
6872                            // particular when the user was on a password field, so
6873                            // the WebTextView was visible.
6874                            clearTextEntry();
6875                        }
6876                    }
6877
6878                    // We update the layout (i.e. request a layout from the
6879                    // view system) if the last view size that we sent to
6880                    // WebCore matches the view size of the picture we just
6881                    // received in the fixed dimension.
6882                    final boolean updateLayout = viewSize.x == mLastWidthSent
6883                            && viewSize.y == mLastHeightSent;
6884                    recordNewContentSize(draw.mContentSize.x,
6885                            draw.mContentSize.y, updateLayout);
6886                    if (DebugFlags.WEB_VIEW) {
6887                        Rect b = draw.mInvalRegion.getBounds();
6888                        Log.v(LOGTAG, "NEW_PICTURE_MSG_ID {" +
6889                                b.left+","+b.top+","+b.right+","+b.bottom+"}");
6890                    }
6891                    invalidateContentRect(draw.mInvalRegion.getBounds());
6892
6893                    if (mPictureListener != null) {
6894                        mPictureListener.onNewPicture(WebView.this, capturePicture());
6895                    }
6896
6897                    // update the zoom information based on the new picture
6898                    mZoomManager.onNewPicture(draw);
6899
6900                    if (draw.mFocusSizeChanged && inEditingMode()) {
6901                        mFocusSizeChanged = true;
6902                    }
6903                    if (isPictureAfterFirstLayout) {
6904                        mViewManager.postReadyToDrawAll();
6905                    }
6906                    break;
6907                }
6908                case WEBCORE_INITIALIZED_MSG_ID:
6909                    // nativeCreate sets mNativeClass to a non-zero value
6910                    nativeCreate(msg.arg1);
6911                    break;
6912                case UPDATE_TEXTFIELD_TEXT_MSG_ID:
6913                    // Make sure that the textfield is currently focused
6914                    // and representing the same node as the pointer.
6915                    if (inEditingMode() &&
6916                            mWebTextView.isSameTextField(msg.arg1)) {
6917                        if (msg.getData().getBoolean("password")) {
6918                            Spannable text = (Spannable) mWebTextView.getText();
6919                            int start = Selection.getSelectionStart(text);
6920                            int end = Selection.getSelectionEnd(text);
6921                            mWebTextView.setInPassword(true);
6922                            // Restore the selection, which may have been
6923                            // ruined by setInPassword.
6924                            Spannable pword =
6925                                    (Spannable) mWebTextView.getText();
6926                            Selection.setSelection(pword, start, end);
6927                        // If the text entry has created more events, ignore
6928                        // this one.
6929                        } else if (msg.arg2 == mTextGeneration) {
6930                            String text = (String) msg.obj;
6931                            if (null == text) {
6932                                text = "";
6933                            }
6934                            mWebTextView.setTextAndKeepSelection(text);
6935                        }
6936                    }
6937                    break;
6938                case REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID:
6939                    displaySoftKeyboard(true);
6940                    // fall through to UPDATE_TEXT_SELECTION_MSG_ID
6941                case UPDATE_TEXT_SELECTION_MSG_ID:
6942                    updateTextSelectionFromMessage(msg.arg1, msg.arg2,
6943                            (WebViewCore.TextSelectionData) msg.obj);
6944                    break;
6945                case FORM_DID_BLUR:
6946                    if (inEditingMode()
6947                            && mWebTextView.isSameTextField(msg.arg1)) {
6948                        hideSoftKeyboard();
6949                    }
6950                    break;
6951                case RETURN_LABEL:
6952                    if (inEditingMode()
6953                            && mWebTextView.isSameTextField(msg.arg1)) {
6954                        mWebTextView.setHint((String) msg.obj);
6955                        InputMethodManager imm
6956                                = InputMethodManager.peekInstance();
6957                        // The hint is propagated to the IME in
6958                        // onCreateInputConnection.  If the IME is already
6959                        // active, restart it so that its hint text is updated.
6960                        if (imm != null && imm.isActive(mWebTextView)) {
6961                            imm.restartInput(mWebTextView);
6962                        }
6963                    }
6964                    break;
6965                case UNHANDLED_NAV_KEY:
6966                    navHandledKey(msg.arg1, 1, false, 0);
6967                    break;
6968                case UPDATE_TEXT_ENTRY_MSG_ID:
6969                    // this is sent after finishing resize in WebViewCore. Make
6970                    // sure the text edit box is still on the  screen.
6971                    if (inEditingMode() && nativeCursorIsTextInput()) {
6972                        mWebTextView.bringIntoView();
6973                        rebuildWebTextView();
6974                    }
6975                    break;
6976                case CLEAR_TEXT_ENTRY:
6977                    clearTextEntry();
6978                    break;
6979                case INVAL_RECT_MSG_ID: {
6980                    Rect r = (Rect)msg.obj;
6981                    if (r == null) {
6982                        invalidate();
6983                    } else {
6984                        // we need to scale r from content into view coords,
6985                        // which viewInvalidate() does for us
6986                        viewInvalidate(r.left, r.top, r.right, r.bottom);
6987                    }
6988                    break;
6989                }
6990                case REQUEST_FORM_DATA:
6991                    AutoCompleteAdapter adapter = (AutoCompleteAdapter) msg.obj;
6992                    if (mWebTextView.isSameTextField(msg.arg1)) {
6993                        mWebTextView.setAdapterCustom(adapter);
6994                    }
6995                    break;
6996                case RESUME_WEBCORE_PRIORITY:
6997                    WebViewCore.resumePriority();
6998                    WebViewCore.resumeUpdatePicture(mWebViewCore);
6999                    break;
7000
7001                case LONG_PRESS_CENTER:
7002                    // as this is shared by keydown and trackballdown, reset all
7003                    // the states
7004                    mGotCenterDown = false;
7005                    mTrackballDown = false;
7006                    performLongClick();
7007                    break;
7008
7009                case WEBCORE_NEED_TOUCH_EVENTS:
7010                    mForwardTouchEvents = (msg.arg1 != 0);
7011                    break;
7012
7013                case PREVENT_TOUCH_ID:
7014                    if (inFullScreenMode()) {
7015                        break;
7016                    }
7017                    if (msg.obj == null) {
7018                        if (msg.arg1 == MotionEvent.ACTION_DOWN
7019                                && mPreventDefault == PREVENT_DEFAULT_MAYBE_YES) {
7020                            // if prevent default is called from WebCore, UI
7021                            // will not handle the rest of the touch events any
7022                            // more.
7023                            mPreventDefault = msg.arg2 == 1 ? PREVENT_DEFAULT_YES
7024                                    : PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN;
7025                        } else if (msg.arg1 == MotionEvent.ACTION_MOVE
7026                                && mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN) {
7027                            // the return for the first ACTION_MOVE will decide
7028                            // whether UI will handle touch or not. Currently no
7029                            // support for alternating prevent default
7030                            mPreventDefault = msg.arg2 == 1 ? PREVENT_DEFAULT_YES
7031                                    : PREVENT_DEFAULT_NO;
7032                        }
7033                        if (mPreventDefault == PREVENT_DEFAULT_YES) {
7034                            mTouchHighlightRegion.setEmpty();
7035                        }
7036                    } else if (msg.arg2 == 0) {
7037                        // prevent default is not called in WebCore, so the
7038                        // message needs to be reprocessed in UI
7039                        TouchEventData ted = (TouchEventData) msg.obj;
7040                        switch (ted.mAction) {
7041                            case MotionEvent.ACTION_DOWN:
7042                                mLastDeferTouchX = contentToViewX(ted.mPoints[0].x)
7043                                        - mScrollX;
7044                                mLastDeferTouchY = contentToViewY(ted.mPoints[0].y)
7045                                        - mScrollY;
7046                                mDeferTouchMode = TOUCH_INIT_MODE;
7047                                break;
7048                            case MotionEvent.ACTION_MOVE: {
7049                                // no snapping in defer process
7050                                int x = contentToViewX(ted.mPoints[0].x) - mScrollX;
7051                                int y = contentToViewY(ted.mPoints[0].y) - mScrollY;
7052                                if (mDeferTouchMode != TOUCH_DRAG_MODE) {
7053                                    mDeferTouchMode = TOUCH_DRAG_MODE;
7054                                    mLastDeferTouchX = x;
7055                                    mLastDeferTouchY = y;
7056                                    startScrollingLayer(x, y);
7057                                    startDrag();
7058                                }
7059                                int deltaX = pinLocX((int) (mScrollX
7060                                        + mLastDeferTouchX - x))
7061                                        - mScrollX;
7062                                int deltaY = pinLocY((int) (mScrollY
7063                                        + mLastDeferTouchY - y))
7064                                        - mScrollY;
7065                                doDrag(deltaX, deltaY);
7066                                if (deltaX != 0) mLastDeferTouchX = x;
7067                                if (deltaY != 0) mLastDeferTouchY = y;
7068                                break;
7069                            }
7070                            case MotionEvent.ACTION_UP:
7071                            case MotionEvent.ACTION_CANCEL:
7072                                if (mDeferTouchMode == TOUCH_DRAG_MODE) {
7073                                    // no fling in defer process
7074                                    mScroller.springBack(mScrollX, mScrollY, 0,
7075                                            computeMaxScrollX(), 0,
7076                                            computeMaxScrollY());
7077                                    invalidate();
7078                                    WebViewCore.resumePriority();
7079                                    WebViewCore.resumeUpdatePicture(mWebViewCore);
7080                                }
7081                                mDeferTouchMode = TOUCH_DONE_MODE;
7082                                break;
7083                            case WebViewCore.ACTION_DOUBLETAP:
7084                                // doDoubleTap() needs mLastTouchX/Y as anchor
7085                                mLastTouchX = contentToViewX(ted.mPoints[0].x) - mScrollX;
7086                                mLastTouchY = contentToViewY(ted.mPoints[0].y) - mScrollY;
7087                                mZoomManager.handleDoubleTap(mLastTouchX, mLastTouchY);
7088                                mDeferTouchMode = TOUCH_DONE_MODE;
7089                                break;
7090                            case WebViewCore.ACTION_LONGPRESS:
7091                                HitTestResult hitTest = getHitTestResult();
7092                                if (hitTest != null && hitTest.mType
7093                                        != HitTestResult.UNKNOWN_TYPE) {
7094                                    performLongClick();
7095                                }
7096                                mDeferTouchMode = TOUCH_DONE_MODE;
7097                                break;
7098                        }
7099                    }
7100                    break;
7101
7102                case REQUEST_KEYBOARD:
7103                    if (msg.arg1 == 0) {
7104                        hideSoftKeyboard();
7105                    } else {
7106                        displaySoftKeyboard(false);
7107                    }
7108                    break;
7109
7110                case FIND_AGAIN:
7111                    // Ignore if find has been dismissed.
7112                    if (mFindIsUp && mFindCallback != null) {
7113                        mFindCallback.findAll();
7114                    }
7115                    break;
7116
7117                case DRAG_HELD_MOTIONLESS:
7118                    mHeldMotionless = MOTIONLESS_TRUE;
7119                    invalidate();
7120                    // fall through to keep scrollbars awake
7121
7122                case AWAKEN_SCROLL_BARS:
7123                    if (mTouchMode == TOUCH_DRAG_MODE
7124                            && mHeldMotionless == MOTIONLESS_TRUE) {
7125                        awakenScrollBars(ViewConfiguration
7126                                .getScrollDefaultDelay(), false);
7127                        mPrivateHandler.sendMessageDelayed(mPrivateHandler
7128                                .obtainMessage(AWAKEN_SCROLL_BARS),
7129                                ViewConfiguration.getScrollDefaultDelay());
7130                    }
7131                    break;
7132
7133                case DO_MOTION_UP:
7134                    doMotionUp(msg.arg1, msg.arg2);
7135                    break;
7136
7137                case SHOW_FULLSCREEN: {
7138                    View view = (View) msg.obj;
7139                    int npp = msg.arg1;
7140
7141                    if (inFullScreenMode()) {
7142                        Log.w(LOGTAG, "Should not have another full screen.");
7143                        dismissFullScreenMode();
7144                    }
7145                    mFullScreenHolder = new PluginFullScreenHolder(WebView.this, npp);
7146                    mFullScreenHolder.setContentView(view);
7147                    mFullScreenHolder.setCancelable(false);
7148                    mFullScreenHolder.setCanceledOnTouchOutside(false);
7149                    mFullScreenHolder.show();
7150
7151                    break;
7152                }
7153                case HIDE_FULLSCREEN:
7154                    dismissFullScreenMode();
7155                    break;
7156
7157                case DOM_FOCUS_CHANGED:
7158                    if (inEditingMode()) {
7159                        nativeClearCursor();
7160                        rebuildWebTextView();
7161                    }
7162                    break;
7163
7164                case SHOW_RECT_MSG_ID: {
7165                    WebViewCore.ShowRectData data = (WebViewCore.ShowRectData) msg.obj;
7166                    int x = mScrollX;
7167                    int left = contentToViewX(data.mLeft);
7168                    int width = contentToViewDimension(data.mWidth);
7169                    int maxWidth = contentToViewDimension(data.mContentWidth);
7170                    int viewWidth = getViewWidth();
7171                    if (width < viewWidth) {
7172                        // center align
7173                        x += left + width / 2 - mScrollX - viewWidth / 2;
7174                    } else {
7175                        x += (int) (left + data.mXPercentInDoc * width
7176                                - mScrollX - data.mXPercentInView * viewWidth);
7177                    }
7178                    if (DebugFlags.WEB_VIEW) {
7179                        Log.v(LOGTAG, "showRectMsg=(left=" + left + ",width=" +
7180                              width + ",maxWidth=" + maxWidth +
7181                              ",viewWidth=" + viewWidth + ",x="
7182                              + x + ",xPercentInDoc=" + data.mXPercentInDoc +
7183                              ",xPercentInView=" + data.mXPercentInView+ ")");
7184                    }
7185                    // use the passing content width to cap x as the current
7186                    // mContentWidth may not be updated yet
7187                    x = Math.max(0,
7188                            (Math.min(maxWidth, x + viewWidth)) - viewWidth);
7189                    int top = contentToViewY(data.mTop);
7190                    int height = contentToViewDimension(data.mHeight);
7191                    int maxHeight = contentToViewDimension(data.mContentHeight);
7192                    int viewHeight = getViewHeight();
7193                    int y = (int) (top + data.mYPercentInDoc * height -
7194                                   data.mYPercentInView * viewHeight);
7195                    if (DebugFlags.WEB_VIEW) {
7196                        Log.v(LOGTAG, "showRectMsg=(top=" + top + ",height=" +
7197                              height + ",maxHeight=" + maxHeight +
7198                              ",viewHeight=" + viewHeight + ",y="
7199                              + y + ",yPercentInDoc=" + data.mYPercentInDoc +
7200                              ",yPercentInView=" + data.mYPercentInView+ ")");
7201                    }
7202                    // use the passing content height to cap y as the current
7203                    // mContentHeight may not be updated yet
7204                    y = Math.max(0,
7205                            (Math.min(maxHeight, y + viewHeight) - viewHeight));
7206                    // We need to take into account the visible title height
7207                    // when scrolling since y is an absolute view position.
7208                    y = Math.max(0, y - getVisibleTitleHeight());
7209                    scrollTo(x, y);
7210                    }
7211                    break;
7212
7213                case CENTER_FIT_RECT:
7214                    Rect r = (Rect)msg.obj;
7215                    centerFitRect(r.left, r.top, r.width(), r.height());
7216                    break;
7217
7218                case SET_SCROLLBAR_MODES:
7219                    mHorizontalScrollBarMode = msg.arg1;
7220                    mVerticalScrollBarMode = msg.arg2;
7221                    break;
7222
7223                case SELECTION_STRING_CHANGED:
7224                    if (mAccessibilityInjector != null) {
7225                        String selectionString = (String) msg.obj;
7226                        mAccessibilityInjector.onSelectionStringChange(selectionString);
7227                    }
7228                    break;
7229
7230                case SET_TOUCH_HIGHLIGHT_RECTS:
7231                    invalidate(mTouchHighlightRegion.getBounds());
7232                    mTouchHighlightRegion.setEmpty();
7233                    if (msg.obj != null) {
7234                        ArrayList<Rect> rects = (ArrayList<Rect>) msg.obj;
7235                        for (Rect rect : rects) {
7236                            Rect viewRect = contentToViewRect(rect);
7237                            // some sites, like stories in nytimes.com, set
7238                            // mouse event handler in the top div. It is not
7239                            // user friendly to highlight the div if it covers
7240                            // more than half of the screen.
7241                            if (viewRect.width() < getWidth() >> 1
7242                                    || viewRect.height() < getHeight() >> 1) {
7243                                mTouchHighlightRegion.union(viewRect);
7244                                invalidate(viewRect);
7245                            } else {
7246                                Log.w(LOGTAG, "Skip the huge selection rect:"
7247                                        + viewRect);
7248                            }
7249                        }
7250                    }
7251                    break;
7252
7253                case SAVE_WEBARCHIVE_FINISHED:
7254                    SaveWebArchiveMessage saveMessage = (SaveWebArchiveMessage)msg.obj;
7255                    if (saveMessage.mCallback != null) {
7256                        saveMessage.mCallback.onReceiveValue(saveMessage.mResultFile);
7257                    }
7258                    break;
7259
7260                case SET_AUTOFILLABLE:
7261                    mAutoFillData = (WebViewCore.AutoFillData) msg.obj;
7262                    if (mWebTextView != null) {
7263                        mWebTextView.setAutoFillable(mAutoFillData.getQueryId());
7264                        rebuildWebTextView();
7265                    }
7266                    break;
7267
7268                case AUTOFILL_COMPLETE:
7269                    if (mWebTextView != null) {
7270                        // Clear the WebTextView adapter when AutoFill finishes
7271                        // so that the drop down gets cleared.
7272                        mWebTextView.setAdapterCustom(null);
7273                    }
7274                    break;
7275
7276                default:
7277                    super.handleMessage(msg);
7278                    break;
7279            }
7280        }
7281    }
7282
7283    /**
7284     * Used when receiving messages for REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID
7285     * and UPDATE_TEXT_SELECTION_MSG_ID.  Update the selection of WebTextView.
7286     */
7287    private void updateTextSelectionFromMessage(int nodePointer,
7288            int textGeneration, WebViewCore.TextSelectionData data) {
7289        if (inEditingMode()
7290                && mWebTextView.isSameTextField(nodePointer)
7291                && textGeneration == mTextGeneration) {
7292            mWebTextView.setSelectionFromWebKit(data.mStart, data.mEnd);
7293        }
7294    }
7295
7296    // Class used to use a dropdown for a <select> element
7297    private class InvokeListBox implements Runnable {
7298        // Whether the listbox allows multiple selection.
7299        private boolean     mMultiple;
7300        // Passed in to a list with multiple selection to tell
7301        // which items are selected.
7302        private int[]       mSelectedArray;
7303        // Passed in to a list with single selection to tell
7304        // where the initial selection is.
7305        private int         mSelection;
7306
7307        private Container[] mContainers;
7308
7309        // Need these to provide stable ids to my ArrayAdapter,
7310        // which normally does not have stable ids. (Bug 1250098)
7311        private class Container extends Object {
7312            /**
7313             * Possible values for mEnabled.  Keep in sync with OptionStatus in
7314             * WebViewCore.cpp
7315             */
7316            final static int OPTGROUP = -1;
7317            final static int OPTION_DISABLED = 0;
7318            final static int OPTION_ENABLED = 1;
7319
7320            String  mString;
7321            int     mEnabled;
7322            int     mId;
7323
7324            public String toString() {
7325                return mString;
7326            }
7327        }
7328
7329        /**
7330         *  Subclass ArrayAdapter so we can disable OptionGroupLabels,
7331         *  and allow filtering.
7332         */
7333        private class MyArrayListAdapter extends ArrayAdapter<Container> {
7334            public MyArrayListAdapter(Context context, Container[] objects, boolean multiple) {
7335                super(context,
7336                            multiple ? com.android.internal.R.layout.select_dialog_multichoice :
7337                            com.android.internal.R.layout.select_dialog_singlechoice,
7338                            objects);
7339            }
7340
7341            @Override
7342            public View getView(int position, View convertView,
7343                    ViewGroup parent) {
7344                // Always pass in null so that we will get a new CheckedTextView
7345                // Otherwise, an item which was previously used as an <optgroup>
7346                // element (i.e. has no check), could get used as an <option>
7347                // element, which needs a checkbox/radio, but it would not have
7348                // one.
7349                convertView = super.getView(position, null, parent);
7350                Container c = item(position);
7351                if (c != null && Container.OPTION_ENABLED != c.mEnabled) {
7352                    // ListView does not draw dividers between disabled and
7353                    // enabled elements.  Use a LinearLayout to provide dividers
7354                    LinearLayout layout = new LinearLayout(mContext);
7355                    layout.setOrientation(LinearLayout.VERTICAL);
7356                    if (position > 0) {
7357                        View dividerTop = new View(mContext);
7358                        dividerTop.setBackgroundResource(
7359                                android.R.drawable.divider_horizontal_bright);
7360                        layout.addView(dividerTop);
7361                    }
7362
7363                    if (Container.OPTGROUP == c.mEnabled) {
7364                        // Currently select_dialog_multichoice and
7365                        // select_dialog_singlechoice are CheckedTextViews.  If
7366                        // that changes, the class cast will no longer be valid.
7367                        Assert.assertTrue(
7368                                convertView instanceof CheckedTextView);
7369                        ((CheckedTextView) convertView).setCheckMarkDrawable(
7370                                null);
7371                    } else {
7372                        // c.mEnabled == Container.OPTION_DISABLED
7373                        // Draw the disabled element in a disabled state.
7374                        convertView.setEnabled(false);
7375                    }
7376
7377                    layout.addView(convertView);
7378                    if (position < getCount() - 1) {
7379                        View dividerBottom = new View(mContext);
7380                        dividerBottom.setBackgroundResource(
7381                                android.R.drawable.divider_horizontal_bright);
7382                        layout.addView(dividerBottom);
7383                    }
7384                    return layout;
7385                }
7386                return convertView;
7387            }
7388
7389            @Override
7390            public boolean hasStableIds() {
7391                // AdapterView's onChanged method uses this to determine whether
7392                // to restore the old state.  Return false so that the old (out
7393                // of date) state does not replace the new, valid state.
7394                return false;
7395            }
7396
7397            private Container item(int position) {
7398                if (position < 0 || position >= getCount()) {
7399                    return null;
7400                }
7401                return (Container) getItem(position);
7402            }
7403
7404            @Override
7405            public long getItemId(int position) {
7406                Container item = item(position);
7407                if (item == null) {
7408                    return -1;
7409                }
7410                return item.mId;
7411            }
7412
7413            @Override
7414            public boolean areAllItemsEnabled() {
7415                return false;
7416            }
7417
7418            @Override
7419            public boolean isEnabled(int position) {
7420                Container item = item(position);
7421                if (item == null) {
7422                    return false;
7423                }
7424                return Container.OPTION_ENABLED == item.mEnabled;
7425            }
7426        }
7427
7428        private InvokeListBox(String[] array, int[] enabled, int[] selected) {
7429            mMultiple = true;
7430            mSelectedArray = selected;
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        private InvokeListBox(String[] array, int[] enabled, int selection) {
7443            mSelection = selection;
7444            mMultiple = false;
7445
7446            int length = array.length;
7447            mContainers = new Container[length];
7448            for (int i = 0; i < length; i++) {
7449                mContainers[i] = new Container();
7450                mContainers[i].mString = array[i];
7451                mContainers[i].mEnabled = enabled[i];
7452                mContainers[i].mId = i;
7453            }
7454        }
7455
7456        /*
7457         * Whenever the data set changes due to filtering, this class ensures
7458         * that the checked item remains checked.
7459         */
7460        private class SingleDataSetObserver extends DataSetObserver {
7461            private long        mCheckedId;
7462            private ListView    mListView;
7463            private Adapter     mAdapter;
7464
7465            /*
7466             * Create a new observer.
7467             * @param id The ID of the item to keep checked.
7468             * @param l ListView for getting and clearing the checked states
7469             * @param a Adapter for getting the IDs
7470             */
7471            public SingleDataSetObserver(long id, ListView l, Adapter a) {
7472                mCheckedId = id;
7473                mListView = l;
7474                mAdapter = a;
7475            }
7476
7477            public void onChanged() {
7478                // The filter may have changed which item is checked.  Find the
7479                // item that the ListView thinks is checked.
7480                int position = mListView.getCheckedItemPosition();
7481                long id = mAdapter.getItemId(position);
7482                if (mCheckedId != id) {
7483                    // Clear the ListView's idea of the checked item, since
7484                    // it is incorrect
7485                    mListView.clearChoices();
7486                    // Search for mCheckedId.  If it is in the filtered list,
7487                    // mark it as checked
7488                    int count = mAdapter.getCount();
7489                    for (int i = 0; i < count; i++) {
7490                        if (mAdapter.getItemId(i) == mCheckedId) {
7491                            mListView.setItemChecked(i, true);
7492                            break;
7493                        }
7494                    }
7495                }
7496            }
7497
7498            public void onInvalidate() {}
7499        }
7500
7501        public void run() {
7502            final ListView listView = (ListView) LayoutInflater.from(mContext)
7503                    .inflate(com.android.internal.R.layout.select_dialog, null);
7504            final MyArrayListAdapter adapter = new
7505                    MyArrayListAdapter(mContext, mContainers, mMultiple);
7506            AlertDialog.Builder b = new AlertDialog.Builder(mContext)
7507                    .setView(listView).setCancelable(true)
7508                    .setInverseBackgroundForced(true);
7509
7510            if (mMultiple) {
7511                b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
7512                    public void onClick(DialogInterface dialog, int which) {
7513                        mWebViewCore.sendMessage(
7514                                EventHub.LISTBOX_CHOICES,
7515                                adapter.getCount(), 0,
7516                                listView.getCheckedItemPositions());
7517                    }});
7518                b.setNegativeButton(android.R.string.cancel,
7519                        new DialogInterface.OnClickListener() {
7520                    public void onClick(DialogInterface dialog, int which) {
7521                        mWebViewCore.sendMessage(
7522                                EventHub.SINGLE_LISTBOX_CHOICE, -2, 0);
7523                }});
7524            }
7525            mListBoxDialog = b.create();
7526            listView.setAdapter(adapter);
7527            listView.setFocusableInTouchMode(true);
7528            // There is a bug (1250103) where the checks in a ListView with
7529            // multiple items selected are associated with the positions, not
7530            // the ids, so the items do not properly retain their checks when
7531            // filtered.  Do not allow filtering on multiple lists until
7532            // that bug is fixed.
7533
7534            listView.setTextFilterEnabled(!mMultiple);
7535            if (mMultiple) {
7536                listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
7537                int length = mSelectedArray.length;
7538                for (int i = 0; i < length; i++) {
7539                    listView.setItemChecked(mSelectedArray[i], true);
7540                }
7541            } else {
7542                listView.setOnItemClickListener(new OnItemClickListener() {
7543                    public void onItemClick(AdapterView parent, View v,
7544                            int position, long id) {
7545                        // Rather than sending the message right away, send it
7546                        // after the page regains focus.
7547                        mListBoxMessage = Message.obtain(null,
7548                                EventHub.SINGLE_LISTBOX_CHOICE, (int) id, 0);
7549                        mListBoxDialog.dismiss();
7550                        mListBoxDialog = null;
7551                    }
7552                });
7553                if (mSelection != -1) {
7554                    listView.setSelection(mSelection);
7555                    listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
7556                    listView.setItemChecked(mSelection, true);
7557                    DataSetObserver observer = new SingleDataSetObserver(
7558                            adapter.getItemId(mSelection), listView, adapter);
7559                    adapter.registerDataSetObserver(observer);
7560                }
7561            }
7562            mListBoxDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
7563                public void onCancel(DialogInterface dialog) {
7564                    mWebViewCore.sendMessage(
7565                                EventHub.SINGLE_LISTBOX_CHOICE, -2, 0);
7566                    mListBoxDialog = null;
7567                }
7568            });
7569            mListBoxDialog.show();
7570        }
7571    }
7572
7573    private Message mListBoxMessage;
7574
7575    /*
7576     * Request a dropdown menu for a listbox with multiple selection.
7577     *
7578     * @param array Labels for the listbox.
7579     * @param enabledArray  State for each element in the list.  See static
7580     *      integers in Container class.
7581     * @param selectedArray Which positions are initally selected.
7582     */
7583    void requestListBox(String[] array, int[] enabledArray, int[]
7584            selectedArray) {
7585        mPrivateHandler.post(
7586                new InvokeListBox(array, enabledArray, selectedArray));
7587    }
7588
7589    /*
7590     * Request a dropdown menu for a listbox with single selection or a single
7591     * <select> element.
7592     *
7593     * @param array Labels for the listbox.
7594     * @param enabledArray  State for each element in the list.  See static
7595     *      integers in Container class.
7596     * @param selection Which position is initally selected.
7597     */
7598    void requestListBox(String[] array, int[] enabledArray, int selection) {
7599        mPrivateHandler.post(
7600                new InvokeListBox(array, enabledArray, selection));
7601    }
7602
7603    // called by JNI
7604    private void sendMoveFocus(int frame, int node) {
7605        mWebViewCore.sendMessage(EventHub.SET_MOVE_FOCUS,
7606                new WebViewCore.CursorData(frame, node, 0, 0));
7607    }
7608
7609    // called by JNI
7610    private void sendMoveMouse(int frame, int node, int x, int y) {
7611        mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE,
7612                new WebViewCore.CursorData(frame, node, x, y));
7613    }
7614
7615    /*
7616     * Send a mouse move event to the webcore thread.
7617     *
7618     * @param removeFocus Pass true if the "mouse" cursor is now over a node
7619     *                    which wants key events, but it is not the focus. This
7620     *                    will make the visual appear as though nothing is in
7621     *                    focus.  Remove the WebTextView, if present, and stop
7622     *                    drawing the blinking caret.
7623     * called by JNI
7624     */
7625    private void sendMoveMouseIfLatest(boolean removeFocus) {
7626        if (removeFocus) {
7627            clearTextEntry();
7628        }
7629        mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE_IF_LATEST,
7630                cursorData());
7631    }
7632
7633    // called by JNI
7634    private void sendMotionUp(int touchGeneration,
7635            int frame, int node, int x, int y) {
7636        WebViewCore.TouchUpData touchUpData = new WebViewCore.TouchUpData();
7637        touchUpData.mMoveGeneration = touchGeneration;
7638        touchUpData.mFrame = frame;
7639        touchUpData.mNode = node;
7640        touchUpData.mX = x;
7641        touchUpData.mY = y;
7642        mWebViewCore.sendMessage(EventHub.TOUCH_UP, touchUpData);
7643    }
7644
7645
7646    private int getScaledMaxXScroll() {
7647        int width;
7648        if (mHeightCanMeasure == false) {
7649            width = getViewWidth() / 4;
7650        } else {
7651            Rect visRect = new Rect();
7652            calcOurVisibleRect(visRect);
7653            width = visRect.width() / 2;
7654        }
7655        // FIXME the divisor should be retrieved from somewhere
7656        return viewToContentX(width);
7657    }
7658
7659    private int getScaledMaxYScroll() {
7660        int height;
7661        if (mHeightCanMeasure == false) {
7662            height = getViewHeight() / 4;
7663        } else {
7664            Rect visRect = new Rect();
7665            calcOurVisibleRect(visRect);
7666            height = visRect.height() / 2;
7667        }
7668        // FIXME the divisor should be retrieved from somewhere
7669        // the closest thing today is hard-coded into ScrollView.java
7670        // (from ScrollView.java, line 363)   int maxJump = height/2;
7671        return Math.round(height * mZoomManager.getInvScale());
7672    }
7673
7674    /**
7675     * Called by JNI to invalidate view
7676     */
7677    private void viewInvalidate() {
7678        invalidate();
7679    }
7680
7681    /**
7682     * Pass the key directly to the page.  This assumes that
7683     * nativePageShouldHandleShiftAndArrows() returned true.
7684     */
7685    private void letPageHandleNavKey(int keyCode, long time, boolean down, int metaState) {
7686        int keyEventAction;
7687        int eventHubAction;
7688        if (down) {
7689            keyEventAction = KeyEvent.ACTION_DOWN;
7690            eventHubAction = EventHub.KEY_DOWN;
7691            playSoundEffect(keyCodeToSoundsEffect(keyCode));
7692        } else {
7693            keyEventAction = KeyEvent.ACTION_UP;
7694            eventHubAction = EventHub.KEY_UP;
7695        }
7696
7697        KeyEvent event = new KeyEvent(time, time, keyEventAction, keyCode,
7698                1, (metaState & KeyEvent.META_SHIFT_ON)
7699                | (metaState & KeyEvent.META_ALT_ON)
7700                | (metaState & KeyEvent.META_SYM_ON)
7701                , KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0);
7702        mWebViewCore.sendMessage(eventHubAction, event);
7703    }
7704
7705    // return true if the key was handled
7706    private boolean navHandledKey(int keyCode, int count, boolean noScroll,
7707            long time) {
7708        if (mNativeClass == 0) {
7709            return false;
7710        }
7711        mInitialHitTestResult = null;
7712        mLastCursorTime = time;
7713        mLastCursorBounds = nativeGetCursorRingBounds();
7714        boolean keyHandled
7715                = nativeMoveCursor(keyCode, count, noScroll) == false;
7716        if (DebugFlags.WEB_VIEW) {
7717            Log.v(LOGTAG, "navHandledKey mLastCursorBounds=" + mLastCursorBounds
7718                    + " mLastCursorTime=" + mLastCursorTime
7719                    + " handled=" + keyHandled);
7720        }
7721        if (keyHandled == false || mHeightCanMeasure == false) {
7722            return keyHandled;
7723        }
7724        Rect contentCursorRingBounds = nativeGetCursorRingBounds();
7725        if (contentCursorRingBounds.isEmpty()) return keyHandled;
7726        Rect viewCursorRingBounds = contentToViewRect(contentCursorRingBounds);
7727        Rect visRect = new Rect();
7728        calcOurVisibleRect(visRect);
7729        Rect outset = new Rect(visRect);
7730        int maxXScroll = visRect.width() / 2;
7731        int maxYScroll = visRect.height() / 2;
7732        outset.inset(-maxXScroll, -maxYScroll);
7733        if (Rect.intersects(outset, viewCursorRingBounds) == false) {
7734            return keyHandled;
7735        }
7736        // FIXME: Necessary because ScrollView/ListView do not scroll left/right
7737        int maxH = Math.min(viewCursorRingBounds.right - visRect.right,
7738                maxXScroll);
7739        if (maxH > 0) {
7740            pinScrollBy(maxH, 0, true, 0);
7741        } else {
7742            maxH = Math.max(viewCursorRingBounds.left - visRect.left,
7743                    -maxXScroll);
7744            if (maxH < 0) {
7745                pinScrollBy(maxH, 0, true, 0);
7746            }
7747        }
7748        if (mLastCursorBounds.isEmpty()) return keyHandled;
7749        if (mLastCursorBounds.equals(contentCursorRingBounds)) {
7750            return keyHandled;
7751        }
7752        if (DebugFlags.WEB_VIEW) {
7753            Log.v(LOGTAG, "navHandledKey contentCursorRingBounds="
7754                    + contentCursorRingBounds);
7755        }
7756        requestRectangleOnScreen(viewCursorRingBounds);
7757        mUserScroll = true;
7758        return keyHandled;
7759    }
7760
7761    /**
7762     * @return If the page should receive Shift and arrows.
7763     */
7764    private boolean pageShouldHandleShiftAndArrows() {
7765        // TODO: Maybe the injected script should announce its presence in
7766        // the page meta-tag so the nativePageShouldHandleShiftAndArrows
7767        // will check that as one of the conditions it looks for
7768        return (nativePageShouldHandleShiftAndArrows() || mAccessibilityScriptInjected);
7769    }
7770
7771    /**
7772     * Set the background color. It's white by default. Pass
7773     * zero to make the view transparent.
7774     * @param color   the ARGB color described by Color.java
7775     */
7776    public void setBackgroundColor(int color) {
7777        mBackgroundColor = color;
7778        mWebViewCore.sendMessage(EventHub.SET_BACKGROUND_COLOR, color);
7779    }
7780
7781    public void debugDump() {
7782        nativeDebugDump();
7783        mWebViewCore.sendMessage(EventHub.DUMP_NAVTREE);
7784    }
7785
7786    /**
7787     * Draw the HTML page into the specified canvas. This call ignores any
7788     * view-specific zoom, scroll offset, or other changes. It does not draw
7789     * any view-specific chrome, such as progress or URL bars.
7790     *
7791     * @hide only needs to be accessible to Browser and testing
7792     */
7793    public void drawPage(Canvas canvas) {
7794        nativeDraw(canvas, 0, 0, false);
7795    }
7796
7797    /**
7798     * Set the time to wait between passing touches to WebCore. See also the
7799     * TOUCH_SENT_INTERVAL member for further discussion.
7800     *
7801     * @hide This is only used by the DRT test application.
7802     */
7803    public void setTouchInterval(int interval) {
7804        mCurrentTouchInterval = interval;
7805    }
7806
7807    /**
7808     * Toggle whether multi touch events should be sent to webkit
7809     * no matter if UI wants to handle it first.
7810     *
7811     * @hide This is only used by the webkit layout test.
7812     */
7813    public void setDeferMultiTouch(boolean value) {
7814        mDeferMultitouch = value;
7815        Log.v(LOGTAG, "set mDeferMultitouch to " + value);
7816    }
7817
7818    /**
7819     *  Update our cache with updatedText.
7820     *  @param updatedText  The new text to put in our cache.
7821     */
7822    /* package */ void updateCachedTextfield(String updatedText) {
7823        // Also place our generation number so that when we look at the cache
7824        // we recognize that it is up to date.
7825        nativeUpdateCachedTextfield(updatedText, mTextGeneration);
7826    }
7827
7828    /*package*/ void autoFillForm(int autoFillQueryId) {
7829        mWebViewCore.sendMessage(EventHub.AUTOFILL_FORM, autoFillQueryId, /* unused */0);
7830    }
7831
7832    /* package */ ViewManager getViewManager() {
7833        return mViewManager;
7834    }
7835
7836    private native int nativeCacheHitFramePointer();
7837    private native Rect nativeCacheHitNodeBounds();
7838    private native int nativeCacheHitNodePointer();
7839    /* package */ native void nativeClearCursor();
7840    private native void     nativeCreate(int ptr);
7841    private native int      nativeCursorFramePointer();
7842    private native Rect     nativeCursorNodeBounds();
7843    private native int nativeCursorNodePointer();
7844    /* package */ native boolean nativeCursorMatchesFocus();
7845    private native boolean  nativeCursorIntersects(Rect visibleRect);
7846    private native boolean  nativeCursorIsAnchor();
7847    private native boolean  nativeCursorIsTextInput();
7848    private native Point    nativeCursorPosition();
7849    private native String   nativeCursorText();
7850    /**
7851     * Returns true if the native cursor node says it wants to handle key events
7852     * (ala plugins). This can only be called if mNativeClass is non-zero!
7853     */
7854    private native boolean  nativeCursorWantsKeyEvents();
7855    private native void     nativeDebugDump();
7856    private native void     nativeDestroy();
7857
7858    /**
7859     * Draw the picture set with a background color and extra. If
7860     * "splitIfNeeded" is true and the return value is not 0, the return value
7861     * MUST be passed to WebViewCore with SPLIT_PICTURE_SET message so that the
7862     * native allocation can be freed.
7863     */
7864    private native int nativeDraw(Canvas canvas, int color, int extra,
7865            boolean splitIfNeeded);
7866    private native void     nativeDumpDisplayTree(String urlOrNull);
7867    private native boolean  nativeEvaluateLayersAnimations();
7868    private native boolean  nativeDrawGL(Rect rect, float scale, int extras);
7869    private native void     nativeExtendSelection(int x, int y);
7870    private native int      nativeFindAll(String findLower, String findUpper,
7871            boolean sameAsLastSearch);
7872    private native void     nativeFindNext(boolean forward);
7873    /* package */ native int      nativeFocusCandidateFramePointer();
7874    /* package */ native boolean  nativeFocusCandidateHasNextTextfield();
7875    /* package */ native boolean  nativeFocusCandidateIsPassword();
7876    private native boolean  nativeFocusCandidateIsRtlText();
7877    private native boolean  nativeFocusCandidateIsTextInput();
7878    /* package */ native int      nativeFocusCandidateMaxLength();
7879    /* package */ native String   nativeFocusCandidateName();
7880    private native Rect     nativeFocusCandidateNodeBounds();
7881    /**
7882     * @return A Rect with left, top, right, bottom set to the corresponding
7883     * padding values in the focus candidate, if it is a textfield/textarea with
7884     * a style.  Otherwise return null.  This is not actually a rectangle; Rect
7885     * is being used to pass four integers.
7886     */
7887    private native Rect     nativeFocusCandidatePaddingRect();
7888    /* package */ native int      nativeFocusCandidatePointer();
7889    private native String   nativeFocusCandidateText();
7890    /* package */ native float    nativeFocusCandidateTextSize();
7891    /* package */ native int nativeFocusCandidateLineHeight();
7892    /**
7893     * Returns an integer corresponding to WebView.cpp::type.
7894     * See WebTextView.setType()
7895     */
7896    private native int      nativeFocusCandidateType();
7897    private native boolean  nativeFocusIsPlugin();
7898    private native Rect     nativeFocusNodeBounds();
7899    /* package */ native int nativeFocusNodePointer();
7900    private native Rect     nativeGetCursorRingBounds();
7901    private native String   nativeGetSelection();
7902    private native boolean  nativeHasCursorNode();
7903    private native boolean  nativeHasFocusNode();
7904    private native void     nativeHideCursor();
7905    private native boolean  nativeHitSelection(int x, int y);
7906    private native String   nativeImageURI(int x, int y);
7907    private native void     nativeInstrumentReport();
7908    private native Rect     nativeLayerBounds(int layer);
7909    /* package */ native boolean nativeMoveCursorToNextTextInput();
7910    // return true if the page has been scrolled
7911    private native boolean  nativeMotionUp(int x, int y, int slop);
7912    // returns false if it handled the key
7913    private native boolean  nativeMoveCursor(int keyCode, int count,
7914            boolean noScroll);
7915    private native int      nativeMoveGeneration();
7916    private native void     nativeMoveSelection(int x, int y);
7917    /**
7918     * @return true if the page should get the shift and arrow keys, rather
7919     * than select text/navigation.
7920     *
7921     * If the focus is a plugin, or if the focus and cursor match and are
7922     * a contentEditable element, then the page should handle these keys.
7923     */
7924    private native boolean  nativePageShouldHandleShiftAndArrows();
7925    private native boolean  nativePointInNavCache(int x, int y, int slop);
7926    // Like many other of our native methods, you must make sure that
7927    // mNativeClass is not null before calling this method.
7928    private native void     nativeRecordButtons(boolean focused,
7929            boolean pressed, boolean invalidate);
7930    private native void     nativeResetSelection();
7931    private native void     nativeSelectAll();
7932    private native void     nativeSelectBestAt(Rect rect);
7933    private native int      nativeSelectionX();
7934    private native int      nativeSelectionY();
7935    private native int      nativeFindIndex();
7936    private native void     nativeSetExtendSelection();
7937    private native void     nativeSetFindIsEmpty();
7938    private native void     nativeSetFindIsUp(boolean isUp);
7939    private native void     nativeSetHeightCanMeasure(boolean measure);
7940    private native void     nativeSetBaseLayer(int layer, Rect invalRect);
7941    private native void     nativeShowCursorTimed();
7942    private native void     nativeReplaceBaseContent(int content);
7943    private native void     nativeCopyBaseContentToPicture(Picture pict);
7944    private native boolean  nativeHasContent();
7945    private native void     nativeSetSelectionPointer(boolean set,
7946            float scale, int x, int y);
7947    private native boolean  nativeStartSelection(int x, int y);
7948    private native Rect     nativeSubtractLayers(Rect content);
7949    private native int      nativeTextGeneration();
7950    // Never call this version except by updateCachedTextfield(String) -
7951    // we always want to pass in our generation number.
7952    private native void     nativeUpdateCachedTextfield(String updatedText,
7953            int generation);
7954    private native boolean  nativeWordSelection(int x, int y);
7955    // return NO_LEFTEDGE means failure.
7956    static final int NO_LEFTEDGE = -1;
7957    native int nativeGetBlockLeftEdge(int x, int y, float scale);
7958
7959    // Returns a pointer to the scrollable LayerAndroid at the given point.
7960    private native int      nativeScrollableLayer(int x, int y, Rect scrollRect);
7961    private native boolean  nativeScrollLayer(int layer, int dx, int dy);
7962}
7963