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