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