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