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