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