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