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