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