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