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