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