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