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