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