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