WebView.java revision 3ccd3655a09633794f4d815ff85f35fa986a10d4
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.app.AlertDialog;
20import android.content.Context;
21import android.content.DialogInterface;
22import android.content.Intent;
23import android.content.DialogInterface.OnCancelListener;
24import android.database.DataSetObserver;
25import android.graphics.Bitmap;
26import android.graphics.Canvas;
27import android.graphics.Color;
28import android.graphics.Paint;
29import android.graphics.Path;
30import android.graphics.Picture;
31import android.graphics.Point;
32import android.graphics.Rect;
33import android.graphics.Region;
34import android.net.http.SslCertificate;
35import android.net.Uri;
36import android.os.Bundle;
37import android.os.Handler;
38import android.os.Message;
39import android.os.ServiceManager;
40import android.os.SystemClock;
41import android.provider.Checkin;
42import android.text.IClipboard;
43import android.text.Selection;
44import android.text.Spannable;
45import android.util.AttributeSet;
46import android.util.EventLog;
47import android.util.Log;
48import android.view.Gravity;
49import android.view.KeyEvent;
50import android.view.LayoutInflater;
51import android.view.MotionEvent;
52import android.view.SoundEffectConstants;
53import android.view.VelocityTracker;
54import android.view.View;
55import android.view.ViewConfiguration;
56import android.view.ViewGroup;
57import android.view.ViewParent;
58import android.view.ViewTreeObserver;
59import android.view.animation.AlphaAnimation;
60import android.view.inputmethod.InputMethodManager;
61import android.webkit.WebTextView.AutoCompleteAdapter;
62import android.webkit.WebViewCore.EventHub;
63import android.widget.AbsoluteLayout;
64import android.widget.Adapter;
65import android.widget.AdapterView;
66import android.widget.ArrayAdapter;
67import android.widget.FrameLayout;
68import android.widget.ImageView;
69import android.widget.ListView;
70import android.widget.Scroller;
71import android.widget.Toast;
72import android.widget.ZoomButtonsController;
73import android.widget.ZoomControls;
74import android.widget.AdapterView.OnItemClickListener;
75
76import java.io.File;
77import java.io.FileInputStream;
78import java.io.FileNotFoundException;
79import java.io.FileOutputStream;
80import java.io.IOException;
81import java.net.URLDecoder;
82import java.util.ArrayList;
83import java.util.List;
84
85/**
86 * <p>A View that displays web pages. This class is the basis upon which you
87 * can roll your own web browser or simply display some online content within your Activity.
88 * It uses the WebKit rendering engine to display
89 * web pages and includes methods to navigate forward and backward
90 * through a history, zoom in and out, perform text searches and more.</p>
91 * <p>To enable the built-in zoom, set
92 * {@link #getSettings() WebSettings}.{@link WebSettings#setBuiltInZoomControls(boolean)}
93 * (introduced in API version 3).
94 * <p>Note that, in order for your Activity to access the Internet and load web pages
95 * in a WebView, you must add the <var>INTERNET</var> permissions to your
96 * Android Manifest file:</p>
97 * <pre>&lt;uses-permission android:name="android.permission.INTERNET" /></pre>
98 *
99 * <p>This must be a child of the <code>&lt;manifest></code> element.</p>
100 *
101 * <h3>Basic usage</h3>
102 *
103 * <p>By default, a WebView provides no browser-like widgets, does not
104 * enable JavaScript and errors will be ignored. If your goal is only
105 * to display some HTML as a part of your UI, this is probably fine;
106 * the user won't need to interact with the web page beyond reading
107 * it, and the web page won't need to interact with the user. If you
108 * actually want a fully blown web browser, then you probably want to
109 * invoke the Browser application with your URL rather than show it
110 * with a WebView. See {@link android.content.Intent} for more information.</p>
111 *
112 * <pre class="prettyprint">
113 * WebView webview = new WebView(this);
114 * setContentView(webview);
115 *
116 * // Simplest usage: note that an exception will NOT be thrown
117 * // if there is an error loading this page (see below).
118 * webview.loadUrl("http://slashdot.org/");
119 *
120 * // Of course you can also load from any string:
121 * String summary = "&lt;html>&lt;body>You scored &lt;b>192</b> points.&lt;/body>&lt;/html>";
122 * webview.loadData(summary, "text/html", "utf-8");
123 * // ... although note that there are restrictions on what this HTML can do.
124 * // See the JavaDocs for loadData and loadDataWithBaseUrl for more info.
125 * </pre>
126 *
127 * <p>A WebView has several customization points where you can add your
128 * own behavior. These are:</p>
129 *
130 * <ul>
131 *   <li>Creating and setting a {@link android.webkit.WebChromeClient} subclass.
132 *       This class is called when something that might impact a
133 *       browser UI happens, for instance, progress updates and
134 *       JavaScript alerts are sent here.
135 *   </li>
136 *   <li>Creating and setting a {@link android.webkit.WebViewClient} subclass.
137 *       It will be called when things happen that impact the
138 *       rendering of the content, eg, errors or form submissions. You
139 *       can also intercept URL loading here.</li>
140 *   <li>Via the {@link android.webkit.WebSettings} class, which contains
141 *       miscellaneous configuration. </li>
142 *   <li>With the {@link android.webkit.WebView#addJavascriptInterface} method.
143 *       This lets you bind Java objects into the WebView so they can be
144 *       controlled from the web pages JavaScript.</li>
145 * </ul>
146 *
147 * <p>Here's a more complicated example, showing error handling,
148 *    settings, and progress notification:</p>
149 *
150 * <pre class="prettyprint">
151 * // Let's display the progress in the activity title bar, like the
152 * // browser app does.
153 * getWindow().requestFeature(Window.FEATURE_PROGRESS);
154 *
155 * webview.getSettings().setJavaScriptEnabled(true);
156 *
157 * final Activity activity = this;
158 * webview.setWebChromeClient(new WebChromeClient() {
159 *   public void onProgressChanged(WebView view, int progress) {
160 *     // Activities and WebViews measure progress with different scales.
161 *     // The progress meter will automatically disappear when we reach 100%
162 *     activity.setProgress(progress * 1000);
163 *   }
164 * });
165 * webview.setWebViewClient(new WebViewClient() {
166 *   public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
167 *     Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
168 *   }
169 * });
170 *
171 * webview.loadUrl("http://slashdot.org/");
172 * </pre>
173 *
174 * <h3>Cookie and window management</h3>
175 *
176 * <p>For obvious security reasons, your application has its own
177 * cache, cookie store etc - it does not share the Browser
178 * applications data. Cookies are managed on a separate thread, so
179 * operations like index building don't block the UI
180 * thread. Follow the instructions in {@link android.webkit.CookieSyncManager}
181 * if you want to use cookies in your application.
182 * </p>
183 *
184 * <p>By default, requests by the HTML to open new windows are
185 * ignored. This is true whether they be opened by JavaScript or by
186 * the target attribute on a link. You can customize your
187 * WebChromeClient to provide your own behaviour for opening multiple windows,
188 * and render them in whatever manner you want.</p>
189 *
190 * <p>Standard behavior for an Activity is to be destroyed and
191 * recreated when the devices orientation is changed. This will cause
192 * the WebView to reload the current page. If you don't want that, you
193 * can set your Activity to handle the orientation and keyboardHidden
194 * changes, and then just leave the WebView alone. It'll automatically
195 * re-orient itself as appropriate.</p>
196 */
197public class WebView extends AbsoluteLayout
198        implements ViewTreeObserver.OnGlobalFocusChangeListener,
199        ViewGroup.OnHierarchyChangeListener {
200
201    // if AUTO_REDRAW_HACK is true, then the CALL key will toggle redrawing
202    // the screen all-the-time. Good for profiling our drawing code
203    static private final boolean AUTO_REDRAW_HACK = false;
204    // true means redraw the screen all-the-time. Only with AUTO_REDRAW_HACK
205    private boolean mAutoRedraw;
206
207    static final String LOGTAG = "webview";
208
209    static class ScaleLimitData {
210        int mMinScale;
211        int mMaxScale;
212    }
213
214    private static class ExtendedZoomControls extends FrameLayout {
215        public ExtendedZoomControls(Context context, AttributeSet attrs) {
216            super(context, attrs);
217            LayoutInflater inflater = (LayoutInflater)
218                    context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
219            inflater.inflate(com.android.internal.R.layout.zoom_magnify, this, true);
220            mPlusMinusZoomControls = (ZoomControls) findViewById(
221                    com.android.internal.R.id.zoomControls);
222            mZoomMagnify = (ImageView) findViewById(com.android.internal.R.id.zoomMagnify);
223        }
224
225        public void show(boolean showZoom, boolean canZoomOut) {
226            mPlusMinusZoomControls.setVisibility(
227                    showZoom ? View.VISIBLE : View.GONE);
228            mZoomMagnify.setVisibility(canZoomOut ? View.VISIBLE : View.GONE);
229            fade(View.VISIBLE, 0.0f, 1.0f);
230        }
231
232        public void hide() {
233            fade(View.GONE, 1.0f, 0.0f);
234        }
235
236        private void fade(int visibility, float startAlpha, float endAlpha) {
237            AlphaAnimation anim = new AlphaAnimation(startAlpha, endAlpha);
238            anim.setDuration(500);
239            startAnimation(anim);
240            setVisibility(visibility);
241        }
242
243        public void setIsZoomMagnifyEnabled(boolean isEnabled) {
244            mZoomMagnify.setEnabled(isEnabled);
245        }
246
247        public boolean hasFocus() {
248            return mPlusMinusZoomControls.hasFocus() || mZoomMagnify.hasFocus();
249        }
250
251        public void setOnZoomInClickListener(OnClickListener listener) {
252            mPlusMinusZoomControls.setOnZoomInClickListener(listener);
253        }
254
255        public void setOnZoomOutClickListener(OnClickListener listener) {
256            mPlusMinusZoomControls.setOnZoomOutClickListener(listener);
257        }
258
259        public void setOnZoomMagnifyClickListener(OnClickListener listener) {
260            mZoomMagnify.setOnClickListener(listener);
261        }
262
263        ZoomControls    mPlusMinusZoomControls;
264        ImageView       mZoomMagnify;
265    }
266
267    /**
268     *  Transportation object for returning WebView across thread boundaries.
269     */
270    public class WebViewTransport {
271        private WebView mWebview;
272
273        /**
274         * Set the WebView to the transportation object.
275         * @param webview The WebView to transport.
276         */
277        public synchronized void setWebView(WebView webview) {
278            mWebview = webview;
279        }
280
281        /**
282         * Return the WebView object.
283         * @return WebView The transported WebView object.
284         */
285        public synchronized WebView getWebView() {
286            return mWebview;
287        }
288    }
289
290    // A final CallbackProxy shared by WebViewCore and BrowserFrame.
291    private final CallbackProxy mCallbackProxy;
292
293    private final WebViewDatabase mDatabase;
294
295    // SSL certificate for the main top-level page (if secure)
296    private SslCertificate mCertificate;
297
298    // Native WebView pointer that is 0 until the native object has been
299    // created.
300    private int mNativeClass;
301    // This would be final but it needs to be set to null when the WebView is
302    // destroyed.
303    private WebViewCore mWebViewCore;
304    // Handler for dispatching UI messages.
305    /* package */ final Handler mPrivateHandler = new PrivateHandler();
306    private WebTextView mWebTextView;
307    // Used to ignore changes to webkit text that arrives to the UI side after
308    // more key events.
309    private int mTextGeneration;
310
311    // The list of loaded plugins.
312    private static PluginList sPluginList;
313
314    /**
315     * Position of the last touch event.
316     */
317    private float mLastTouchX;
318    private float mLastTouchY;
319
320    /**
321     * Time of the last touch event.
322     */
323    private long mLastTouchTime;
324
325    /**
326     * Time of the last time sending touch event to WebViewCore
327     */
328    private long mLastSentTouchTime;
329
330    /**
331     * The minimum elapsed time before sending another ACTION_MOVE event to
332     * WebViewCore. This really should be tuned for each type of the devices.
333     * For example in Google Map api test case, it takes Dream device at least
334     * 150ms to do a full cycle in the WebViewCore by processing a touch event,
335     * triggering the layout and drawing the picture. While the same process
336     * takes 60+ms on the current high speed device. If we make
337     * TOUCH_SENT_INTERVAL too small, there will be multiple touch events sent
338     * to WebViewCore queue and the real layout and draw events will be pushed
339     * to further, which slows down the refresh rate. Choose 50 to favor the
340     * current high speed devices. For Dream like devices, 100 is a better
341     * choice. Maybe make this in the buildspec later.
342     */
343    private static final int TOUCH_SENT_INTERVAL = 50;
344
345    /**
346     * Helper class to get velocity for fling
347     */
348    VelocityTracker mVelocityTracker;
349
350    /**
351     * Touch mode
352     */
353    private int mTouchMode = TOUCH_DONE_MODE;
354    private static final int TOUCH_INIT_MODE = 1;
355    private static final int TOUCH_DRAG_START_MODE = 2;
356    private static final int TOUCH_DRAG_MODE = 3;
357    private static final int TOUCH_SHORTPRESS_START_MODE = 4;
358    private static final int TOUCH_SHORTPRESS_MODE = 5;
359    private static final int TOUCH_DOUBLECLICK_MODE = 6;
360    private static final int TOUCH_DONE_MODE = 7;
361    private static final int TOUCH_SELECT_MODE = 8;
362    // touch mode values specific to scale+scroll
363    private static final int FIRST_SCROLL_ZOOM = 9;
364    private static final int SCROLL_ZOOM_ANIMATION_IN = 9;
365    private static final int SCROLL_ZOOM_ANIMATION_OUT = 10;
366    private static final int SCROLL_ZOOM_OUT = 11;
367    private static final int LAST_SCROLL_ZOOM = 11;
368    // end of touch mode values specific to scale+scroll
369
370    // Whether to forward the touch events to WebCore
371    private boolean mForwardTouchEvents = false;
372
373    // Whether to prevent drag during touch. The initial value depends on
374    // mForwardTouchEvents. If WebCore wants touch events, we assume it will
375    // take control of touch events unless it says no for touch down event.
376    private boolean mPreventDrag;
377
378    // Whether or not to draw the cursor ring.
379    private boolean mDrawCursorRing = true;
380
381    // true if onPause has been called (and not onResume)
382    private boolean mIsPaused;
383
384    /**
385     * Customizable constant
386     */
387    // pre-computed square of ViewConfiguration.getScaledTouchSlop()
388    private int mTouchSlopSquare;
389    // pre-computed density adjusted navigation slop
390    private int mNavSlop;
391    // This should be ViewConfiguration.getTapTimeout()
392    // But system time out is 100ms, which is too short for the browser.
393    // In the browser, if it switches out of tap too soon, jump tap won't work.
394    private static final int TAP_TIMEOUT = 200;
395    // This should be ViewConfiguration.getLongPressTimeout()
396    // But system time out is 500ms, which is too short for the browser.
397    // With a short timeout, it's difficult to treat trigger a short press.
398    private static final int LONG_PRESS_TIMEOUT = 1000;
399    // needed to avoid flinging after a pause of no movement
400    private static final int MIN_FLING_TIME = 250;
401    // The time that the Zoom Controls are visible before fading away
402    private static final long ZOOM_CONTROLS_TIMEOUT =
403            ViewConfiguration.getZoomControlsTimeout();
404    // The amount of content to overlap between two screens when going through
405    // pages with the space bar, in pixels.
406    private static final int PAGE_SCROLL_OVERLAP = 24;
407
408    /**
409     * These prevent calling requestLayout if either dimension is fixed. This
410     * depends on the layout parameters and the measure specs.
411     */
412    boolean mWidthCanMeasure;
413    boolean mHeightCanMeasure;
414
415    // Remember the last dimensions we sent to the native side so we can avoid
416    // sending the same dimensions more than once.
417    int mLastWidthSent;
418    int mLastHeightSent;
419
420    private int mContentWidth;   // cache of value from WebViewCore
421    private int mContentHeight;  // cache of value from WebViewCore
422
423    // Need to have the separate control for horizontal and vertical scrollbar
424    // style than the View's single scrollbar style
425    private boolean mOverlayHorizontalScrollbar = true;
426    private boolean mOverlayVerticalScrollbar = false;
427
428    // our standard speed. this way small distances will be traversed in less
429    // time than large distances, but we cap the duration, so that very large
430    // distances won't take too long to get there.
431    private static final int STD_SPEED = 480;  // pixels per second
432    // time for the longest scroll animation
433    private static final int MAX_DURATION = 750;   // milliseconds
434    private Scroller mScroller;
435
436    private boolean mWrapContent;
437
438    /**
439     * Private message ids
440     */
441    private static final int REMEMBER_PASSWORD          = 1;
442    private static final int NEVER_REMEMBER_PASSWORD    = 2;
443    private static final int SWITCH_TO_SHORTPRESS       = 3;
444    private static final int SWITCH_TO_LONGPRESS        = 4;
445    private static final int REQUEST_FORM_DATA          = 6;
446    private static final int SWITCH_TO_CLICK            = 7;
447    private static final int RESUME_WEBCORE_UPDATE      = 8;
448
449    //! arg1=x, arg2=y
450    static final int SCROLL_TO_MSG_ID                   = 10;
451    static final int SCROLL_BY_MSG_ID                   = 11;
452    //! arg1=x, arg2=y
453    static final int SPAWN_SCROLL_TO_MSG_ID             = 12;
454    //! arg1=x, arg2=y
455    static final int SYNC_SCROLL_TO_MSG_ID              = 13;
456    static final int NEW_PICTURE_MSG_ID                 = 14;
457    static final int UPDATE_TEXT_ENTRY_MSG_ID           = 15;
458    static final int WEBCORE_INITIALIZED_MSG_ID         = 16;
459    static final int UPDATE_TEXTFIELD_TEXT_MSG_ID       = 17;
460    static final int DID_FIRST_LAYOUT_MSG_ID            = 18;
461    static final int MOVE_OUT_OF_PLUGIN                 = 19;
462    static final int CLEAR_TEXT_ENTRY                   = 20;
463
464    static final int UPDATE_CLIPBOARD                   = 22;
465    static final int LONG_PRESS_CENTER                  = 23;
466    static final int PREVENT_TOUCH_ID                   = 24;
467    static final int WEBCORE_NEED_TOUCH_EVENTS          = 25;
468    // obj=Rect in doc coordinates
469    static final int INVAL_RECT_MSG_ID                  = 26;
470    static final int REQUEST_KEYBOARD                   = 27;
471
472    static final String[] HandlerDebugString = {
473        "REMEMBER_PASSWORD", //              = 1;
474        "NEVER_REMEMBER_PASSWORD", //        = 2;
475        "SWITCH_TO_SHORTPRESS", //           = 3;
476        "SWITCH_TO_LONGPRESS", //            = 4;
477        "5",
478        "REQUEST_FORM_DATA", //              = 6;
479        "SWITCH_TO_CLICK", //                = 7;
480        "RESUME_WEBCORE_UPDATE", //          = 8;
481        "9",
482        "SCROLL_TO_MSG_ID", //               = 10;
483        "SCROLL_BY_MSG_ID", //               = 11;
484        "SPAWN_SCROLL_TO_MSG_ID", //         = 12;
485        "SYNC_SCROLL_TO_MSG_ID", //          = 13;
486        "NEW_PICTURE_MSG_ID", //             = 14;
487        "UPDATE_TEXT_ENTRY_MSG_ID", //       = 15;
488        "WEBCORE_INITIALIZED_MSG_ID", //     = 16;
489        "UPDATE_TEXTFIELD_TEXT_MSG_ID", //   = 17;
490        "DID_FIRST_LAYOUT_MSG_ID", //        = 18;
491        "MOVE_OUT_OF_PLUGIN", //             = 19;
492        "CLEAR_TEXT_ENTRY", //               = 20;
493        "21", //                             = 21;
494        "UPDATE_CLIPBOARD", //               = 22;
495        "LONG_PRESS_CENTER", //              = 23;
496        "PREVENT_TOUCH_ID", //               = 24;
497        "WEBCORE_NEED_TOUCH_EVENTS", //      = 25;
498        "INVAL_RECT_MSG_ID", //              = 26;
499        "REQUEST_KEYBOARD" //                = 27;
500    };
501
502    // width which view is considered to be fully zoomed out
503    static final int ZOOM_OUT_WIDTH = 1008;
504
505    // default scale limit. Depending on the display density
506    private static float DEFAULT_MAX_ZOOM_SCALE;
507    private static float DEFAULT_MIN_ZOOM_SCALE;
508    // scale limit, which can be set through viewport meta tag in the web page
509    private float mMaxZoomScale;
510    private float mMinZoomScale;
511    private boolean mMinZoomScaleFixed = false;
512
513    // initial scale in percent. 0 means using default.
514    private int mInitialScale = 0;
515
516    // default scale. Depending on the display density.
517    static int DEFAULT_SCALE_PERCENT;
518    private float mDefaultScale;
519
520    // set to true temporarily while the zoom control is being dragged
521    private boolean mPreviewZoomOnly = false;
522
523    // computed scale and inverse, from mZoomWidth.
524    private float mActualScale;
525    private float mInvActualScale;
526    // if this is non-zero, it is used on drawing rather than mActualScale
527    private float mZoomScale;
528    private float mInvInitialZoomScale;
529    private float mInvFinalZoomScale;
530    private long mZoomStart;
531    private static final int ZOOM_ANIMATION_LENGTH = 500;
532
533    private boolean mUserScroll = false;
534
535    private int mSnapScrollMode = SNAP_NONE;
536    private static final int SNAP_NONE = 1;
537    private static final int SNAP_X = 2;
538    private static final int SNAP_Y = 3;
539    private static final int SNAP_X_LOCK = 4;
540    private static final int SNAP_Y_LOCK = 5;
541    private boolean mSnapPositive;
542
543    // Used to match key downs and key ups
544    private boolean mGotKeyDown;
545
546    /* package */ static boolean mLogEvent = true;
547    private static final int EVENT_LOG_ZOOM_LEVEL_CHANGE = 70101;
548    private static final int EVENT_LOG_DOUBLE_TAP_DURATION = 70102;
549
550    // for event log
551    private long mLastTouchUpTime = 0;
552
553    /**
554     * URI scheme for telephone number
555     */
556    public static final String SCHEME_TEL = "tel:";
557    /**
558     * URI scheme for email address
559     */
560    public static final String SCHEME_MAILTO = "mailto:";
561    /**
562     * URI scheme for map address
563     */
564    public static final String SCHEME_GEO = "geo:0,0?q=";
565
566    private int mBackgroundColor = Color.WHITE;
567
568    // Used to notify listeners of a new picture.
569    private PictureListener mPictureListener;
570    /**
571     * Interface to listen for new pictures as they change.
572     */
573    public interface PictureListener {
574        /**
575         * Notify the listener that the picture has changed.
576         * @param view The WebView that owns the picture.
577         * @param picture The new picture.
578         */
579        public void onNewPicture(WebView view, Picture picture);
580    }
581
582    // FIXME: Want to make this public, but need to change the API file.
583    public /*static*/ class HitTestResult {
584        /**
585         * Default HitTestResult, where the target is unknown
586         */
587        public static final int UNKNOWN_TYPE = 0;
588        /**
589         * HitTestResult for hitting a HTML::a tag
590         */
591        public static final int ANCHOR_TYPE = 1;
592        /**
593         * HitTestResult for hitting a phone number
594         */
595        public static final int PHONE_TYPE = 2;
596        /**
597         * HitTestResult for hitting a map address
598         */
599        public static final int GEO_TYPE = 3;
600        /**
601         * HitTestResult for hitting an email address
602         */
603        public static final int EMAIL_TYPE = 4;
604        /**
605         * HitTestResult for hitting an HTML::img tag
606         */
607        public static final int IMAGE_TYPE = 5;
608        /**
609         * HitTestResult for hitting a HTML::a tag which contains HTML::img
610         */
611        public static final int IMAGE_ANCHOR_TYPE = 6;
612        /**
613         * HitTestResult for hitting a HTML::a tag with src=http
614         */
615        public static final int SRC_ANCHOR_TYPE = 7;
616        /**
617         * HitTestResult for hitting a HTML::a tag with src=http + HTML::img
618         */
619        public static final int SRC_IMAGE_ANCHOR_TYPE = 8;
620        /**
621         * HitTestResult for hitting an edit text area
622         */
623        public static final int EDIT_TEXT_TYPE = 9;
624
625        private int mType;
626        private String mExtra;
627
628        HitTestResult() {
629            mType = UNKNOWN_TYPE;
630        }
631
632        private void setType(int type) {
633            mType = type;
634        }
635
636        private void setExtra(String extra) {
637            mExtra = extra;
638        }
639
640        public int getType() {
641            return mType;
642        }
643
644        public String getExtra() {
645            return mExtra;
646        }
647    }
648
649    // The View containing the zoom controls
650    private ExtendedZoomControls mZoomControls;
651    private Runnable mZoomControlRunnable;
652
653    private ZoomButtonsController mZoomButtonsController;
654
655    // These keep track of the center point of the zoom.  They are used to
656    // determine the point around which we should zoom.
657    private float mZoomCenterX;
658    private float mZoomCenterY;
659
660    private ZoomButtonsController.OnZoomListener mZoomListener =
661            new ZoomButtonsController.OnZoomListener() {
662
663        public void onVisibilityChanged(boolean visible) {
664            if (visible) {
665                switchOutDrawHistory();
666                updateZoomButtonsEnabled();
667            }
668        }
669
670        public void onZoom(boolean zoomIn) {
671            if (zoomIn) {
672                zoomIn();
673            } else {
674                zoomOut();
675            }
676
677            updateZoomButtonsEnabled();
678        }
679    };
680
681    /**
682     * Construct a new WebView with a Context object.
683     * @param context A Context object used to access application assets.
684     */
685    public WebView(Context context) {
686        this(context, null);
687    }
688
689    /**
690     * Construct a new WebView with layout parameters.
691     * @param context A Context object used to access application assets.
692     * @param attrs An AttributeSet passed to our parent.
693     */
694    public WebView(Context context, AttributeSet attrs) {
695        this(context, attrs, com.android.internal.R.attr.webViewStyle);
696    }
697
698    /**
699     * Construct a new WebView with layout parameters and a default style.
700     * @param context A Context object used to access application assets.
701     * @param attrs An AttributeSet passed to our parent.
702     * @param defStyle The default style resource ID.
703     */
704    public WebView(Context context, AttributeSet attrs, int defStyle) {
705        super(context, attrs, defStyle);
706        init();
707
708        mCallbackProxy = new CallbackProxy(context, this);
709        mWebViewCore = new WebViewCore(context, this, mCallbackProxy);
710        mDatabase = WebViewDatabase.getInstance(context);
711        mScroller = new Scroller(context);
712
713        mZoomButtonsController = new ZoomButtonsController(this);
714        mZoomButtonsController.setOnZoomListener(mZoomListener);
715        // ZoomButtonsController positions the buttons at the bottom, but in
716        // the middle.  Change their layout parameters so they appear on the
717        // right.
718        View controls = mZoomButtonsController.getZoomControls();
719        ViewGroup.LayoutParams params = controls.getLayoutParams();
720        if (params instanceof FrameLayout.LayoutParams) {
721            FrameLayout.LayoutParams frameParams = (FrameLayout.LayoutParams)
722                    params;
723            frameParams.gravity = Gravity.RIGHT;
724        }
725    }
726
727    private void updateZoomButtonsEnabled() {
728        boolean canZoomIn = mActualScale < mMaxZoomScale;
729        boolean canZoomOut = mActualScale > mMinZoomScale;
730        if (!canZoomIn && !canZoomOut) {
731            // Hide the zoom in and out buttons, as well as the fit to page
732            // button, if the page cannot zoom
733            mZoomButtonsController.getZoomControls().setVisibility(View.GONE);
734        } else {
735            // Bring back the hidden zoom controls.
736            mZoomButtonsController.getZoomControls()
737                    .setVisibility(View.VISIBLE);
738            // Set each one individually, as a page may be able to zoom in
739            // or out.
740            mZoomButtonsController.setZoomInEnabled(canZoomIn);
741            mZoomButtonsController.setZoomOutEnabled(canZoomOut);
742        }
743    }
744
745    private void init() {
746        setWillNotDraw(false);
747        setFocusable(true);
748        setFocusableInTouchMode(true);
749        setClickable(true);
750        setLongClickable(true);
751
752        final int slop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
753        mTouchSlopSquare = slop * slop;
754        mMinLockSnapReverseDistance = slop;
755        final float density = getContext().getResources().getDisplayMetrics().density;
756        // use one line height, 16 based on our current default font, for how
757        // far we allow a touch be away from the edge of a link
758        mNavSlop = (int) (16 * density);
759        // density adjusted scale factors
760        DEFAULT_SCALE_PERCENT = (int) (100 * density);
761        mDefaultScale = density;
762        mActualScale = density;
763        mInvActualScale = 1 / density;
764        DEFAULT_MAX_ZOOM_SCALE = 4.0f * density;
765        DEFAULT_MIN_ZOOM_SCALE = 0.25f * density;
766        mMaxZoomScale = DEFAULT_MAX_ZOOM_SCALE;
767        mMinZoomScale = DEFAULT_MIN_ZOOM_SCALE;
768    }
769
770    /* package */void updateDefaultZoomDensity(int zoomDensity) {
771        final float density = getContext().getResources().getDisplayMetrics().density
772                * 100 / zoomDensity;
773        if (Math.abs(density - mDefaultScale) > 0.01) {
774            float scaleFactor = density / mDefaultScale;
775            // adjust the limits
776            mNavSlop = (int) (16 * density);
777            DEFAULT_SCALE_PERCENT = (int) (100 * density);
778            DEFAULT_MAX_ZOOM_SCALE = 4.0f * density;
779            DEFAULT_MIN_ZOOM_SCALE = 0.25f * density;
780            mDefaultScale = density;
781            mMaxZoomScale *= scaleFactor;
782            mMinZoomScale *= scaleFactor;
783            setNewZoomScale(mActualScale * scaleFactor, false);
784        }
785    }
786
787    /* package */ boolean onSavePassword(String schemePlusHost, String username,
788            String password, final Message resumeMsg) {
789       boolean rVal = false;
790       if (resumeMsg == null) {
791           // null resumeMsg implies saving password silently
792           mDatabase.setUsernamePassword(schemePlusHost, username, password);
793       } else {
794            final Message remember = mPrivateHandler.obtainMessage(
795                    REMEMBER_PASSWORD);
796            remember.getData().putString("host", schemePlusHost);
797            remember.getData().putString("username", username);
798            remember.getData().putString("password", password);
799            remember.obj = resumeMsg;
800
801            final Message neverRemember = mPrivateHandler.obtainMessage(
802                    NEVER_REMEMBER_PASSWORD);
803            neverRemember.getData().putString("host", schemePlusHost);
804            neverRemember.getData().putString("username", username);
805            neverRemember.getData().putString("password", password);
806            neverRemember.obj = resumeMsg;
807
808            new AlertDialog.Builder(getContext())
809                    .setTitle(com.android.internal.R.string.save_password_label)
810                    .setMessage(com.android.internal.R.string.save_password_message)
811                    .setPositiveButton(com.android.internal.R.string.save_password_notnow,
812                    new DialogInterface.OnClickListener() {
813                        public void onClick(DialogInterface dialog, int which) {
814                            resumeMsg.sendToTarget();
815                        }
816                    })
817                    .setNeutralButton(com.android.internal.R.string.save_password_remember,
818                    new DialogInterface.OnClickListener() {
819                        public void onClick(DialogInterface dialog, int which) {
820                            remember.sendToTarget();
821                        }
822                    })
823                    .setNegativeButton(com.android.internal.R.string.save_password_never,
824                    new DialogInterface.OnClickListener() {
825                        public void onClick(DialogInterface dialog, int which) {
826                            neverRemember.sendToTarget();
827                        }
828                    })
829                    .setOnCancelListener(new OnCancelListener() {
830                        public void onCancel(DialogInterface dialog) {
831                            resumeMsg.sendToTarget();
832                        }
833                    }).show();
834            // Return true so that WebViewCore will pause while the dialog is
835            // up.
836            rVal = true;
837        }
838       return rVal;
839    }
840
841    @Override
842    public void setScrollBarStyle(int style) {
843        if (style == View.SCROLLBARS_INSIDE_INSET
844                || style == View.SCROLLBARS_OUTSIDE_INSET) {
845            mOverlayHorizontalScrollbar = mOverlayVerticalScrollbar = false;
846        } else {
847            mOverlayHorizontalScrollbar = mOverlayVerticalScrollbar = true;
848        }
849        super.setScrollBarStyle(style);
850    }
851
852    /**
853     * Specify whether the horizontal scrollbar has overlay style.
854     * @param overlay TRUE if horizontal scrollbar should have overlay style.
855     */
856    public void setHorizontalScrollbarOverlay(boolean overlay) {
857        mOverlayHorizontalScrollbar = overlay;
858    }
859
860    /**
861     * Specify whether the vertical scrollbar has overlay style.
862     * @param overlay TRUE if vertical scrollbar should have overlay style.
863     */
864    public void setVerticalScrollbarOverlay(boolean overlay) {
865        mOverlayVerticalScrollbar = overlay;
866    }
867
868    /**
869     * Return whether horizontal scrollbar has overlay style
870     * @return TRUE if horizontal scrollbar has overlay style.
871     */
872    public boolean overlayHorizontalScrollbar() {
873        return mOverlayHorizontalScrollbar;
874    }
875
876    /**
877     * Return whether vertical scrollbar has overlay style
878     * @return TRUE if vertical scrollbar has overlay style.
879     */
880    public boolean overlayVerticalScrollbar() {
881        return mOverlayVerticalScrollbar;
882    }
883
884    /*
885     * Return the width of the view where the content of WebView should render
886     * to.
887     */
888    private int getViewWidth() {
889        if (!isVerticalScrollBarEnabled() || mOverlayVerticalScrollbar) {
890            return getWidth();
891        } else {
892            return getWidth() - getVerticalScrollbarWidth();
893        }
894    }
895
896    /*
897     * Return the height of the view where the content of WebView should render
898     * to.
899     */
900    private int getViewHeight() {
901        if (!isHorizontalScrollBarEnabled() || mOverlayHorizontalScrollbar) {
902            return getHeight();
903        } else {
904            return getHeight() - getHorizontalScrollbarHeight();
905        }
906    }
907
908    /**
909     * @return The SSL certificate for the main top-level page or null if
910     * there is no certificate (the site is not secure).
911     */
912    public SslCertificate getCertificate() {
913        return mCertificate;
914    }
915
916    /**
917     * Sets the SSL certificate for the main top-level page.
918     */
919    public void setCertificate(SslCertificate certificate) {
920        // here, the certificate can be null (if the site is not secure)
921        mCertificate = certificate;
922    }
923
924    //-------------------------------------------------------------------------
925    // Methods called by activity
926    //-------------------------------------------------------------------------
927
928    /**
929     * Save the username and password for a particular host in the WebView's
930     * internal database.
931     * @param host The host that required the credentials.
932     * @param username The username for the given host.
933     * @param password The password for the given host.
934     */
935    public void savePassword(String host, String username, String password) {
936        mDatabase.setUsernamePassword(host, username, password);
937    }
938
939    /**
940     * Set the HTTP authentication credentials for a given host and realm.
941     *
942     * @param host The host for the credentials.
943     * @param realm The realm for the credentials.
944     * @param username The username for the password. If it is null, it means
945     *                 password can't be saved.
946     * @param password The password
947     */
948    public void setHttpAuthUsernamePassword(String host, String realm,
949            String username, String password) {
950        mDatabase.setHttpAuthUsernamePassword(host, realm, username, password);
951    }
952
953    /**
954     * Retrieve the HTTP authentication username and password for a given
955     * host & realm pair
956     *
957     * @param host The host for which the credentials apply.
958     * @param realm The realm for which the credentials apply.
959     * @return String[] if found, String[0] is username, which can be null and
960     *         String[1] is password. Return null if it can't find anything.
961     */
962    public String[] getHttpAuthUsernamePassword(String host, String realm) {
963        return mDatabase.getHttpAuthUsernamePassword(host, realm);
964    }
965
966    /**
967     * Destroy the internal state of the WebView. This method should be called
968     * after the WebView has been removed from the view system. No other
969     * methods may be called on a WebView after destroy.
970     */
971    public void destroy() {
972        clearTextEntry();
973        if (mWebViewCore != null) {
974            // Set the handlers to null before destroying WebViewCore so no
975            // more messages will be posted.
976            mCallbackProxy.setWebViewClient(null);
977            mCallbackProxy.setWebChromeClient(null);
978            // Tell WebViewCore to destroy itself
979            WebViewCore webViewCore = mWebViewCore;
980            mWebViewCore = null; // prevent using partial webViewCore
981            webViewCore.destroy();
982            // Remove any pending messages that might not be serviced yet.
983            mPrivateHandler.removeCallbacksAndMessages(null);
984            mCallbackProxy.removeCallbacksAndMessages(null);
985            // Wake up the WebCore thread just in case it is waiting for a
986            // javascript dialog.
987            synchronized (mCallbackProxy) {
988                mCallbackProxy.notify();
989            }
990        }
991        if (mNativeClass != 0) {
992            nativeDestroy();
993            mNativeClass = 0;
994        }
995    }
996
997    /**
998     * Enables platform notifications of data state and proxy changes.
999     */
1000    public static void enablePlatformNotifications() {
1001        Network.enablePlatformNotifications();
1002    }
1003
1004    /**
1005     * If platform notifications are enabled, this should be called
1006     * from the Activity's onPause() or onStop().
1007     */
1008    public static void disablePlatformNotifications() {
1009        Network.disablePlatformNotifications();
1010    }
1011
1012    /**
1013     * Sets JavaScript engine flags.
1014     *
1015     * @param flags JS engine flags in a String
1016     *
1017     * @hide pending API solidification
1018     */
1019    public void setJsFlags(String flags) {
1020        mWebViewCore.sendMessage(EventHub.SET_JS_FLAGS, flags);
1021    }
1022
1023    /**
1024     * Inform WebView of the network state. This is used to set
1025     * the javascript property window.navigator.isOnline and
1026     * generates the online/offline event as specified in HTML5, sec. 5.7.7
1027     * @param networkUp boolean indicating if network is available
1028     */
1029    public void setNetworkAvailable(boolean networkUp) {
1030        mWebViewCore.sendMessage(EventHub.SET_NETWORK_STATE,
1031                networkUp ? 1 : 0, 0);
1032    }
1033
1034    /**
1035     * Save the state of this WebView used in
1036     * {@link android.app.Activity#onSaveInstanceState}. Please note that this
1037     * method no longer stores the display data for this WebView. The previous
1038     * behavior could potentially leak files if {@link #restoreState} was never
1039     * called. See {@link #savePicture} and {@link #restorePicture} for saving
1040     * and restoring the display data.
1041     * @param outState The Bundle to store the WebView state.
1042     * @return The same copy of the back/forward list used to save the state. If
1043     *         saveState fails, the returned list will be null.
1044     * @see #savePicture
1045     * @see #restorePicture
1046     */
1047    public WebBackForwardList saveState(Bundle outState) {
1048        if (outState == null) {
1049            return null;
1050        }
1051        // We grab a copy of the back/forward list because a client of WebView
1052        // may have invalidated the history list by calling clearHistory.
1053        WebBackForwardList list = copyBackForwardList();
1054        final int currentIndex = list.getCurrentIndex();
1055        final int size = list.getSize();
1056        // We should fail saving the state if the list is empty or the index is
1057        // not in a valid range.
1058        if (currentIndex < 0 || currentIndex >= size || size == 0) {
1059            return null;
1060        }
1061        outState.putInt("index", currentIndex);
1062        // FIXME: This should just be a byte[][] instead of ArrayList but
1063        // Parcel.java does not have the code to handle multi-dimensional
1064        // arrays.
1065        ArrayList<byte[]> history = new ArrayList<byte[]>(size);
1066        for (int i = 0; i < size; i++) {
1067            WebHistoryItem item = list.getItemAtIndex(i);
1068            byte[] data = item.getFlattenedData();
1069            if (data == null) {
1070                // It would be very odd to not have any data for a given history
1071                // item. And we will fail to rebuild the history list without
1072                // flattened data.
1073                return null;
1074            }
1075            history.add(data);
1076        }
1077        outState.putSerializable("history", history);
1078        if (mCertificate != null) {
1079            outState.putBundle("certificate",
1080                               SslCertificate.saveState(mCertificate));
1081        }
1082        return list;
1083    }
1084
1085    /**
1086     * Save the current display data to the Bundle given. Used in conjunction
1087     * with {@link #saveState}.
1088     * @param b A Bundle to store the display data.
1089     * @param dest The file to store the serialized picture data. Will be
1090     *             overwritten with this WebView's picture data.
1091     * @return True if the picture was successfully saved.
1092     */
1093    public boolean savePicture(Bundle b, File dest) {
1094        if (dest == null || b == null) {
1095            return false;
1096        }
1097        final Picture p = capturePicture();
1098        try {
1099            final FileOutputStream out = new FileOutputStream(dest);
1100            p.writeToStream(out);
1101            out.close();
1102        } catch (FileNotFoundException e){
1103            e.printStackTrace();
1104        } catch (IOException e) {
1105            e.printStackTrace();
1106        } catch (RuntimeException e) {
1107            e.printStackTrace();
1108        }
1109        if (dest.length() > 0) {
1110            b.putInt("scrollX", mScrollX);
1111            b.putInt("scrollY", mScrollY);
1112            b.putFloat("scale", mActualScale);
1113            return true;
1114        }
1115        return false;
1116    }
1117
1118    /**
1119     * Restore the display data that was save in {@link #savePicture}. Used in
1120     * conjunction with {@link #restoreState}.
1121     * @param b A Bundle containing the saved display data.
1122     * @param src The file where the picture data was stored.
1123     * @return True if the picture was successfully restored.
1124     */
1125    public boolean restorePicture(Bundle b, File src) {
1126        if (src == null || b == null) {
1127            return false;
1128        }
1129        if (src.exists()) {
1130            Picture p = null;
1131            try {
1132                final FileInputStream in = new FileInputStream(src);
1133                p = Picture.createFromStream(in);
1134                in.close();
1135            } catch (FileNotFoundException e){
1136                e.printStackTrace();
1137            } catch (RuntimeException e) {
1138                e.printStackTrace();
1139            } catch (IOException e) {
1140                e.printStackTrace();
1141            }
1142            if (p != null) {
1143                int sx = b.getInt("scrollX", 0);
1144                int sy = b.getInt("scrollY", 0);
1145                float scale = b.getFloat("scale", 1.0f);
1146                mDrawHistory = true;
1147                mHistoryPicture = p;
1148                mScrollX = sx;
1149                mScrollY = sy;
1150                mHistoryWidth = Math.round(p.getWidth() * scale);
1151                mHistoryHeight = Math.round(p.getHeight() * scale);
1152                // as getWidth() / getHeight() of the view are not
1153                // available yet, set up mActualScale, so that when
1154                // onSizeChanged() is called, the rest will be set
1155                // correctly
1156                mActualScale = scale;
1157                invalidate();
1158                return true;
1159            }
1160        }
1161        return false;
1162    }
1163
1164    /**
1165     * Restore the state of this WebView from the given map used in
1166     * {@link android.app.Activity#onRestoreInstanceState}. This method should
1167     * be called to restore the state of the WebView before using the object. If
1168     * it is called after the WebView has had a chance to build state (load
1169     * pages, create a back/forward list, etc.) there may be undesirable
1170     * side-effects. Please note that this method no longer restores the
1171     * display data for this WebView. See {@link #savePicture} and {@link
1172     * #restorePicture} for saving and restoring the display data.
1173     * @param inState The incoming Bundle of state.
1174     * @return The restored back/forward list or null if restoreState failed.
1175     * @see #savePicture
1176     * @see #restorePicture
1177     */
1178    public WebBackForwardList restoreState(Bundle inState) {
1179        WebBackForwardList returnList = null;
1180        if (inState == null) {
1181            return returnList;
1182        }
1183        if (inState.containsKey("index") && inState.containsKey("history")) {
1184            mCertificate = SslCertificate.restoreState(
1185                inState.getBundle("certificate"));
1186
1187            final WebBackForwardList list = mCallbackProxy.getBackForwardList();
1188            final int index = inState.getInt("index");
1189            // We can't use a clone of the list because we need to modify the
1190            // shared copy, so synchronize instead to prevent concurrent
1191            // modifications.
1192            synchronized (list) {
1193                final List<byte[]> history =
1194                        (List<byte[]>) inState.getSerializable("history");
1195                final int size = history.size();
1196                // Check the index bounds so we don't crash in native code while
1197                // restoring the history index.
1198                if (index < 0 || index >= size) {
1199                    return null;
1200                }
1201                for (int i = 0; i < size; i++) {
1202                    byte[] data = history.remove(0);
1203                    if (data == null) {
1204                        // If we somehow have null data, we cannot reconstruct
1205                        // the item and thus our history list cannot be rebuilt.
1206                        return null;
1207                    }
1208                    WebHistoryItem item = new WebHistoryItem(data);
1209                    list.addHistoryItem(item);
1210                }
1211                // Grab the most recent copy to return to the caller.
1212                returnList = copyBackForwardList();
1213                // Update the copy to have the correct index.
1214                returnList.setCurrentIndex(index);
1215            }
1216            // Remove all pending messages because we are restoring previous
1217            // state.
1218            mWebViewCore.removeMessages();
1219            // Send a restore state message.
1220            mWebViewCore.sendMessage(EventHub.RESTORE_STATE, index);
1221        }
1222        return returnList;
1223    }
1224
1225    /**
1226     * Load the given url.
1227     * @param url The url of the resource to load.
1228     */
1229    public void loadUrl(String url) {
1230        switchOutDrawHistory();
1231        mWebViewCore.sendMessage(EventHub.LOAD_URL, url);
1232        clearTextEntry();
1233    }
1234
1235    /**
1236     * Load the url with postData using "POST" method into the WebView. If url
1237     * is not a network url, it will be loaded with {link
1238     * {@link #loadUrl(String)} instead.
1239     *
1240     * @param url The url of the resource to load.
1241     * @param postData The data will be passed to "POST" request.
1242     *
1243     * @hide pending API solidification
1244     */
1245    public void postUrl(String url, byte[] postData) {
1246        if (URLUtil.isNetworkUrl(url)) {
1247            switchOutDrawHistory();
1248            WebViewCore.PostUrlData arg = new WebViewCore.PostUrlData();
1249            arg.mUrl = url;
1250            arg.mPostData = postData;
1251            mWebViewCore.sendMessage(EventHub.POST_URL, arg);
1252            clearTextEntry();
1253        } else {
1254            loadUrl(url);
1255        }
1256    }
1257
1258    /**
1259     * Load the given data into the WebView. This will load the data into
1260     * WebView using the data: scheme. Content loaded through this mechanism
1261     * does not have the ability to load content from the network.
1262     * @param data A String of data in the given encoding.
1263     * @param mimeType The MIMEType of the data. i.e. text/html, image/jpeg
1264     * @param encoding The encoding of the data. i.e. utf-8, base64
1265     */
1266    public void loadData(String data, String mimeType, String encoding) {
1267        loadUrl("data:" + mimeType + ";" + encoding + "," + data);
1268    }
1269
1270    /**
1271     * Load the given data into the WebView, use the provided URL as the base
1272     * URL for the content. The base URL is the URL that represents the page
1273     * that is loaded through this interface. As such, it is used for the
1274     * history entry and to resolve any relative URLs. The failUrl is used if
1275     * browser fails to load the data provided. If it is empty or null, and the
1276     * load fails, then no history entry is created.
1277     * <p>
1278     * Note for post 1.0. Due to the change in the WebKit, the access to asset
1279     * files through "file:///android_asset/" for the sub resources is more
1280     * restricted. If you provide null or empty string as baseUrl, you won't be
1281     * able to access asset files. If the baseUrl is anything other than
1282     * http(s)/ftp(s)/about/javascript as scheme, you can access asset files for
1283     * sub resources.
1284     *
1285     * @param baseUrl Url to resolve relative paths with, if null defaults to
1286     *            "about:blank"
1287     * @param data A String of data in the given encoding.
1288     * @param mimeType The MIMEType of the data. i.e. text/html. If null,
1289     *            defaults to "text/html"
1290     * @param encoding The encoding of the data. i.e. utf-8, us-ascii
1291     * @param failUrl URL to use if the content fails to load or null.
1292     */
1293    public void loadDataWithBaseURL(String baseUrl, String data,
1294            String mimeType, String encoding, String failUrl) {
1295
1296        if (baseUrl != null && baseUrl.toLowerCase().startsWith("data:")) {
1297            loadData(data, mimeType, encoding);
1298            return;
1299        }
1300        switchOutDrawHistory();
1301        WebViewCore.BaseUrlData arg = new WebViewCore.BaseUrlData();
1302        arg.mBaseUrl = baseUrl;
1303        arg.mData = data;
1304        arg.mMimeType = mimeType;
1305        arg.mEncoding = encoding;
1306        arg.mFailUrl = failUrl;
1307        mWebViewCore.sendMessage(EventHub.LOAD_DATA, arg);
1308        clearTextEntry();
1309    }
1310
1311    /**
1312     * Stop the current load.
1313     */
1314    public void stopLoading() {
1315        // TODO: should we clear all the messages in the queue before sending
1316        // STOP_LOADING?
1317        switchOutDrawHistory();
1318        mWebViewCore.sendMessage(EventHub.STOP_LOADING);
1319    }
1320
1321    /**
1322     * Reload the current url.
1323     */
1324    public void reload() {
1325        switchOutDrawHistory();
1326        mWebViewCore.sendMessage(EventHub.RELOAD);
1327    }
1328
1329    /**
1330     * Return true if this WebView has a back history item.
1331     * @return True iff this WebView has a back history item.
1332     */
1333    public boolean canGoBack() {
1334        WebBackForwardList l = mCallbackProxy.getBackForwardList();
1335        synchronized (l) {
1336            if (l.getClearPending()) {
1337                return false;
1338            } else {
1339                return l.getCurrentIndex() > 0;
1340            }
1341        }
1342    }
1343
1344    /**
1345     * Go back in the history of this WebView.
1346     */
1347    public void goBack() {
1348        goBackOrForward(-1);
1349    }
1350
1351    /**
1352     * Return true if this WebView has a forward history item.
1353     * @return True iff this Webview has a forward history item.
1354     */
1355    public boolean canGoForward() {
1356        WebBackForwardList l = mCallbackProxy.getBackForwardList();
1357        synchronized (l) {
1358            if (l.getClearPending()) {
1359                return false;
1360            } else {
1361                return l.getCurrentIndex() < l.getSize() - 1;
1362            }
1363        }
1364    }
1365
1366    /**
1367     * Go forward in the history of this WebView.
1368     */
1369    public void goForward() {
1370        goBackOrForward(1);
1371    }
1372
1373    /**
1374     * Return true if the page can go back or forward the given
1375     * number of steps.
1376     * @param steps The negative or positive number of steps to move the
1377     *              history.
1378     */
1379    public boolean canGoBackOrForward(int steps) {
1380        WebBackForwardList l = mCallbackProxy.getBackForwardList();
1381        synchronized (l) {
1382            if (l.getClearPending()) {
1383                return false;
1384            } else {
1385                int newIndex = l.getCurrentIndex() + steps;
1386                return newIndex >= 0 && newIndex < l.getSize();
1387            }
1388        }
1389    }
1390
1391    /**
1392     * Go to the history item that is the number of steps away from
1393     * the current item. Steps is negative if backward and positive
1394     * if forward.
1395     * @param steps The number of steps to take back or forward in the back
1396     *              forward list.
1397     */
1398    public void goBackOrForward(int steps) {
1399        goBackOrForward(steps, false);
1400    }
1401
1402    private void goBackOrForward(int steps, boolean ignoreSnapshot) {
1403        // every time we go back or forward, we want to reset the
1404        // WebView certificate:
1405        // if the new site is secure, we will reload it and get a
1406        // new certificate set;
1407        // if the new site is not secure, the certificate must be
1408        // null, and that will be the case
1409        mCertificate = null;
1410        if (steps != 0) {
1411            clearTextEntry();
1412            mWebViewCore.sendMessage(EventHub.GO_BACK_FORWARD, steps,
1413                    ignoreSnapshot ? 1 : 0);
1414        }
1415    }
1416
1417    private boolean extendScroll(int y) {
1418        int finalY = mScroller.getFinalY();
1419        int newY = pinLocY(finalY + y);
1420        if (newY == finalY) return false;
1421        mScroller.setFinalY(newY);
1422        mScroller.extendDuration(computeDuration(0, y));
1423        return true;
1424    }
1425
1426    /**
1427     * Scroll the contents of the view up by half the view size
1428     * @param top true to jump to the top of the page
1429     * @return true if the page was scrolled
1430     */
1431    public boolean pageUp(boolean top) {
1432        if (mNativeClass == 0) {
1433            return false;
1434        }
1435        nativeClearCursor(); // start next trackball movement from page edge
1436        if (top) {
1437            // go to the top of the document
1438            return pinScrollTo(mScrollX, 0, true, 0);
1439        }
1440        // Page up
1441        int h = getHeight();
1442        int y;
1443        if (h > 2 * PAGE_SCROLL_OVERLAP) {
1444            y = -h + PAGE_SCROLL_OVERLAP;
1445        } else {
1446            y = -h / 2;
1447        }
1448        mUserScroll = true;
1449        return mScroller.isFinished() ? pinScrollBy(0, y, true, 0)
1450                : extendScroll(y);
1451    }
1452
1453    /**
1454     * Scroll the contents of the view down by half the page size
1455     * @param bottom true to jump to bottom of page
1456     * @return true if the page was scrolled
1457     */
1458    public boolean pageDown(boolean bottom) {
1459        if (mNativeClass == 0) {
1460            return false;
1461        }
1462        nativeClearCursor(); // start next trackball movement from page edge
1463        if (bottom) {
1464            return pinScrollTo(mScrollX, mContentHeight, true, 0);
1465        }
1466        // Page down.
1467        int h = getHeight();
1468        int y;
1469        if (h > 2 * PAGE_SCROLL_OVERLAP) {
1470            y = h - PAGE_SCROLL_OVERLAP;
1471        } else {
1472            y = h / 2;
1473        }
1474        mUserScroll = true;
1475        return mScroller.isFinished() ? pinScrollBy(0, y, true, 0)
1476                : extendScroll(y);
1477    }
1478
1479    /**
1480     * Clear the view so that onDraw() will draw nothing but white background,
1481     * and onMeasure() will return 0 if MeasureSpec is not MeasureSpec.EXACTLY
1482     */
1483    public void clearView() {
1484        mContentWidth = 0;
1485        mContentHeight = 0;
1486        mWebViewCore.sendMessage(EventHub.CLEAR_CONTENT);
1487    }
1488
1489    /**
1490     * Return a new picture that captures the current display of the webview.
1491     * This is a copy of the display, and will be unaffected if the webview
1492     * later loads a different URL.
1493     *
1494     * @return a picture containing the current contents of the view. Note this
1495     *         picture is of the entire document, and is not restricted to the
1496     *         bounds of the view.
1497     */
1498    public Picture capturePicture() {
1499        if (null == mWebViewCore) return null; // check for out of memory tab
1500        return mWebViewCore.copyContentPicture();
1501    }
1502
1503    /**
1504     *  Return true if the browser is displaying a TextView for text input.
1505     */
1506    private boolean inEditingMode() {
1507        return mWebTextView != null && mWebTextView.getParent() != null
1508                && mWebTextView.hasFocus();
1509    }
1510
1511    private void clearTextEntry() {
1512        if (inEditingMode()) {
1513            mWebTextView.remove();
1514        }
1515    }
1516
1517    /**
1518     * Return the current scale of the WebView
1519     * @return The current scale.
1520     */
1521    public float getScale() {
1522        return mActualScale;
1523    }
1524
1525    /**
1526     * Set the initial scale for the WebView. 0 means default. If
1527     * {@link WebSettings#getUseWideViewPort()} is true, it zooms out all the
1528     * way. Otherwise it starts with 100%. If initial scale is greater than 0,
1529     * WebView starts will this value as initial scale.
1530     *
1531     * @param scaleInPercent The initial scale in percent.
1532     */
1533    public void setInitialScale(int scaleInPercent) {
1534        mInitialScale = scaleInPercent;
1535    }
1536
1537    /**
1538     * Invoke the graphical zoom picker widget for this WebView. This will
1539     * result in the zoom widget appearing on the screen to control the zoom
1540     * level of this WebView.
1541     */
1542    public void invokeZoomPicker() {
1543        if (!getSettings().supportZoom()) {
1544            Log.w(LOGTAG, "This WebView doesn't support zoom.");
1545            return;
1546        }
1547        clearTextEntry();
1548        if (getSettings().getBuiltInZoomControls()) {
1549            mZoomButtonsController.setVisible(true);
1550        } else {
1551            mPrivateHandler.removeCallbacks(mZoomControlRunnable);
1552            mPrivateHandler.postDelayed(mZoomControlRunnable,
1553                    ZOOM_CONTROLS_TIMEOUT);
1554        }
1555    }
1556
1557    /**
1558     * Return a HitTestResult based on the current cursor node. If a HTML::a tag
1559     * is found and the anchor has a non-javascript url, the HitTestResult type
1560     * is set to SRC_ANCHOR_TYPE and the url is set in the "extra" field. If the
1561     * anchor does not have a url or if it is a javascript url, the type will
1562     * be UNKNOWN_TYPE and the url has to be retrieved through
1563     * {@link #requestFocusNodeHref} asynchronously. If a HTML::img tag is
1564     * found, the HitTestResult type is set to IMAGE_TYPE and the url is set in
1565     * the "extra" field. A type of
1566     * SRC_IMAGE_ANCHOR_TYPE indicates an anchor with a url that has an image as
1567     * a child node. If a phone number is found, the HitTestResult type is set
1568     * to PHONE_TYPE and the phone number is set in the "extra" field of
1569     * HitTestResult. If a map address is found, the HitTestResult type is set
1570     * to GEO_TYPE and the address is set in the "extra" field of HitTestResult.
1571     * If an email address is found, the HitTestResult type is set to EMAIL_TYPE
1572     * and the email is set in the "extra" field of HitTestResult. Otherwise,
1573     * HitTestResult type is set to UNKNOWN_TYPE.
1574     */
1575    public HitTestResult getHitTestResult() {
1576        if (mNativeClass == 0) {
1577            return null;
1578        }
1579
1580        HitTestResult result = new HitTestResult();
1581        if (nativeHasCursorNode()) {
1582            if (nativeCursorIsTextInput()) {
1583                result.setType(HitTestResult.EDIT_TEXT_TYPE);
1584            } else {
1585                String text = nativeCursorText();
1586                if (text != null) {
1587                    if (text.startsWith(SCHEME_TEL)) {
1588                        result.setType(HitTestResult.PHONE_TYPE);
1589                        result.setExtra(text.substring(SCHEME_TEL.length()));
1590                    } else if (text.startsWith(SCHEME_MAILTO)) {
1591                        result.setType(HitTestResult.EMAIL_TYPE);
1592                        result.setExtra(text.substring(SCHEME_MAILTO.length()));
1593                    } else if (text.startsWith(SCHEME_GEO)) {
1594                        result.setType(HitTestResult.GEO_TYPE);
1595                        result.setExtra(URLDecoder.decode(text
1596                                .substring(SCHEME_GEO.length())));
1597                    } else if (nativeCursorIsAnchor()) {
1598                        result.setType(HitTestResult.SRC_ANCHOR_TYPE);
1599                        result.setExtra(text);
1600                    }
1601                }
1602            }
1603        }
1604        int type = result.getType();
1605        if (type == HitTestResult.UNKNOWN_TYPE
1606                || type == HitTestResult.SRC_ANCHOR_TYPE) {
1607            // Now check to see if it is an image.
1608            int contentX = viewToContent((int) mLastTouchX + mScrollX);
1609            int contentY = viewToContent((int) mLastTouchY + mScrollY);
1610            String text = nativeImageURI(contentX, contentY);
1611            if (text != null) {
1612                result.setType(type == HitTestResult.UNKNOWN_TYPE ?
1613                        HitTestResult.IMAGE_TYPE :
1614                        HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1615                result.setExtra(text);
1616            }
1617        }
1618        return result;
1619    }
1620
1621    /**
1622     * Request the href of an anchor element due to getFocusNodePath returning
1623     * "href." If hrefMsg is null, this method returns immediately and does not
1624     * dispatch hrefMsg to its target.
1625     *
1626     * @param hrefMsg This message will be dispatched with the result of the
1627     *            request as the data member with "url" as key. The result can
1628     *            be null.
1629     */
1630    // FIXME: API change required to change the name of this function.  We now
1631    // look at the cursor node, and not the focus node.  Also, what is
1632    // getFocusNodePath?
1633    public void requestFocusNodeHref(Message hrefMsg) {
1634        if (hrefMsg == null || mNativeClass == 0) {
1635            return;
1636        }
1637        if (nativeCursorIsAnchor()) {
1638            mWebViewCore.sendMessage(EventHub.REQUEST_CURSOR_HREF,
1639                    nativeCursorFramePointer(), nativeCursorNodePointer(),
1640                    hrefMsg);
1641        }
1642    }
1643
1644    /**
1645     * Request the url of the image last touched by the user. msg will be sent
1646     * to its target with a String representing the url as its object.
1647     *
1648     * @param msg This message will be dispatched with the result of the request
1649     *            as the data member with "url" as key. The result can be null.
1650     */
1651    public void requestImageRef(Message msg) {
1652        int contentX = viewToContent((int) mLastTouchX + mScrollX);
1653        int contentY = viewToContent((int) mLastTouchY + mScrollY);
1654        String ref = nativeImageURI(contentX, contentY);
1655        Bundle data = msg.getData();
1656        data.putString("url", ref);
1657        msg.setData(data);
1658        msg.sendToTarget();
1659    }
1660
1661    private static int pinLoc(int x, int viewMax, int docMax) {
1662//        Log.d(LOGTAG, "-- pinLoc " + x + " " + viewMax + " " + docMax);
1663        if (docMax < viewMax) {   // the doc has room on the sides for "blank"
1664            // pin the short document to the top/left of the screen
1665            x = 0;
1666//            Log.d(LOGTAG, "--- center " + x);
1667        } else if (x < 0) {
1668            x = 0;
1669//            Log.d(LOGTAG, "--- zero");
1670        } else if (x + viewMax > docMax) {
1671            x = docMax - viewMax;
1672//            Log.d(LOGTAG, "--- pin " + x);
1673        }
1674        return x;
1675    }
1676
1677    // Expects x in view coordinates
1678    private int pinLocX(int x) {
1679        return pinLoc(x, getViewWidth(), computeHorizontalScrollRange());
1680    }
1681
1682    // Expects y in view coordinates
1683    private int pinLocY(int y) {
1684        return pinLoc(y, getViewHeight(), computeVerticalScrollRange());
1685    }
1686
1687    /*package*/ int viewToContent(int x) {
1688        return Math.round(x * mInvActualScale);
1689    }
1690
1691    private int contentToView(int x) {
1692        return Math.round(x * mActualScale);
1693    }
1694
1695    // Called by JNI to invalidate the View, given rectangle coordinates in
1696    // content space
1697    private void viewInvalidate(int l, int t, int r, int b) {
1698        invalidate(contentToView(l), contentToView(t), contentToView(r),
1699                contentToView(b));
1700    }
1701
1702    // Called by JNI to invalidate the View after a delay, given rectangle
1703    // coordinates in content space
1704    private void viewInvalidateDelayed(long delay, int l, int t, int r, int b) {
1705        postInvalidateDelayed(delay, contentToView(l), contentToView(t),
1706                contentToView(r), contentToView(b));
1707    }
1708
1709    private Rect contentToView(Rect x) {
1710        return new Rect(contentToView(x.left), contentToView(x.top)
1711                , contentToView(x.right), contentToView(x.bottom));
1712    }
1713
1714    /* call from webcoreview.draw(), so we're still executing in the UI thread
1715    */
1716    private void recordNewContentSize(int w, int h, boolean updateLayout) {
1717
1718        // premature data from webkit, ignore
1719        if ((w | h) == 0) {
1720            return;
1721        }
1722
1723        // don't abort a scroll animation if we didn't change anything
1724        if (mContentWidth != w || mContentHeight != h) {
1725            // record new dimensions
1726            mContentWidth = w;
1727            mContentHeight = h;
1728            // If history Picture is drawn, don't update scroll. They will be
1729            // updated when we get out of that mode.
1730            if (!mDrawHistory) {
1731                // repin our scroll, taking into account the new content size
1732                int oldX = mScrollX;
1733                int oldY = mScrollY;
1734                mScrollX = pinLocX(mScrollX);
1735                mScrollY = pinLocY(mScrollY);
1736                // android.util.Log.d("skia", "recordNewContentSize -
1737                // abortAnimation");
1738                mScroller.abortAnimation(); // just in case
1739                if (oldX != mScrollX || oldY != mScrollY) {
1740                    sendOurVisibleRect();
1741                }
1742            }
1743        }
1744        contentSizeChanged(updateLayout);
1745    }
1746
1747    private void setNewZoomScale(float scale, boolean force) {
1748        if (scale < mMinZoomScale) {
1749            scale = mMinZoomScale;
1750        } else if (scale > mMaxZoomScale) {
1751            scale = mMaxZoomScale;
1752        }
1753        if (scale != mActualScale || force) {
1754            if (mDrawHistory) {
1755                // If history Picture is drawn, don't update scroll. They will
1756                // be updated when we get out of that mode.
1757                if (scale != mActualScale && !mPreviewZoomOnly) {
1758                    mCallbackProxy.onScaleChanged(mActualScale, scale);
1759                }
1760                mActualScale = scale;
1761                mInvActualScale = 1 / scale;
1762                if (!mPreviewZoomOnly) {
1763                    sendViewSizeZoom();
1764                }
1765            } else {
1766                // update our scroll so we don't appear to jump
1767                // i.e. keep the center of the doc in the center of the view
1768
1769                int oldX = mScrollX;
1770                int oldY = mScrollY;
1771                float ratio = scale * mInvActualScale;   // old inverse
1772                float sx = ratio * oldX + (ratio - 1) * mZoomCenterX;
1773                float sy = ratio * oldY + (ratio - 1) * mZoomCenterY;
1774
1775                // now update our new scale and inverse
1776                if (scale != mActualScale && !mPreviewZoomOnly) {
1777                    mCallbackProxy.onScaleChanged(mActualScale, scale);
1778                }
1779                mActualScale = scale;
1780                mInvActualScale = 1 / scale;
1781
1782                // as we don't have animation for scaling, don't do animation
1783                // for scrolling, as it causes weird intermediate state
1784                //        pinScrollTo(Math.round(sx), Math.round(sy));
1785                mScrollX = pinLocX(Math.round(sx));
1786                mScrollY = pinLocY(Math.round(sy));
1787
1788                if (!mPreviewZoomOnly) {
1789                    sendViewSizeZoom();
1790                    sendOurVisibleRect();
1791                }
1792            }
1793        }
1794    }
1795
1796    // Used to avoid sending many visible rect messages.
1797    private Rect mLastVisibleRectSent;
1798    private Rect mLastGlobalRect;
1799
1800    private Rect sendOurVisibleRect() {
1801        Rect rect = new Rect();
1802        calcOurContentVisibleRect(rect);
1803        // Rect.equals() checks for null input.
1804        if (!rect.equals(mLastVisibleRectSent)) {
1805            Point pos = new Point(rect.left, rect.top);
1806            mWebViewCore.sendMessage(EventHub.SET_SCROLL_OFFSET,
1807                    nativeMoveGeneration(), 0, pos);
1808            mLastVisibleRectSent = rect;
1809        }
1810        Rect globalRect = new Rect();
1811        if (getGlobalVisibleRect(globalRect)
1812                && !globalRect.equals(mLastGlobalRect)) {
1813            if (DebugFlags.WEB_VIEW) {
1814                Log.v(LOGTAG, "sendOurVisibleRect=(" + globalRect.left + ","
1815                        + globalRect.top + ",r=" + globalRect.right + ",b="
1816                        + globalRect.bottom);
1817            }
1818            // TODO: the global offset is only used by windowRect()
1819            // in ChromeClientAndroid ; other clients such as touch
1820            // and mouse events could return view + screen relative points.
1821            mWebViewCore.sendMessage(EventHub.SET_GLOBAL_BOUNDS, globalRect);
1822            mLastGlobalRect = globalRect;
1823        }
1824        return rect;
1825    }
1826
1827    // Sets r to be the visible rectangle of our webview in view coordinates
1828    private void calcOurVisibleRect(Rect r) {
1829        Point p = new Point();
1830        getGlobalVisibleRect(r, p);
1831        r.offset(-p.x, -p.y);
1832        if (mFindIsUp) {
1833            r.bottom -= FIND_HEIGHT;
1834        }
1835    }
1836
1837    // Sets r to be our visible rectangle in content coordinates
1838    private void calcOurContentVisibleRect(Rect r) {
1839        calcOurVisibleRect(r);
1840        r.left = viewToContent(r.left);
1841        r.top = viewToContent(r.top);
1842        r.right = viewToContent(r.right);
1843        r.bottom = viewToContent(r.bottom);
1844    }
1845
1846    /**
1847     * Compute unzoomed width and height, and if they differ from the last
1848     * values we sent, send them to webkit (to be used has new viewport)
1849     *
1850     * @return true if new values were sent
1851     */
1852    private boolean sendViewSizeZoom() {
1853        int newWidth = Math.round(getViewWidth() * mInvActualScale);
1854        int newHeight = Math.round(getViewHeight() * mInvActualScale);
1855        /*
1856         * Because the native side may have already done a layout before the
1857         * View system was able to measure us, we have to send a height of 0 to
1858         * remove excess whitespace when we grow our width. This will trigger a
1859         * layout and a change in content size. This content size change will
1860         * mean that contentSizeChanged will either call this method directly or
1861         * indirectly from onSizeChanged.
1862         */
1863        if (newWidth > mLastWidthSent && mWrapContent) {
1864            newHeight = 0;
1865        }
1866        // Avoid sending another message if the dimensions have not changed.
1867        if (newWidth != mLastWidthSent || newHeight != mLastHeightSent) {
1868            mWebViewCore.sendMessage(EventHub.VIEW_SIZE_CHANGED,
1869                    newWidth, newHeight, new Float(mActualScale));
1870            mLastWidthSent = newWidth;
1871            mLastHeightSent = newHeight;
1872            return true;
1873        }
1874        return false;
1875    }
1876
1877    @Override
1878    protected int computeHorizontalScrollRange() {
1879        if (mDrawHistory) {
1880            return mHistoryWidth;
1881        } else {
1882            return contentToView(mContentWidth);
1883        }
1884    }
1885
1886    // Make sure this stays in sync with the actual height of the FindDialog.
1887    private static final int FIND_HEIGHT = 79;
1888
1889    @Override
1890    protected int computeVerticalScrollRange() {
1891        if (mDrawHistory) {
1892            return mHistoryHeight;
1893        } else {
1894            int height = contentToView(mContentHeight);
1895            if (mFindIsUp) {
1896                height += FIND_HEIGHT;
1897            }
1898            return height;
1899        }
1900    }
1901
1902    /**
1903     * Get the url for the current page. This is not always the same as the url
1904     * passed to WebViewClient.onPageStarted because although the load for
1905     * that url has begun, the current page may not have changed.
1906     * @return The url for the current page.
1907     */
1908    public String getUrl() {
1909        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
1910        return h != null ? h.getUrl() : null;
1911    }
1912
1913    /**
1914     * Get the original url for the current page. This is not always the same
1915     * as the url passed to WebViewClient.onPageStarted because although the
1916     * load for that url has begun, the current page may not have changed.
1917     * Also, there may have been redirects resulting in a different url to that
1918     * originally requested.
1919     * @return The url that was originally requested for the current page.
1920     */
1921    public String getOriginalUrl() {
1922        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
1923        return h != null ? h.getOriginalUrl() : null;
1924    }
1925
1926    /**
1927     * Get the title for the current page. This is the title of the current page
1928     * until WebViewClient.onReceivedTitle is called.
1929     * @return The title for the current page.
1930     */
1931    public String getTitle() {
1932        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
1933        return h != null ? h.getTitle() : null;
1934    }
1935
1936    /**
1937     * Get the favicon for the current page. This is the favicon of the current
1938     * page until WebViewClient.onReceivedIcon is called.
1939     * @return The favicon for the current page.
1940     */
1941    public Bitmap getFavicon() {
1942        WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem();
1943        return h != null ? h.getFavicon() : null;
1944    }
1945
1946    /**
1947     * Get the progress for the current page.
1948     * @return The progress for the current page between 0 and 100.
1949     */
1950    public int getProgress() {
1951        return mCallbackProxy.getProgress();
1952    }
1953
1954    /**
1955     * @return the height of the HTML content.
1956     */
1957    public int getContentHeight() {
1958        return mContentHeight;
1959    }
1960
1961    /**
1962     * Pause all layout, parsing, and javascript timers for all webviews. This
1963     * is a global requests, not restricted to just this webview. This can be
1964     * useful if the application has been paused.
1965     */
1966    public void pauseTimers() {
1967        mWebViewCore.sendMessage(EventHub.PAUSE_TIMERS);
1968    }
1969
1970    /**
1971     * Resume all layout, parsing, and javascript timers for all webviews.
1972     * This will resume dispatching all timers.
1973     */
1974    public void resumeTimers() {
1975        mWebViewCore.sendMessage(EventHub.RESUME_TIMERS);
1976    }
1977
1978    /**
1979     * Call this to pause any extra processing associated with this view and
1980     * its associated DOM/plugins/javascript/etc. For example, if the view is
1981     * taken offscreen, this could be called to reduce unnecessary CPU and/or
1982     * network traffic. When the view is again "active", call onResume().
1983     *
1984     * Note that this differs from pauseTimers(), which affects all views/DOMs
1985     * @hide
1986     */
1987    public void onPause() {
1988        if (!mIsPaused) {
1989            mIsPaused = true;
1990            mWebViewCore.sendMessage(EventHub.ON_PAUSE);
1991        }
1992    }
1993
1994    /**
1995     * Call this to balanace a previous call to onPause()
1996     * @hide
1997     */
1998    public void onResume() {
1999        if (mIsPaused) {
2000            mIsPaused = false;
2001            mWebViewCore.sendMessage(EventHub.ON_RESUME);
2002        }
2003    }
2004
2005    /**
2006     * Returns true if the view is paused, meaning onPause() was called. Calling
2007     * onResume() sets the paused state back to false.
2008     * @hide
2009     */
2010    public boolean isPaused() {
2011        return mIsPaused;
2012    }
2013
2014    /**
2015     * Call this to inform the view that memory is low so that it can
2016     * free any available memory.
2017     * @hide
2018     */
2019    public void freeMemory() {
2020        mWebViewCore.sendMessage(EventHub.FREE_MEMORY);
2021    }
2022
2023    /**
2024     * Clear the resource cache. Note that the cache is per-application, so
2025     * this will clear the cache for all WebViews used.
2026     *
2027     * @param includeDiskFiles If false, only the RAM cache is cleared.
2028     */
2029    public void clearCache(boolean includeDiskFiles) {
2030        // Note: this really needs to be a static method as it clears cache for all
2031        // WebView. But we need mWebViewCore to send message to WebCore thread, so
2032        // we can't make this static.
2033        mWebViewCore.sendMessage(EventHub.CLEAR_CACHE,
2034                includeDiskFiles ? 1 : 0, 0);
2035    }
2036
2037    /**
2038     * Make sure that clearing the form data removes the adapter from the
2039     * currently focused textfield if there is one.
2040     */
2041    public void clearFormData() {
2042        if (inEditingMode()) {
2043            AutoCompleteAdapter adapter = null;
2044            mWebTextView.setAdapterCustom(adapter);
2045        }
2046    }
2047
2048    /**
2049     * Tell the WebView to clear its internal back/forward list.
2050     */
2051    public void clearHistory() {
2052        mCallbackProxy.getBackForwardList().setClearPending();
2053        mWebViewCore.sendMessage(EventHub.CLEAR_HISTORY);
2054    }
2055
2056    /**
2057     * Clear the SSL preferences table stored in response to proceeding with SSL
2058     * certificate errors.
2059     */
2060    public void clearSslPreferences() {
2061        mWebViewCore.sendMessage(EventHub.CLEAR_SSL_PREF_TABLE);
2062    }
2063
2064    /**
2065     * Return the WebBackForwardList for this WebView. This contains the
2066     * back/forward list for use in querying each item in the history stack.
2067     * This is a copy of the private WebBackForwardList so it contains only a
2068     * snapshot of the current state. Multiple calls to this method may return
2069     * different objects. The object returned from this method will not be
2070     * updated to reflect any new state.
2071     */
2072    public WebBackForwardList copyBackForwardList() {
2073        return mCallbackProxy.getBackForwardList().clone();
2074    }
2075
2076    /*
2077     * Highlight and scroll to the next occurance of String in findAll.
2078     * Wraps the page infinitely, and scrolls.  Must be called after
2079     * calling findAll.
2080     *
2081     * @param forward Direction to search.
2082     */
2083    public void findNext(boolean forward) {
2084        nativeFindNext(forward);
2085    }
2086
2087    /*
2088     * Find all instances of find on the page and highlight them.
2089     * @param find  String to find.
2090     * @return int  The number of occurances of the String "find"
2091     *              that were found.
2092     */
2093    public int findAll(String find) {
2094        mFindIsUp = true;
2095        int result = nativeFindAll(find.toLowerCase(), find.toUpperCase());
2096        invalidate();
2097        return result;
2098    }
2099
2100    // Used to know whether the find dialog is open.  Affects whether
2101    // or not we draw the highlights for matches.
2102    private boolean mFindIsUp;
2103
2104    /**
2105     * Return the first substring consisting of the address of a physical
2106     * location. Currently, only addresses in the United States are detected,
2107     * and consist of:
2108     * - a house number
2109     * - a street name
2110     * - a street type (Road, Circle, etc), either spelled out or abbreviated
2111     * - a city name
2112     * - a state or territory, either spelled out or two-letter abbr.
2113     * - an optional 5 digit or 9 digit zip code.
2114     *
2115     * All names must be correctly capitalized, and the zip code, if present,
2116     * must be valid for the state. The street type must be a standard USPS
2117     * spelling or abbreviation. The state or territory must also be spelled
2118     * or abbreviated using USPS standards. The house number may not exceed
2119     * five digits.
2120     * @param addr The string to search for addresses.
2121     *
2122     * @return the address, or if no address is found, return null.
2123     */
2124    public static String findAddress(String addr) {
2125        return findAddress(addr, false);
2126    }
2127
2128    /**
2129     * @hide
2130     * Return the first substring consisting of the address of a physical
2131     * location. Currently, only addresses in the United States are detected,
2132     * and consist of:
2133     * - a house number
2134     * - a street name
2135     * - a street type (Road, Circle, etc), either spelled out or abbreviated
2136     * - a city name
2137     * - a state or territory, either spelled out or two-letter abbr.
2138     * - an optional 5 digit or 9 digit zip code.
2139     *
2140     * Names are optionally capitalized, and the zip code, if present,
2141     * must be valid for the state. The street type must be a standard USPS
2142     * spelling or abbreviation. The state or territory must also be spelled
2143     * or abbreviated using USPS standards. The house number may not exceed
2144     * five digits.
2145     * @param addr The string to search for addresses.
2146     * @param caseInsensitive addr Set to true to make search ignore case.
2147     *
2148     * @return the address, or if no address is found, return null.
2149     */
2150    public static String findAddress(String addr, boolean caseInsensitive) {
2151        return WebViewCore.nativeFindAddress(addr, caseInsensitive);
2152    }
2153
2154    /*
2155     * Clear the highlighting surrounding text matches created by findAll.
2156     */
2157    public void clearMatches() {
2158        mFindIsUp = false;
2159        nativeSetFindIsDown();
2160        // Now that the dialog has been removed, ensure that we scroll to a
2161        // location that is not beyond the end of the page.
2162        pinScrollTo(mScrollX, mScrollY, false, 0);
2163        invalidate();
2164    }
2165
2166    /**
2167     * Query the document to see if it contains any image references. The
2168     * message object will be dispatched with arg1 being set to 1 if images
2169     * were found and 0 if the document does not reference any images.
2170     * @param response The message that will be dispatched with the result.
2171     */
2172    public void documentHasImages(Message response) {
2173        if (response == null) {
2174            return;
2175        }
2176        mWebViewCore.sendMessage(EventHub.DOC_HAS_IMAGES, response);
2177    }
2178
2179    @Override
2180    public void computeScroll() {
2181        if (mScroller.computeScrollOffset()) {
2182            int oldX = mScrollX;
2183            int oldY = mScrollY;
2184            mScrollX = mScroller.getCurrX();
2185            mScrollY = mScroller.getCurrY();
2186            postInvalidate();  // So we draw again
2187            if (oldX != mScrollX || oldY != mScrollY) {
2188                // as onScrollChanged() is not called, sendOurVisibleRect()
2189                // needs to be call explicitly
2190                sendOurVisibleRect();
2191            }
2192        } else {
2193            super.computeScroll();
2194        }
2195    }
2196
2197    private static int computeDuration(int dx, int dy) {
2198        int distance = Math.max(Math.abs(dx), Math.abs(dy));
2199        int duration = distance * 1000 / STD_SPEED;
2200        return Math.min(duration, MAX_DURATION);
2201    }
2202
2203    // helper to pin the scrollBy parameters (already in view coordinates)
2204    // returns true if the scroll was changed
2205    private boolean pinScrollBy(int dx, int dy, boolean animate, int animationDuration) {
2206        return pinScrollTo(mScrollX + dx, mScrollY + dy, animate, animationDuration);
2207    }
2208
2209    // helper to pin the scrollTo parameters (already in view coordinates)
2210    // returns true if the scroll was changed
2211    private boolean pinScrollTo(int x, int y, boolean animate, int animationDuration) {
2212        x = pinLocX(x);
2213        y = pinLocY(y);
2214        int dx = x - mScrollX;
2215        int dy = y - mScrollY;
2216
2217        if ((dx | dy) == 0) {
2218            return false;
2219        }
2220
2221        if (true && animate) {
2222            //        Log.d(LOGTAG, "startScroll: " + dx + " " + dy);
2223
2224            mScroller.startScroll(mScrollX, mScrollY, dx, dy,
2225                    animationDuration > 0 ? animationDuration : computeDuration(dx, dy));
2226            invalidate();
2227        } else {
2228            mScroller.abortAnimation(); // just in case
2229            scrollTo(x, y);
2230        }
2231        return true;
2232    }
2233
2234    // Scale from content to view coordinates, and pin.
2235    // Also called by jni webview.cpp
2236    private void setContentScrollBy(int cx, int cy, boolean animate) {
2237        if (mDrawHistory) {
2238            // disallow WebView to change the scroll position as History Picture
2239            // is used in the view system.
2240            // TODO: as we switchOutDrawHistory when trackball or navigation
2241            // keys are hit, this should be safe. Right?
2242            return;
2243        }
2244        cx = contentToView(cx);
2245        cy = contentToView(cy);
2246        if (mHeightCanMeasure) {
2247            // move our visible rect according to scroll request
2248            if (cy != 0) {
2249                Rect tempRect = new Rect();
2250                calcOurVisibleRect(tempRect);
2251                tempRect.offset(cx, cy);
2252                requestRectangleOnScreen(tempRect);
2253            }
2254            // FIXME: We scroll horizontally no matter what because currently
2255            // ScrollView and ListView will not scroll horizontally.
2256            // FIXME: Why do we only scroll horizontally if there is no
2257            // vertical scroll?
2258//                Log.d(LOGTAG, "setContentScrollBy cy=" + cy);
2259            if (cy == 0 && cx != 0) {
2260                pinScrollBy(cx, 0, animate, 0);
2261            }
2262        } else {
2263            pinScrollBy(cx, cy, animate, 0);
2264        }
2265    }
2266
2267    // scale from content to view coordinates, and pin
2268    // return true if pin caused the final x/y different than the request cx/cy;
2269    // return false if the view scroll to the exact position as it is requested.
2270    private boolean setContentScrollTo(int cx, int cy) {
2271        if (mDrawHistory) {
2272            // disallow WebView to change the scroll position as History Picture
2273            // is used in the view system.
2274            // One known case where this is called is that WebCore tries to
2275            // restore the scroll position. As history Picture already uses the
2276            // saved scroll position, it is ok to skip this.
2277            return false;
2278        }
2279        int vx = contentToView(cx);
2280        int vy = contentToView(cy);
2281//        Log.d(LOGTAG, "content scrollTo [" + cx + " " + cy + "] view=[" +
2282//                      vx + " " + vy + "]");
2283        pinScrollTo(vx, vy, false, 0);
2284        if (mScrollX != vx || mScrollY != vy) {
2285            return true;
2286        } else {
2287            return false;
2288        }
2289    }
2290
2291    // scale from content to view coordinates, and pin
2292    private void spawnContentScrollTo(int cx, int cy) {
2293        if (mDrawHistory) {
2294            // disallow WebView to change the scroll position as History Picture
2295            // is used in the view system.
2296            return;
2297        }
2298        int vx = contentToView(cx);
2299        int vy = contentToView(cy);
2300        pinScrollTo(vx, vy, true, 0);
2301    }
2302
2303    /**
2304     * These are from webkit, and are in content coordinate system (unzoomed)
2305     */
2306    private void contentSizeChanged(boolean updateLayout) {
2307        // suppress 0,0 since we usually see real dimensions soon after
2308        // this avoids drawing the prev content in a funny place. If we find a
2309        // way to consolidate these notifications, this check may become
2310        // obsolete
2311        if ((mContentWidth | mContentHeight) == 0) {
2312            return;
2313        }
2314
2315        if (mHeightCanMeasure) {
2316            if (getMeasuredHeight() != contentToView(mContentHeight)
2317                    && updateLayout) {
2318                requestLayout();
2319            }
2320        } else if (mWidthCanMeasure) {
2321            if (getMeasuredWidth() != contentToView(mContentWidth)
2322                    && updateLayout) {
2323                requestLayout();
2324            }
2325        } else {
2326            // If we don't request a layout, try to send our view size to the
2327            // native side to ensure that WebCore has the correct dimensions.
2328            sendViewSizeZoom();
2329        }
2330    }
2331
2332    /**
2333     * Set the WebViewClient that will receive various notifications and
2334     * requests. This will replace the current handler.
2335     * @param client An implementation of WebViewClient.
2336     */
2337    public void setWebViewClient(WebViewClient client) {
2338        mCallbackProxy.setWebViewClient(client);
2339    }
2340
2341    /**
2342     * Register the interface to be used when content can not be handled by
2343     * the rendering engine, and should be downloaded instead. This will replace
2344     * the current handler.
2345     * @param listener An implementation of DownloadListener.
2346     */
2347    public void setDownloadListener(DownloadListener listener) {
2348        mCallbackProxy.setDownloadListener(listener);
2349    }
2350
2351    /**
2352     * Set the chrome handler. This is an implementation of WebChromeClient for
2353     * use in handling Javascript dialogs, favicons, titles, and the progress.
2354     * This will replace the current handler.
2355     * @param client An implementation of WebChromeClient.
2356     */
2357    public void setWebChromeClient(WebChromeClient client) {
2358        mCallbackProxy.setWebChromeClient(client);
2359    }
2360
2361    /**
2362     * Gets the chrome handler.
2363     * @return the current WebChromeClient instance.
2364     *
2365     * @hide API council approval.
2366     */
2367    public WebChromeClient getWebChromeClient() {
2368        return mCallbackProxy.getWebChromeClient();
2369    }
2370
2371    /**
2372     * Set the Picture listener. This is an interface used to receive
2373     * notifications of a new Picture.
2374     * @param listener An implementation of WebView.PictureListener.
2375     */
2376    public void setPictureListener(PictureListener listener) {
2377        mPictureListener = listener;
2378    }
2379
2380    /**
2381     * {@hide}
2382     */
2383    /* FIXME: Debug only! Remove for SDK! */
2384    public void externalRepresentation(Message callback) {
2385        mWebViewCore.sendMessage(EventHub.REQUEST_EXT_REPRESENTATION, callback);
2386    }
2387
2388    /**
2389     * {@hide}
2390     */
2391    /* FIXME: Debug only! Remove for SDK! */
2392    public void documentAsText(Message callback) {
2393        mWebViewCore.sendMessage(EventHub.REQUEST_DOC_AS_TEXT, callback);
2394    }
2395
2396    /**
2397     * Use this function to bind an object to Javascript so that the
2398     * methods can be accessed from Javascript.
2399     * <p><strong>IMPORTANT:</strong>
2400     * <ul>
2401     * <li> Using addJavascriptInterface() allows JavaScript to control your
2402     * application. This can be a very useful feature or a dangerous security
2403     * issue. When the HTML in the WebView is untrustworthy (for example, part
2404     * or all of the HTML is provided by some person or process), then an
2405     * attacker could inject HTML that will execute your code and possibly any
2406     * code of the attacker's choosing.<br>
2407     * Do not use addJavascriptInterface() unless all of the HTML in this
2408     * WebView was written by you.</li>
2409     * <li> The Java object that is bound runs in another thread and not in
2410     * the thread that it was constructed in.</li>
2411     * </ul></p>
2412     * @param obj The class instance to bind to Javascript
2413     * @param interfaceName The name to used to expose the class in Javascript
2414     */
2415    public void addJavascriptInterface(Object obj, String interfaceName) {
2416        WebViewCore.JSInterfaceData arg = new WebViewCore.JSInterfaceData();
2417        arg.mObject = obj;
2418        arg.mInterfaceName = interfaceName;
2419        mWebViewCore.sendMessage(EventHub.ADD_JS_INTERFACE, arg);
2420    }
2421
2422    /**
2423     * Return the WebSettings object used to control the settings for this
2424     * WebView.
2425     * @return A WebSettings object that can be used to control this WebView's
2426     *         settings.
2427     */
2428    public WebSettings getSettings() {
2429        return mWebViewCore.getSettings();
2430    }
2431
2432   /**
2433    * Return the list of currently loaded plugins.
2434    * @return The list of currently loaded plugins.
2435    */
2436    public static synchronized PluginList getPluginList() {
2437        if (sPluginList == null) {
2438            sPluginList = new PluginList();
2439        }
2440        return sPluginList;
2441    }
2442
2443   /**
2444     * TODO: need to add @Deprecated
2445    */
2446    public void refreshPlugins(boolean reloadOpenPages) {
2447        PluginManager.getInstance(mContext).refreshPlugins(reloadOpenPages);
2448    }
2449
2450    //-------------------------------------------------------------------------
2451    // Override View methods
2452    //-------------------------------------------------------------------------
2453
2454    @Override
2455    protected void finalize() throws Throwable {
2456        destroy();
2457    }
2458
2459    @Override
2460    protected void onDraw(Canvas canvas) {
2461        // if mNativeClass is 0, the WebView has been destroyed. Do nothing.
2462        if (mNativeClass == 0) {
2463            return;
2464        }
2465        if (mWebViewCore.mEndScaleZoom) {
2466            mWebViewCore.mEndScaleZoom = false;
2467            if (mTouchMode >= FIRST_SCROLL_ZOOM
2468                    && mTouchMode <= LAST_SCROLL_ZOOM) {
2469                setHorizontalScrollBarEnabled(true);
2470                setVerticalScrollBarEnabled(true);
2471                mTouchMode = TOUCH_DONE_MODE;
2472            }
2473        }
2474        int sc = canvas.save();
2475        if (mTouchMode >= FIRST_SCROLL_ZOOM && mTouchMode <= LAST_SCROLL_ZOOM) {
2476            scrollZoomDraw(canvas);
2477        } else {
2478            // Update the buttons in the picture, so when we draw the picture
2479            // to the screen, they are in the correct state.
2480            // Tell the native side if user is a) touching the screen,
2481            // b) pressing the trackball down, or c) pressing the enter key
2482            // If the cursor is on a button, we need to draw it in the pressed
2483            // state.
2484            // If mNativeClass is 0, we should not reach here, so we do not
2485            // need to check it again.
2486            nativeRecordButtons(hasFocus() && hasWindowFocus(),
2487                    mTouchMode == TOUCH_SHORTPRESS_START_MODE
2488                    || mTrackballDown || mGotCenterDown, false);
2489            drawCoreAndCursorRing(canvas, mBackgroundColor, mDrawCursorRing);
2490        }
2491        canvas.restoreToCount(sc);
2492
2493        if (AUTO_REDRAW_HACK && mAutoRedraw) {
2494            invalidate();
2495        }
2496    }
2497
2498    @Override
2499    public void setLayoutParams(ViewGroup.LayoutParams params) {
2500        if (params.height == LayoutParams.WRAP_CONTENT) {
2501            mWrapContent = true;
2502        }
2503        super.setLayoutParams(params);
2504    }
2505
2506    @Override
2507    public boolean performLongClick() {
2508        if (mNativeClass != 0 && nativeCursorIsTextInput()) {
2509            // Send the click so that the textfield is in focus
2510            // FIXME: When we start respecting changes to the native textfield's
2511            // selection, need to make sure that this does not change it.
2512            mWebViewCore.sendMessage(EventHub.CLICK, nativeCursorFramePointer(),
2513                    nativeCursorNodePointer());
2514            rebuildWebTextView();
2515        }
2516        if (inEditingMode()) {
2517            return mWebTextView.performLongClick();
2518        } else {
2519            return super.performLongClick();
2520        }
2521    }
2522
2523    private void drawCoreAndCursorRing(Canvas canvas, int color,
2524        boolean drawCursorRing) {
2525        if (mDrawHistory) {
2526            canvas.scale(mActualScale, mActualScale);
2527            canvas.drawPicture(mHistoryPicture);
2528            return;
2529        }
2530
2531        boolean animateZoom = mZoomScale != 0;
2532        boolean animateScroll = !mScroller.isFinished()
2533                || mVelocityTracker != null;
2534        if (animateZoom) {
2535            float zoomScale;
2536            int interval = (int) (SystemClock.uptimeMillis() - mZoomStart);
2537            if (interval < ZOOM_ANIMATION_LENGTH) {
2538                float ratio = (float) interval / ZOOM_ANIMATION_LENGTH;
2539                zoomScale = 1.0f / (mInvInitialZoomScale
2540                        + (mInvFinalZoomScale - mInvInitialZoomScale) * ratio);
2541                invalidate();
2542            } else {
2543                zoomScale = mZoomScale;
2544                // set mZoomScale to be 0 as we have done animation
2545                mZoomScale = 0;
2546            }
2547            float scale = (mActualScale - zoomScale) * mInvActualScale;
2548            float tx = scale * (mZoomCenterX + mScrollX);
2549            float ty = scale * (mZoomCenterY + mScrollY);
2550
2551            // this block pins the translate to "legal" bounds. This makes the
2552            // animation a bit non-obvious, but it means we won't pop when the
2553            // "real" zoom takes effect
2554            if (true) {
2555               // canvas.translate(mScrollX, mScrollY);
2556                tx -= mScrollX;
2557                ty -= mScrollY;
2558                tx = -pinLoc(-Math.round(tx), getViewWidth(), Math
2559                        .round(mContentWidth * zoomScale));
2560                ty = -pinLoc(-Math.round(ty), getViewHeight(), Math
2561                        .round(mContentHeight * zoomScale));
2562                tx += mScrollX;
2563                ty += mScrollY;
2564            }
2565            canvas.translate(tx, ty);
2566            canvas.scale(zoomScale, zoomScale);
2567        } else {
2568            canvas.scale(mActualScale, mActualScale);
2569        }
2570
2571        mWebViewCore.drawContentPicture(canvas, color, animateZoom,
2572                animateScroll);
2573
2574        if (mNativeClass == 0) return;
2575        if (mShiftIsPressed) {
2576            if (mTouchSelection) {
2577                nativeDrawSelectionRegion(canvas);
2578            } else {
2579                nativeDrawSelection(canvas, mSelectX, mSelectY,
2580                        mExtendSelection);
2581            }
2582        } else if (drawCursorRing) {
2583            if (mTouchMode == TOUCH_SHORTPRESS_START_MODE) {
2584                mTouchMode = TOUCH_SHORTPRESS_MODE;
2585                HitTestResult hitTest = getHitTestResult();
2586                if (hitTest != null &&
2587                        hitTest.mType != HitTestResult.UNKNOWN_TYPE) {
2588                    mPrivateHandler.sendMessageDelayed(mPrivateHandler
2589                            .obtainMessage(SWITCH_TO_LONGPRESS),
2590                            LONG_PRESS_TIMEOUT);
2591                }
2592            }
2593            nativeDrawCursorRing(canvas);
2594        }
2595        // When the FindDialog is up, only draw the matches if we are not in
2596        // the process of scrolling them into view.
2597        if (mFindIsUp && !animateScroll) {
2598            nativeDrawMatches(canvas);
2599        }
2600    }
2601
2602    private float scrollZoomGridScale(float invScale) {
2603        float griddedInvScale = (int) (invScale * SCROLL_ZOOM_GRID)
2604            / (float) SCROLL_ZOOM_GRID;
2605        return 1.0f / griddedInvScale;
2606    }
2607
2608    private float scrollZoomX(float scale) {
2609        int width = getViewWidth();
2610        float maxScrollZoomX = mContentWidth * scale - width;
2611        int maxX = mContentWidth - width;
2612        return -(maxScrollZoomX > 0 ? mZoomScrollX * maxScrollZoomX / maxX
2613                : maxScrollZoomX / 2);
2614    }
2615
2616    private float scrollZoomY(float scale) {
2617        int height = getViewHeight();
2618        float maxScrollZoomY = mContentHeight * scale - height;
2619        int maxY = mContentHeight - height;
2620        return -(maxScrollZoomY > 0 ? mZoomScrollY * maxScrollZoomY / maxY
2621                : maxScrollZoomY / 2);
2622    }
2623
2624    private void drawMagnifyFrame(Canvas canvas, Rect frame, Paint paint) {
2625        final float ADORNMENT_LEN = 16.0f;
2626        float width = frame.width();
2627        float height = frame.height();
2628        Path path = new Path();
2629        path.moveTo(-ADORNMENT_LEN, -ADORNMENT_LEN);
2630        path.lineTo(0, 0);
2631        path.lineTo(width, 0);
2632        path.lineTo(width + ADORNMENT_LEN, -ADORNMENT_LEN);
2633        path.moveTo(-ADORNMENT_LEN, height + ADORNMENT_LEN);
2634        path.lineTo(0, height);
2635        path.lineTo(width, height);
2636        path.lineTo(width + ADORNMENT_LEN, height + ADORNMENT_LEN);
2637        path.moveTo(0, 0);
2638        path.lineTo(0, height);
2639        path.moveTo(width, 0);
2640        path.lineTo(width, height);
2641        path.offset(frame.left, frame.top);
2642        canvas.drawPath(path, paint);
2643    }
2644
2645    // Returns frame surrounding magified portion of screen while
2646    // scroll-zoom is enabled. The frame is also used to center the
2647    // zoom-in zoom-out points at the start and end of the animation.
2648    private Rect scrollZoomFrame(int width, int height, float halfScale) {
2649        Rect scrollFrame = new Rect();
2650        scrollFrame.set(mZoomScrollX, mZoomScrollY,
2651                mZoomScrollX + width, mZoomScrollY + height);
2652        if (mContentWidth * mZoomScrollLimit < width) {
2653            float scale = zoomFrameScaleX(width, halfScale, 1.0f);
2654            float offsetX = (width * scale - width) * 0.5f;
2655            scrollFrame.left -= offsetX;
2656            scrollFrame.right += offsetX;
2657        }
2658        if (mContentHeight * mZoomScrollLimit < height) {
2659            float scale = zoomFrameScaleY(height, halfScale, 1.0f);
2660            float offsetY = (height * scale - height) * 0.5f;
2661            scrollFrame.top -= offsetY;
2662            scrollFrame.bottom += offsetY;
2663        }
2664        return scrollFrame;
2665    }
2666
2667    private float zoomFrameScaleX(int width, float halfScale, float noScale) {
2668        // mContentWidth > width > mContentWidth * mZoomScrollLimit
2669        if (mContentWidth <= width) {
2670            return halfScale;
2671        }
2672        float part = (width - mContentWidth * mZoomScrollLimit)
2673                / (width * (1 - mZoomScrollLimit));
2674        return halfScale * part + noScale * (1.0f - part);
2675    }
2676
2677    private float zoomFrameScaleY(int height, float halfScale, float noScale) {
2678        if (mContentHeight <= height) {
2679            return halfScale;
2680        }
2681        float part = (height - mContentHeight * mZoomScrollLimit)
2682                / (height * (1 - mZoomScrollLimit));
2683        return halfScale * part + noScale * (1.0f - part);
2684    }
2685
2686    private float scrollZoomMagScale(float invScale) {
2687        return (invScale * 2 + mInvActualScale) / 3;
2688    }
2689
2690    private void scrollZoomDraw(Canvas canvas) {
2691        float invScale = mZoomScrollInvLimit;
2692        int elapsed = 0;
2693        if (mTouchMode != SCROLL_ZOOM_OUT) {
2694            elapsed = (int) Math.min(System.currentTimeMillis()
2695                - mZoomScrollStart, SCROLL_ZOOM_DURATION);
2696            float transitionScale = (mZoomScrollInvLimit - mInvActualScale)
2697                    * elapsed / SCROLL_ZOOM_DURATION;
2698            if (mTouchMode == SCROLL_ZOOM_ANIMATION_OUT) {
2699                invScale = mInvActualScale + transitionScale;
2700            } else { /* if (mTouchMode == SCROLL_ZOOM_ANIMATION_IN) */
2701                invScale = mZoomScrollInvLimit - transitionScale;
2702            }
2703        }
2704        float scale = scrollZoomGridScale(invScale);
2705        invScale = 1.0f / scale;
2706        int width = getViewWidth();
2707        int height = getViewHeight();
2708        float halfScale = scrollZoomMagScale(invScale);
2709        Rect scrollFrame = scrollZoomFrame(width, height, halfScale);
2710        if (elapsed == SCROLL_ZOOM_DURATION) {
2711            if (mTouchMode == SCROLL_ZOOM_ANIMATION_IN) {
2712                setHorizontalScrollBarEnabled(true);
2713                setVerticalScrollBarEnabled(true);
2714                rebuildWebTextView();
2715                scrollTo((int) (scrollFrame.centerX() * mActualScale)
2716                        - (width >> 1), (int) (scrollFrame.centerY()
2717                        * mActualScale) - (height >> 1));
2718                mTouchMode = TOUCH_DONE_MODE;
2719            } else {
2720                mTouchMode = SCROLL_ZOOM_OUT;
2721            }
2722        }
2723        float newX = scrollZoomX(scale);
2724        float newY = scrollZoomY(scale);
2725        if (DebugFlags.WEB_VIEW) {
2726            Log.v(LOGTAG, "scrollZoomDraw scale=" + scale + " + (" + newX
2727                    + ", " + newY + ") mZoomScroll=(" + mZoomScrollX + ", "
2728                    + mZoomScrollY + ")" + " invScale=" + invScale + " scale="
2729                    + scale);
2730        }
2731        canvas.translate(newX, newY);
2732        canvas.scale(scale, scale);
2733        boolean animating = mTouchMode != SCROLL_ZOOM_OUT;
2734        if (mDrawHistory) {
2735            int sc = canvas.save(Canvas.CLIP_SAVE_FLAG);
2736            Rect clip = new Rect(0, 0, mHistoryPicture.getWidth(),
2737                    mHistoryPicture.getHeight());
2738            canvas.clipRect(clip, Region.Op.DIFFERENCE);
2739            canvas.drawColor(mBackgroundColor);
2740            canvas.restoreToCount(sc);
2741            canvas.drawPicture(mHistoryPicture);
2742        } else {
2743            mWebViewCore.drawContentPicture(canvas, mBackgroundColor,
2744                    animating, true);
2745        }
2746        if (mTouchMode == TOUCH_DONE_MODE) {
2747            return;
2748        }
2749        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
2750        paint.setStyle(Paint.Style.STROKE);
2751        paint.setStrokeWidth(30.0f);
2752        paint.setARGB(0x50, 0, 0, 0);
2753        int maxX = mContentWidth - width;
2754        int maxY = mContentHeight - height;
2755        if (true) { // experiment: draw hint to place finger off magnify area
2756            drawMagnifyFrame(canvas, scrollFrame, paint);
2757        } else {
2758            canvas.drawRect(scrollFrame, paint);
2759        }
2760        int sc = canvas.save();
2761        canvas.clipRect(scrollFrame);
2762        float halfX = (float) mZoomScrollX / maxX;
2763        if (mContentWidth * mZoomScrollLimit < width) {
2764            halfX = zoomFrameScaleX(width, 0.5f, halfX);
2765        }
2766        float halfY = (float) mZoomScrollY / maxY;
2767        if (mContentHeight * mZoomScrollLimit < height) {
2768            halfY = zoomFrameScaleY(height, 0.5f, halfY);
2769        }
2770        canvas.scale(halfScale, halfScale, mZoomScrollX + width * halfX
2771                , mZoomScrollY + height * halfY);
2772        if (DebugFlags.WEB_VIEW) {
2773            Log.v(LOGTAG, "scrollZoomDraw halfScale=" + halfScale + " w/h=("
2774                    + width + ", " + height + ") half=(" + halfX + ", "
2775                    + halfY + ")");
2776        }
2777        if (mDrawHistory) {
2778            canvas.drawPicture(mHistoryPicture);
2779        } else {
2780            mWebViewCore.drawContentPicture(canvas, mBackgroundColor,
2781                    animating, false);
2782        }
2783        canvas.restoreToCount(sc);
2784        if (mTouchMode != SCROLL_ZOOM_OUT) {
2785            invalidate();
2786        }
2787    }
2788
2789    private void zoomScrollTap(float x, float y) {
2790        float scale = scrollZoomGridScale(mZoomScrollInvLimit);
2791        float left = scrollZoomX(scale);
2792        float top = scrollZoomY(scale);
2793        int width = getViewWidth();
2794        int height = getViewHeight();
2795        x -= width * scale / 2;
2796        y -= height * scale / 2;
2797        mZoomScrollX = Math.min(mContentWidth - width
2798                , Math.max(0, (int) ((x - left) / scale)));
2799        mZoomScrollY = Math.min(mContentHeight - height
2800                , Math.max(0, (int) ((y - top) / scale)));
2801        if (DebugFlags.WEB_VIEW) {
2802            Log.v(LOGTAG, "zoomScrollTap scale=" + scale + " + (" + left
2803                    + ", " + top + ") mZoomScroll=(" + mZoomScrollX + ", "
2804                    + mZoomScrollY + ")" + " x=" + x + " y=" + y);
2805        }
2806    }
2807
2808    /**
2809     * @hide
2810     */
2811    public boolean canZoomScrollOut() {
2812        if (mContentWidth == 0 || mContentHeight == 0) {
2813            return false;
2814        }
2815        int width = getViewWidth();
2816        int height = getViewHeight();
2817        float x = (float) width / (float) mContentWidth;
2818        float y = (float) height / (float) mContentHeight;
2819        mZoomScrollLimit = Math.max(DEFAULT_MIN_ZOOM_SCALE, Math.min(x, y));
2820        mZoomScrollInvLimit = 1.0f / mZoomScrollLimit;
2821        if (DebugFlags.WEB_VIEW) {
2822            Log.v(LOGTAG, "canZoomScrollOut"
2823                    + " mInvActualScale=" + mInvActualScale
2824                    + " mZoomScrollLimit=" + mZoomScrollLimit
2825                    + " mZoomScrollInvLimit=" + mZoomScrollInvLimit
2826                    + " mContentWidth=" + mContentWidth
2827                    + " mContentHeight=" + mContentHeight
2828                    );
2829        }
2830        // don't zoom out unless magnify area is at least half as wide
2831        // or tall as content
2832        float limit = mZoomScrollLimit * 2;
2833        return mContentWidth >= width * limit
2834                || mContentHeight >= height * limit;
2835    }
2836
2837    private void startZoomScrollOut() {
2838        setHorizontalScrollBarEnabled(false);
2839        setVerticalScrollBarEnabled(false);
2840        if (getSettings().getBuiltInZoomControls()) {
2841            if (mZoomButtonsController.isVisible()) {
2842                mZoomButtonsController.setVisible(false);
2843            }
2844        } else {
2845            if (mZoomControlRunnable != null) {
2846                mPrivateHandler.removeCallbacks(mZoomControlRunnable);
2847            }
2848            if (mZoomControls != null) {
2849                mZoomControls.hide();
2850            }
2851        }
2852        int width = getViewWidth();
2853        int height = getViewHeight();
2854        int halfW = width >> 1;
2855        mLastTouchX = halfW;
2856        int halfH = height >> 1;
2857        mLastTouchY = halfH;
2858        mScroller.abortAnimation();
2859        mZoomScrollStart = System.currentTimeMillis();
2860        Rect zoomFrame = scrollZoomFrame(width, height
2861                , scrollZoomMagScale(mZoomScrollInvLimit));
2862        mZoomScrollX = Math.max(0, (int) ((mScrollX + halfW) * mInvActualScale)
2863                - (zoomFrame.width() >> 1));
2864        mZoomScrollY = Math.max(0, (int) ((mScrollY + halfH) * mInvActualScale)
2865                - (zoomFrame.height() >> 1));
2866        scrollTo(0, 0); // triggers inval, starts animation
2867        clearTextEntry();
2868        if (DebugFlags.WEB_VIEW) {
2869            Log.v(LOGTAG, "startZoomScrollOut mZoomScroll=("
2870                    + mZoomScrollX + ", " + mZoomScrollY +")");
2871        }
2872    }
2873
2874    /**
2875     * @hide
2876     */
2877    public void zoomScrollOut() {
2878        if (canZoomScrollOut() == false) {
2879            mTouchMode = TOUCH_DONE_MODE;
2880            return;
2881        }
2882        startZoomScrollOut();
2883        mTouchMode = SCROLL_ZOOM_ANIMATION_OUT;
2884        invalidate();
2885    }
2886
2887    private void moveZoomScrollWindow(float x, float y) {
2888        if (Math.abs(x - mLastZoomScrollRawX) < 1.5f
2889                && Math.abs(y - mLastZoomScrollRawY) < 1.5f) {
2890            return;
2891        }
2892        mLastZoomScrollRawX = x;
2893        mLastZoomScrollRawY = y;
2894        int oldX = mZoomScrollX;
2895        int oldY = mZoomScrollY;
2896        int width = getViewWidth();
2897        int height = getViewHeight();
2898        int maxZoomX = mContentWidth - width;
2899        if (maxZoomX > 0) {
2900            int maxScreenX = width - (int) Math.ceil(width
2901                    * mZoomScrollLimit) - SCROLL_ZOOM_FINGER_BUFFER;
2902            if (DebugFlags.WEB_VIEW) {
2903                Log.v(LOGTAG, "moveZoomScrollWindow-X"
2904                        + " maxScreenX=" + maxScreenX + " width=" + width
2905                        + " mZoomScrollLimit=" + mZoomScrollLimit + " x=" + x);
2906            }
2907            x += maxScreenX * mLastScrollX / maxZoomX - mLastTouchX;
2908            x *= Math.max(maxZoomX / maxScreenX, mZoomScrollInvLimit);
2909            mZoomScrollX = Math.max(0, Math.min(maxZoomX, (int) x));
2910        }
2911        int maxZoomY = mContentHeight - height;
2912        if (maxZoomY > 0) {
2913            int maxScreenY = height - (int) Math.ceil(height
2914                    * mZoomScrollLimit) - SCROLL_ZOOM_FINGER_BUFFER;
2915            if (DebugFlags.WEB_VIEW) {
2916                Log.v(LOGTAG, "moveZoomScrollWindow-Y"
2917                        + " maxScreenY=" + maxScreenY + " height=" + height
2918                        + " mZoomScrollLimit=" + mZoomScrollLimit + " y=" + y);
2919            }
2920            y += maxScreenY * mLastScrollY / maxZoomY - mLastTouchY;
2921            y *= Math.max(maxZoomY / maxScreenY, mZoomScrollInvLimit);
2922            mZoomScrollY = Math.max(0, Math.min(maxZoomY, (int) y));
2923        }
2924        if (oldX != mZoomScrollX || oldY != mZoomScrollY) {
2925            invalidate();
2926        }
2927        if (DebugFlags.WEB_VIEW) {
2928            Log.v(LOGTAG, "moveZoomScrollWindow"
2929                    + " scrollTo=(" + mZoomScrollX + ", " + mZoomScrollY + ")"
2930                    + " mLastTouch=(" + mLastTouchX + ", " + mLastTouchY + ")"
2931                    + " maxZoom=(" + maxZoomX + ", " + maxZoomY + ")"
2932                    + " last=("+mLastScrollX+", "+mLastScrollY+")"
2933                    + " x=" + x + " y=" + y);
2934        }
2935    }
2936
2937    private void setZoomScrollIn() {
2938        mZoomScrollStart = System.currentTimeMillis();
2939    }
2940
2941    private float mZoomScrollLimit;
2942    private float mZoomScrollInvLimit;
2943    private int mLastScrollX;
2944    private int mLastScrollY;
2945    private long mZoomScrollStart;
2946    private int mZoomScrollX;
2947    private int mZoomScrollY;
2948    private float mLastZoomScrollRawX = -1000.0f;
2949    private float mLastZoomScrollRawY = -1000.0f;
2950    // The zoomed scale varies from 1.0 to DEFAULT_MIN_ZOOM_SCALE == 0.25.
2951    // The zoom animation duration SCROLL_ZOOM_DURATION == 0.5.
2952    // Two pressures compete for gridding; a high frame rate (e.g. 20 fps)
2953    // and minimizing font cache allocations (fewer frames is better).
2954    // A SCROLL_ZOOM_GRID of 6 permits about 20 zoom levels over 0.5 seconds:
2955    // the inverse of: 1.0, 1.16, 1.33, 1.5, 1.67, 1.84, 2.0, etc. to 4.0
2956    private static final int SCROLL_ZOOM_GRID = 6;
2957    private static final int SCROLL_ZOOM_DURATION = 500;
2958    // Make it easier to get to the bottom of a document by reserving a 32
2959    // pixel buffer, for when the starting drag is a bit below the bottom of
2960    // the magnify frame.
2961    private static final int SCROLL_ZOOM_FINGER_BUFFER = 32;
2962
2963    // draw history
2964    private boolean mDrawHistory = false;
2965    private Picture mHistoryPicture = null;
2966    private int mHistoryWidth = 0;
2967    private int mHistoryHeight = 0;
2968
2969    // Only check the flag, can be called from WebCore thread
2970    boolean drawHistory() {
2971        return mDrawHistory;
2972    }
2973
2974    // Should only be called in UI thread
2975    void switchOutDrawHistory() {
2976        if (null == mWebViewCore) return; // CallbackProxy may trigger this
2977        if (mDrawHistory && mWebViewCore.pictureReady()) {
2978            mDrawHistory = false;
2979            invalidate();
2980            int oldScrollX = mScrollX;
2981            int oldScrollY = mScrollY;
2982            mScrollX = pinLocX(mScrollX);
2983            mScrollY = pinLocY(mScrollY);
2984            if (oldScrollX != mScrollX || oldScrollY != mScrollY) {
2985                mUserScroll = false;
2986                mWebViewCore.sendMessage(EventHub.SYNC_SCROLL, oldScrollX,
2987                        oldScrollY);
2988            }
2989            sendOurVisibleRect();
2990        }
2991    }
2992
2993    WebViewCore.CursorData cursorData() {
2994        WebViewCore.CursorData result = new WebViewCore.CursorData();
2995        result.mMoveGeneration = nativeMoveGeneration();
2996        result.mFrame = nativeCursorFramePointer();
2997        Point position = nativeCursorPosition();
2998        result.mX = position.x;
2999        result.mY = position.y;
3000        return result;
3001    }
3002
3003    /**
3004     *  Delete text from start to end in the focused textfield. If there is no
3005     *  focus, or if start == end, silently fail.  If start and end are out of
3006     *  order, swap them.
3007     *  @param  start   Beginning of selection to delete.
3008     *  @param  end     End of selection to delete.
3009     */
3010    /* package */ void deleteSelection(int start, int end) {
3011        mTextGeneration++;
3012        mWebViewCore.sendMessage(EventHub.DELETE_SELECTION, start, end);
3013    }
3014
3015    /**
3016     *  Set the selection to (start, end) in the focused textfield. If start and
3017     *  end are out of order, swap them.
3018     *  @param  start   Beginning of selection.
3019     *  @param  end     End of selection.
3020     */
3021    /* package */ void setSelection(int start, int end) {
3022        mWebViewCore.sendMessage(EventHub.SET_SELECTION, start, end);
3023    }
3024
3025    // Called by JNI when a touch event puts a textfield into focus.
3026    private void displaySoftKeyboard(boolean isTextView) {
3027        InputMethodManager imm = (InputMethodManager)
3028                getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
3029
3030        if (isTextView) {
3031            imm.showSoftInput(mWebTextView, 0);
3032            mWebTextView.enableScrollOnScreen(true);
3033            // Now we need to fake a touch event to place the cursor where the
3034            // user touched.
3035            AbsoluteLayout.LayoutParams lp = (AbsoluteLayout.LayoutParams)
3036                    mWebTextView.getLayoutParams();
3037            if (lp != null) {
3038                // Take the last touch and adjust for the location of the
3039                // WebTextView.
3040                float x = mLastTouchX + (float) (mScrollX - lp.x);
3041                float y = mLastTouchY + (float) (mScrollY - lp.y);
3042                mWebTextView.fakeTouchEvent(x, y);
3043            }
3044        }
3045        else { // used by plugins
3046            imm.showSoftInput(this, 0);
3047        }
3048    }
3049
3050    // Called by WebKit to instruct the UI to hide the keyboard
3051    private void hideSoftKeyboard() {
3052        InputMethodManager imm = (InputMethodManager)
3053                getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
3054
3055        imm.hideSoftInputFromWindow(this.getWindowToken(), 0);
3056    }
3057
3058    /*
3059     * This method checks the current focus and cursor and potentially rebuilds
3060     * mWebTextView to have the appropriate properties, such as password,
3061     * multiline, and what text it contains.  It also removes it if necessary.
3062     */
3063    private void rebuildWebTextView() {
3064        // If the WebView does not have focus, do nothing until it gains focus.
3065        if (!hasFocus() && (null == mWebTextView || !mWebTextView.hasFocus())
3066                || (mTouchMode >= FIRST_SCROLL_ZOOM
3067                && mTouchMode <= LAST_SCROLL_ZOOM)) {
3068            return;
3069        }
3070        boolean alreadyThere = inEditingMode();
3071        // inEditingMode can only return true if mWebTextView is non-null,
3072        // so we can safely call remove() if (alreadyThere)
3073        if (0 == mNativeClass || !nativeFocusCandidateIsTextInput()) {
3074            if (alreadyThere) {
3075                mWebTextView.remove();
3076            }
3077            return;
3078        }
3079        // At this point, we know we have found an input field, so go ahead
3080        // and create the WebTextView if necessary.
3081        if (mWebTextView == null) {
3082            mWebTextView = new WebTextView(mContext, WebView.this);
3083            // Initialize our generation number.
3084            mTextGeneration = 0;
3085        }
3086        mWebTextView.setTextSize(contentToView(nativeFocusCandidateTextSize()));
3087        Rect visibleRect = new Rect();
3088        calcOurContentVisibleRect(visibleRect);
3089        // Note that sendOurVisibleRect calls viewToContent, so the coordinates
3090        // should be in content coordinates.
3091        Rect bounds = nativeFocusCandidateNodeBounds();
3092        if (!Rect.intersects(bounds, visibleRect)) {
3093            // Node is not on screen, so do not bother.
3094            return;
3095        }
3096        String text = nativeFocusCandidateText();
3097        int nodePointer = nativeFocusCandidatePointer();
3098        if (alreadyThere && mWebTextView.isSameTextField(nodePointer)) {
3099            // It is possible that we have the same textfield, but it has moved,
3100            // i.e. In the case of opening/closing the screen.
3101            // In that case, we need to set the dimensions, but not the other
3102            // aspects.
3103            // We also need to restore the selection, which gets wrecked by
3104            // calling setTextEntryRect.
3105            Spannable spannable = (Spannable) mWebTextView.getText();
3106            int start = Selection.getSelectionStart(spannable);
3107            int end = Selection.getSelectionEnd(spannable);
3108            // If the text has been changed by webkit, update it.  However, if
3109            // there has been more UI text input, ignore it.  We will receive
3110            // another update when that text is recognized.
3111            if (text != null && !text.equals(spannable.toString())
3112                    && nativeTextGeneration() == mTextGeneration) {
3113                mWebTextView.setTextAndKeepSelection(text);
3114            } else {
3115                Selection.setSelection(spannable, start, end);
3116            }
3117        } else {
3118            Rect vBox = contentToView(bounds);
3119            mWebTextView.setRect(vBox.left, vBox.top, vBox.width(),
3120                    vBox.height());
3121            mWebTextView.setGravity(nativeFocusCandidateIsRtlText() ?
3122                    Gravity.RIGHT : Gravity.NO_GRAVITY);
3123            // this needs to be called before update adapter thread starts to
3124            // ensure the mWebTextView has the same node pointer
3125            mWebTextView.setNodePointer(nodePointer);
3126            int maxLength = -1;
3127            boolean isTextField = nativeFocusCandidateIsTextField();
3128            if (isTextField) {
3129                maxLength = nativeFocusCandidateMaxLength();
3130                String name = nativeFocusCandidateName();
3131                if (mWebViewCore.getSettings().getSaveFormData()
3132                        && name != null) {
3133                    Message update = mPrivateHandler.obtainMessage(
3134                            REQUEST_FORM_DATA, nodePointer);
3135                    RequestFormData updater = new RequestFormData(name,
3136                            getUrl(), update);
3137                    Thread t = new Thread(updater);
3138                    t.start();
3139                }
3140            }
3141            mWebTextView.setMaxLength(maxLength);
3142            AutoCompleteAdapter adapter = null;
3143            mWebTextView.setAdapterCustom(adapter);
3144            mWebTextView.setSingleLine(isTextField);
3145            mWebTextView.setInPassword(nativeFocusCandidateIsPassword());
3146            if (null == text) {
3147                mWebTextView.setText("", 0, 0);
3148                if (DebugFlags.WEB_VIEW) {
3149                    Log.v(LOGTAG, "rebuildWebTextView null == text");
3150                }
3151            } else {
3152                // Change to true to enable the old style behavior, where
3153                // entering a textfield/textarea always set the selection to the
3154                // whole field.  This was desirable for the case where the user
3155                // intends to scroll past the field using the trackball.
3156                // However, it causes a problem when replying to emails - the
3157                // user expects the cursor to be at the beginning of the
3158                // textarea.  Testing out a new behavior, where textfields set
3159                // selection at the end, and textareas at the beginning.
3160                if (false) {
3161                    mWebTextView.setText(text, 0, text.length());
3162                } else if (isTextField) {
3163                    int length = text.length();
3164                    mWebTextView.setText(text, length, length);
3165                    if (DebugFlags.WEB_VIEW) {
3166                        Log.v(LOGTAG, "rebuildWebTextView length=" + length);
3167                    }
3168                } else {
3169                    mWebTextView.setText(text, 0, 0);
3170                    if (DebugFlags.WEB_VIEW) {
3171                        Log.v(LOGTAG, "rebuildWebTextView !isTextField");
3172                    }
3173                }
3174            }
3175            mWebTextView.requestFocus();
3176        }
3177    }
3178
3179    /*
3180     * This class requests an Adapter for the WebTextView which shows past
3181     * entries stored in the database.  It is a Runnable so that it can be done
3182     * in its own thread, without slowing down the UI.
3183     */
3184    private class RequestFormData implements Runnable {
3185        private String mName;
3186        private String mUrl;
3187        private Message mUpdateMessage;
3188
3189        public RequestFormData(String name, String url, Message msg) {
3190            mName = name;
3191            mUrl = url;
3192            mUpdateMessage = msg;
3193        }
3194
3195        public void run() {
3196            ArrayList<String> pastEntries = mDatabase.getFormData(mUrl, mName);
3197            if (pastEntries.size() > 0) {
3198                AutoCompleteAdapter adapter = new
3199                        AutoCompleteAdapter(mContext, pastEntries);
3200                mUpdateMessage.obj = adapter;
3201                mUpdateMessage.sendToTarget();
3202            }
3203        }
3204    }
3205
3206    // This is used to determine long press with the center key.  Does not
3207    // affect long press with the trackball/touch.
3208    private boolean mGotCenterDown = false;
3209
3210    @Override
3211    public boolean onKeyDown(int keyCode, KeyEvent event) {
3212        if (DebugFlags.WEB_VIEW) {
3213            Log.v(LOGTAG, "keyDown at " + System.currentTimeMillis()
3214                    + ", " + event + ", unicode=" + event.getUnicodeChar());
3215        }
3216
3217        if (mNativeClass == 0) {
3218            return false;
3219        }
3220
3221        // do this hack up front, so it always works, regardless of touch-mode
3222        if (AUTO_REDRAW_HACK && (keyCode == KeyEvent.KEYCODE_CALL)) {
3223            mAutoRedraw = !mAutoRedraw;
3224            if (mAutoRedraw) {
3225                invalidate();
3226            }
3227            return true;
3228        }
3229
3230        // Bubble up the key event if
3231        // 1. it is a system key; or
3232        // 2. the host application wants to handle it; or
3233        // 3. webview is in scroll-zoom state;
3234        if (event.isSystem()
3235                || mCallbackProxy.uiOverrideKeyEvent(event)
3236                || (mTouchMode >= FIRST_SCROLL_ZOOM && mTouchMode <= LAST_SCROLL_ZOOM)) {
3237            return false;
3238        }
3239
3240        if (mShiftIsPressed == false && nativeCursorWantsKeyEvents() == false
3241                && (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT
3242                || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT)) {
3243            mExtendSelection = false;
3244            mShiftIsPressed = true;
3245            if (nativeHasCursorNode()) {
3246                Rect rect = nativeCursorNodeBounds();
3247                mSelectX = contentToView(rect.left);
3248                mSelectY = contentToView(rect.top);
3249            } else {
3250                mSelectX = mScrollX + (int) mLastTouchX;
3251                mSelectY = mScrollY + (int) mLastTouchY;
3252            }
3253            nativeHideCursor();
3254       }
3255
3256        if (keyCode >= KeyEvent.KEYCODE_DPAD_UP
3257                && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) {
3258            // always handle the navigation keys in the UI thread
3259            switchOutDrawHistory();
3260            if (navHandledKey(keyCode, 1, false, event.getEventTime(), false)) {
3261                playSoundEffect(keyCodeToSoundsEffect(keyCode));
3262                return true;
3263            }
3264            // Bubble up the key event as WebView doesn't handle it
3265            return false;
3266        }
3267
3268        if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
3269            switchOutDrawHistory();
3270            if (event.getRepeatCount() == 0) {
3271                mGotCenterDown = true;
3272                mPrivateHandler.sendMessageDelayed(mPrivateHandler
3273                        .obtainMessage(LONG_PRESS_CENTER), LONG_PRESS_TIMEOUT);
3274                // Already checked mNativeClass, so we do not need to check it
3275                // again.
3276                nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true);
3277                return true;
3278            }
3279            // Bubble up the key event as WebView doesn't handle it
3280            return false;
3281        }
3282
3283        if (keyCode != KeyEvent.KEYCODE_SHIFT_LEFT
3284                && keyCode != KeyEvent.KEYCODE_SHIFT_RIGHT) {
3285            // turn off copy select if a shift-key combo is pressed
3286            mExtendSelection = mShiftIsPressed = false;
3287            if (mTouchMode == TOUCH_SELECT_MODE) {
3288                mTouchMode = TOUCH_INIT_MODE;
3289            }
3290        }
3291
3292        if (getSettings().getNavDump()) {
3293            switch (keyCode) {
3294                case KeyEvent.KEYCODE_4:
3295                    // "/data/data/com.android.browser/displayTree.txt"
3296                    nativeDumpDisplayTree(getUrl());
3297                    break;
3298                case KeyEvent.KEYCODE_5:
3299                case KeyEvent.KEYCODE_6:
3300                    // 5: dump the dom tree to the file
3301                    // "/data/data/com.android.browser/domTree.txt"
3302                    // 6: dump the dom tree to the adb log
3303                    mWebViewCore.sendMessage(EventHub.DUMP_DOMTREE,
3304                            (keyCode == KeyEvent.KEYCODE_5) ? 1 : 0, 0);
3305                    break;
3306                case KeyEvent.KEYCODE_7:
3307                case KeyEvent.KEYCODE_8:
3308                    // 7: dump the render tree to the file
3309                    // "/data/data/com.android.browser/renderTree.txt"
3310                    // 8: dump the render tree to the adb log
3311                    mWebViewCore.sendMessage(EventHub.DUMP_RENDERTREE,
3312                            (keyCode == KeyEvent.KEYCODE_7) ? 1 : 0, 0);
3313                    break;
3314                case KeyEvent.KEYCODE_9:
3315                    nativeInstrumentReport();
3316                    return true;
3317            }
3318        }
3319
3320        if (nativeCursorIsPlugin()) {
3321            nativeUpdatePluginReceivesEvents();
3322            invalidate();
3323        } else if (nativeCursorIsTextInput()) {
3324            // This message will put the node in focus, for the DOM's notion
3325            // of focus, and make the focuscontroller active
3326            mWebViewCore.sendMessage(EventHub.CLICK);
3327            // This will bring up the WebTextView and put it in focus, for
3328            // our view system's notion of focus
3329            rebuildWebTextView();
3330            // Now we need to pass the event to it
3331            return mWebTextView.onKeyDown(keyCode, event);
3332        }
3333
3334        // TODO: should we pass all the keys to DOM or check the meta tag
3335        if (nativeCursorWantsKeyEvents() || true) {
3336            // pass the key to DOM
3337            mWebViewCore.sendMessage(EventHub.KEY_DOWN, event);
3338            // return true as DOM handles the key
3339            return true;
3340        }
3341
3342        // Bubble up the key event as WebView doesn't handle it
3343        return false;
3344    }
3345
3346    @Override
3347    public boolean onKeyUp(int keyCode, KeyEvent event) {
3348        if (DebugFlags.WEB_VIEW) {
3349            Log.v(LOGTAG, "keyUp at " + System.currentTimeMillis()
3350                    + ", " + event + ", unicode=" + event.getUnicodeChar());
3351        }
3352
3353        if (mNativeClass == 0) {
3354            return false;
3355        }
3356
3357        // special CALL handling when cursor node's href is "tel:XXX"
3358        if (keyCode == KeyEvent.KEYCODE_CALL && nativeHasCursorNode()) {
3359            String text = nativeCursorText();
3360            if (!nativeCursorIsTextInput() && text != null
3361                    && text.startsWith(SCHEME_TEL)) {
3362                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(text));
3363                getContext().startActivity(intent);
3364                return true;
3365            }
3366        }
3367
3368        // Bubble up the key event if
3369        // 1. it is a system key; or
3370        // 2. the host application wants to handle it;
3371        if (event.isSystem() || mCallbackProxy.uiOverrideKeyEvent(event)) {
3372            return false;
3373        }
3374
3375        // special handling in scroll_zoom state
3376        if (mTouchMode >= FIRST_SCROLL_ZOOM && mTouchMode <= LAST_SCROLL_ZOOM) {
3377            if (KeyEvent.KEYCODE_DPAD_CENTER == keyCode
3378                    && mTouchMode != SCROLL_ZOOM_ANIMATION_IN) {
3379                setZoomScrollIn();
3380                mTouchMode = SCROLL_ZOOM_ANIMATION_IN;
3381                invalidate();
3382                return true;
3383            }
3384            return false;
3385        }
3386
3387        if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT
3388                || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT) {
3389            if (commitCopy()) {
3390                return true;
3391            }
3392        }
3393
3394        if (keyCode >= KeyEvent.KEYCODE_DPAD_UP
3395                && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) {
3396            // always handle the navigation keys in the UI thread
3397            // Bubble up the key event as WebView doesn't handle it
3398            return false;
3399        }
3400
3401        if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
3402            // remove the long press message first
3403            mPrivateHandler.removeMessages(LONG_PRESS_CENTER);
3404            mGotCenterDown = false;
3405
3406            if (mShiftIsPressed) {
3407                return false;
3408            }
3409            if (getSettings().supportZoom()
3410                    && mTouchMode == TOUCH_DOUBLECLICK_MODE) {
3411                zoomScrollOut();
3412            } else {
3413                mPrivateHandler.sendMessageDelayed(mPrivateHandler
3414                        .obtainMessage(SWITCH_TO_CLICK), TAP_TIMEOUT);
3415                if (DebugFlags.WEB_VIEW) {
3416                    Log.v(LOGTAG, "TOUCH_DOUBLECLICK_MODE");
3417                }
3418                mTouchMode = TOUCH_DOUBLECLICK_MODE;
3419            }
3420            return true;
3421        }
3422
3423        // TODO: should we pass all the keys to DOM or check the meta tag
3424        if (nativeCursorWantsKeyEvents() || true) {
3425            // pass the key to DOM
3426            mWebViewCore.sendMessage(EventHub.KEY_UP, event);
3427            // return true as DOM handles the key
3428            return true;
3429        }
3430
3431        // Bubble up the key event as WebView doesn't handle it
3432        return false;
3433    }
3434
3435    /**
3436     * @hide
3437     */
3438    public void emulateShiftHeld() {
3439        mExtendSelection = false;
3440        mShiftIsPressed = true;
3441        nativeHideCursor();
3442    }
3443
3444    private boolean commitCopy() {
3445        boolean copiedSomething = false;
3446        if (mExtendSelection) {
3447            // copy region so core operates on copy without touching orig.
3448            Region selection = new Region(nativeGetSelection());
3449            if (selection.isEmpty() == false) {
3450                Toast.makeText(mContext
3451                        , com.android.internal.R.string.text_copied
3452                        , Toast.LENGTH_SHORT).show();
3453                mWebViewCore.sendMessage(EventHub.GET_SELECTION, selection);
3454                copiedSomething = true;
3455            }
3456            mExtendSelection = false;
3457        }
3458        mShiftIsPressed = false;
3459        if (mTouchMode == TOUCH_SELECT_MODE) {
3460            mTouchMode = TOUCH_INIT_MODE;
3461        }
3462        return copiedSomething;
3463    }
3464
3465    // Set this as a hierarchy change listener so we can know when this view
3466    // is removed and still have access to our parent.
3467    @Override
3468    protected void onAttachedToWindow() {
3469        super.onAttachedToWindow();
3470        ViewParent parent = getParent();
3471        if (parent instanceof ViewGroup) {
3472            ViewGroup p = (ViewGroup) parent;
3473            p.setOnHierarchyChangeListener(this);
3474        }
3475    }
3476
3477    @Override
3478    protected void onDetachedFromWindow() {
3479        super.onDetachedFromWindow();
3480        ViewParent parent = getParent();
3481        if (parent instanceof ViewGroup) {
3482            ViewGroup p = (ViewGroup) parent;
3483            p.setOnHierarchyChangeListener(null);
3484        }
3485
3486        // Clean up the zoom controller
3487        mZoomButtonsController.setVisible(false);
3488    }
3489
3490    // Implementation for OnHierarchyChangeListener
3491    public void onChildViewAdded(View parent, View child) {}
3492
3493    public void onChildViewRemoved(View p, View child) {
3494        if (child == this) {
3495            clearTextEntry();
3496        }
3497    }
3498
3499    /**
3500     * @deprecated WebView should not have implemented
3501     * ViewTreeObserver.OnGlobalFocusChangeListener.  This method
3502     * does nothing now.
3503     */
3504    @Deprecated
3505    public void onGlobalFocusChanged(View oldFocus, View newFocus) {
3506    }
3507
3508    // To avoid drawing the cursor ring, and remove the TextView when our window
3509    // loses focus.
3510    @Override
3511    public void onWindowFocusChanged(boolean hasWindowFocus) {
3512        if (hasWindowFocus) {
3513            if (hasFocus()) {
3514                // If our window regained focus, and we have focus, then begin
3515                // drawing the cursor ring
3516                mDrawCursorRing = true;
3517                if (mNativeClass != 0) {
3518                    nativeRecordButtons(true, false, true);
3519                    if (inEditingMode()) {
3520                        mWebViewCore.sendMessage(EventHub.SET_ACTIVE, 1, 0);
3521                    }
3522                }
3523            } else {
3524                // If our window gained focus, but we do not have it, do not
3525                // draw the cursor ring.
3526                mDrawCursorRing = false;
3527                // We do not call nativeRecordButtons here because we assume
3528                // that when we lost focus, or window focus, it got called with
3529                // false for the first parameter
3530            }
3531        } else {
3532            if (getSettings().getBuiltInZoomControls() && !mZoomButtonsController.isVisible()) {
3533                /*
3534                 * The zoom controls come in their own window, so our window
3535                 * loses focus. Our policy is to not draw the cursor ring if
3536                 * our window is not focused, but this is an exception since
3537                 * the user can still navigate the web page with the zoom
3538                 * controls showing.
3539                 */
3540                // If our window has lost focus, stop drawing the cursor ring
3541                mDrawCursorRing = false;
3542            }
3543            mGotKeyDown = false;
3544            mShiftIsPressed = false;
3545            if (mNativeClass != 0) {
3546                nativeRecordButtons(false, false, true);
3547            }
3548            setFocusControllerInactive();
3549        }
3550        invalidate();
3551        super.onWindowFocusChanged(hasWindowFocus);
3552    }
3553
3554    /*
3555     * Pass a message to WebCore Thread, telling the WebCore::Page's
3556     * FocusController to be  "inactive" so that it will
3557     * not draw the blinking cursor.  It gets set to "active" to draw the cursor
3558     * in WebViewCore.cpp, when the WebCore thread receives key events/clicks.
3559     */
3560    private void setFocusControllerInactive() {
3561        // Do not need to also check whether mWebViewCore is null, because
3562        // mNativeClass is only set if mWebViewCore is non null
3563        if (mNativeClass == 0) return;
3564        mWebViewCore.sendMessage(EventHub.SET_ACTIVE, 0, 0);
3565    }
3566
3567    @Override
3568    protected void onFocusChanged(boolean focused, int direction,
3569            Rect previouslyFocusedRect) {
3570        if (DebugFlags.WEB_VIEW) {
3571            Log.v(LOGTAG, "MT focusChanged " + focused + ", " + direction);
3572        }
3573        if (focused) {
3574            // When we regain focus, if we have window focus, resume drawing
3575            // the cursor ring
3576            if (hasWindowFocus()) {
3577                mDrawCursorRing = true;
3578                if (mNativeClass != 0) {
3579                    nativeRecordButtons(true, false, true);
3580                }
3581            //} else {
3582                // The WebView has gained focus while we do not have
3583                // windowfocus.  When our window lost focus, we should have
3584                // called nativeRecordButtons(false...)
3585            }
3586        } else {
3587            // When we lost focus, unless focus went to the TextView (which is
3588            // true if we are in editing mode), stop drawing the cursor ring.
3589            if (!inEditingMode()) {
3590                mDrawCursorRing = false;
3591                if (mNativeClass != 0) {
3592                    nativeRecordButtons(false, false, true);
3593                }
3594                setFocusControllerInactive();
3595            }
3596            mGotKeyDown = false;
3597        }
3598
3599        super.onFocusChanged(focused, direction, previouslyFocusedRect);
3600    }
3601
3602    @Override
3603    protected void onSizeChanged(int w, int h, int ow, int oh) {
3604        super.onSizeChanged(w, h, ow, oh);
3605        // Center zooming to the center of the screen.
3606        mZoomCenterX = getViewWidth() * .5f;
3607        mZoomCenterY = getViewHeight() * .5f;
3608
3609        // update mMinZoomScale if the minimum zoom scale is not fixed
3610        if (!mMinZoomScaleFixed) {
3611            mMinZoomScale = (float) getViewWidth()
3612                    / Math.max(ZOOM_OUT_WIDTH, mContentWidth);
3613        }
3614
3615        // we always force, in case our height changed, in which case we still
3616        // want to send the notification over to webkit
3617        setNewZoomScale(mActualScale, true);
3618    }
3619
3620    @Override
3621    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
3622        super.onScrollChanged(l, t, oldl, oldt);
3623        sendOurVisibleRect();
3624    }
3625
3626
3627    @Override
3628    public boolean dispatchKeyEvent(KeyEvent event) {
3629        boolean dispatch = true;
3630
3631        if (!inEditingMode()) {
3632            if (event.getAction() == KeyEvent.ACTION_DOWN) {
3633                mGotKeyDown = true;
3634            } else {
3635                if (!mGotKeyDown) {
3636                    /*
3637                     * We got a key up for which we were not the recipient of
3638                     * the original key down. Don't give it to the view.
3639                     */
3640                    dispatch = false;
3641                }
3642                mGotKeyDown = false;
3643            }
3644        }
3645
3646        if (dispatch) {
3647            return super.dispatchKeyEvent(event);
3648        } else {
3649            // We didn't dispatch, so let something else handle the key
3650            return false;
3651        }
3652    }
3653
3654    // Here are the snap align logic:
3655    // 1. If it starts nearly horizontally or vertically, snap align;
3656    // 2. If there is a dramitic direction change, let it go;
3657    // 3. If there is a same direction back and forth, lock it.
3658
3659    // adjustable parameters
3660    private int mMinLockSnapReverseDistance;
3661    private static final float MAX_SLOPE_FOR_DIAG = 1.5f;
3662    private static final int MIN_BREAK_SNAP_CROSS_DISTANCE = 80;
3663
3664    @Override
3665    public boolean onTouchEvent(MotionEvent ev) {
3666        if (mNativeClass == 0 || !isClickable() || !isLongClickable()) {
3667            return false;
3668        }
3669
3670        if (DebugFlags.WEB_VIEW) {
3671            Log.v(LOGTAG, ev + " at " + ev.getEventTime() + " mTouchMode="
3672                    + mTouchMode);
3673        }
3674
3675        int action = ev.getAction();
3676        float x = ev.getX();
3677        float y = ev.getY();
3678        long eventTime = ev.getEventTime();
3679
3680        // Due to the touch screen edge effect, a touch closer to the edge
3681        // always snapped to the edge. As getViewWidth() can be different from
3682        // getWidth() due to the scrollbar, adjusting the point to match
3683        // getViewWidth(). Same applied to the height.
3684        if (x > getViewWidth() - 1) {
3685            x = getViewWidth() - 1;
3686        }
3687        if (y > getViewHeight() - 1) {
3688            y = getViewHeight() - 1;
3689        }
3690
3691        // pass the touch events from UI thread to WebCore thread
3692        if (mForwardTouchEvents && mTouchMode != SCROLL_ZOOM_OUT
3693                && mTouchMode != SCROLL_ZOOM_ANIMATION_IN
3694                && mTouchMode != SCROLL_ZOOM_ANIMATION_OUT
3695                && (action != MotionEvent.ACTION_MOVE ||
3696                        eventTime - mLastSentTouchTime > TOUCH_SENT_INTERVAL)) {
3697            WebViewCore.TouchEventData ted = new WebViewCore.TouchEventData();
3698            ted.mAction = action;
3699            ted.mX = viewToContent((int) x + mScrollX);
3700            ted.mY = viewToContent((int) y + mScrollY);
3701            mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
3702            mLastSentTouchTime = eventTime;
3703        }
3704
3705        int deltaX = (int) (mLastTouchX - x);
3706        int deltaY = (int) (mLastTouchY - y);
3707
3708        switch (action) {
3709            case MotionEvent.ACTION_DOWN: {
3710                if (mTouchMode == SCROLL_ZOOM_ANIMATION_IN
3711                        || mTouchMode == SCROLL_ZOOM_ANIMATION_OUT) {
3712                    // no interaction while animation is in progress
3713                    break;
3714                } else if (mTouchMode == SCROLL_ZOOM_OUT) {
3715                    mLastScrollX = mZoomScrollX;
3716                    mLastScrollY = mZoomScrollY;
3717                    // If two taps are close, ignore the first tap
3718                } else if (!mScroller.isFinished()) {
3719                    mScroller.abortAnimation();
3720                    mTouchMode = TOUCH_DRAG_START_MODE;
3721                    mPrivateHandler.removeMessages(RESUME_WEBCORE_UPDATE);
3722                } else if (mShiftIsPressed) {
3723                    mSelectX = mScrollX + (int) x;
3724                    mSelectY = mScrollY + (int) y;
3725                    mTouchMode = TOUCH_SELECT_MODE;
3726                    if (DebugFlags.WEB_VIEW) {
3727                        Log.v(LOGTAG, "select=" + mSelectX + "," + mSelectY);
3728                    }
3729                    nativeMoveSelection(viewToContent(mSelectX)
3730                            , viewToContent(mSelectY), false);
3731                    mTouchSelection = mExtendSelection = true;
3732                } else {
3733                    mTouchMode = TOUCH_INIT_MODE;
3734                    mPreventDrag = mForwardTouchEvents;
3735                    if (mLogEvent && eventTime - mLastTouchUpTime < 1000) {
3736                        EventLog.writeEvent(EVENT_LOG_DOUBLE_TAP_DURATION,
3737                                (eventTime - mLastTouchUpTime), eventTime);
3738                    }
3739                }
3740                // Trigger the link
3741                if (mTouchMode == TOUCH_INIT_MODE) {
3742                    mPrivateHandler.sendMessageDelayed(mPrivateHandler
3743                            .obtainMessage(SWITCH_TO_SHORTPRESS), TAP_TIMEOUT);
3744                }
3745                // Remember where the motion event started
3746                mLastTouchX = x;
3747                mLastTouchY = y;
3748                mLastTouchTime = eventTime;
3749                mVelocityTracker = VelocityTracker.obtain();
3750                mSnapScrollMode = SNAP_NONE;
3751                break;
3752            }
3753            case MotionEvent.ACTION_MOVE: {
3754                if (mTouchMode == TOUCH_DONE_MODE
3755                        || mTouchMode == SCROLL_ZOOM_ANIMATION_IN
3756                        || mTouchMode == SCROLL_ZOOM_ANIMATION_OUT) {
3757                    // no dragging during scroll zoom animation
3758                    break;
3759                }
3760                if (mTouchMode == SCROLL_ZOOM_OUT) {
3761                    // while fully zoomed out, move the virtual window
3762                    moveZoomScrollWindow(x, y);
3763                    break;
3764                }
3765                mVelocityTracker.addMovement(ev);
3766
3767                if (mTouchMode != TOUCH_DRAG_MODE) {
3768                    if (mTouchMode == TOUCH_SELECT_MODE) {
3769                        mSelectX = mScrollX + (int) x;
3770                        mSelectY = mScrollY + (int) y;
3771                        if (DebugFlags.WEB_VIEW) {
3772                            Log.v(LOGTAG, "xtend=" + mSelectX + "," + mSelectY);
3773                        }
3774                        nativeMoveSelection(viewToContent(mSelectX)
3775                                , viewToContent(mSelectY), true);
3776                        invalidate();
3777                        break;
3778                    }
3779                    if (mPreventDrag || (deltaX * deltaX + deltaY * deltaY)
3780                            < mTouchSlopSquare) {
3781                        break;
3782                    }
3783
3784                    if (mTouchMode == TOUCH_SHORTPRESS_MODE
3785                            || mTouchMode == TOUCH_SHORTPRESS_START_MODE) {
3786                        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
3787                    } else if (mTouchMode == TOUCH_INIT_MODE) {
3788                        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
3789                    }
3790
3791                    // if it starts nearly horizontal or vertical, enforce it
3792                    int ax = Math.abs(deltaX);
3793                    int ay = Math.abs(deltaY);
3794                    if (ax > MAX_SLOPE_FOR_DIAG * ay) {
3795                        mSnapScrollMode = SNAP_X;
3796                        mSnapPositive = deltaX > 0;
3797                    } else if (ay > MAX_SLOPE_FOR_DIAG * ax) {
3798                        mSnapScrollMode = SNAP_Y;
3799                        mSnapPositive = deltaY > 0;
3800                    }
3801
3802                    mTouchMode = TOUCH_DRAG_MODE;
3803                    WebViewCore.pauseUpdate(mWebViewCore);
3804                    nativeHideCursor();
3805                    // remove the zoom anchor if there is any
3806                    if (mZoomScale != 0) {
3807                        mWebViewCore
3808                                .sendMessage(EventHub.SET_SNAP_ANCHOR, 0, 0);
3809                    }
3810                    WebSettings settings = getSettings();
3811                    if (settings.supportZoom()
3812                            && settings.getBuiltInZoomControls()
3813                            && !mZoomButtonsController.isVisible()
3814                            && (canZoomScrollOut() ||
3815                                    mMinZoomScale < mMaxZoomScale)) {
3816                        mZoomButtonsController.setVisible(true);
3817                    }
3818                }
3819
3820                // do pan
3821                int newScrollX = pinLocX(mScrollX + deltaX);
3822                deltaX = newScrollX - mScrollX;
3823                int newScrollY = pinLocY(mScrollY + deltaY);
3824                deltaY = newScrollY - mScrollY;
3825                boolean done = false;
3826                if (deltaX == 0 && deltaY == 0) {
3827                    done = true;
3828                } else {
3829                    if (mSnapScrollMode == SNAP_X || mSnapScrollMode == SNAP_Y) {
3830                        int ax = Math.abs(deltaX);
3831                        int ay = Math.abs(deltaY);
3832                        if (mSnapScrollMode == SNAP_X) {
3833                            // radical change means getting out of snap mode
3834                            if (ay > MAX_SLOPE_FOR_DIAG * ax
3835                                    && ay > MIN_BREAK_SNAP_CROSS_DISTANCE) {
3836                                mSnapScrollMode = SNAP_NONE;
3837                            }
3838                            // reverse direction means lock in the snap mode
3839                            if ((ax > MAX_SLOPE_FOR_DIAG * ay) &&
3840                                    ((mSnapPositive &&
3841                                    deltaX < -mMinLockSnapReverseDistance)
3842                                    || (!mSnapPositive &&
3843                                    deltaX > mMinLockSnapReverseDistance))) {
3844                                mSnapScrollMode = SNAP_X_LOCK;
3845                            }
3846                        } else {
3847                            // radical change means getting out of snap mode
3848                            if ((ax > MAX_SLOPE_FOR_DIAG * ay)
3849                                    && ax > MIN_BREAK_SNAP_CROSS_DISTANCE) {
3850                                mSnapScrollMode = SNAP_NONE;
3851                            }
3852                            // reverse direction means lock in the snap mode
3853                            if ((ay > MAX_SLOPE_FOR_DIAG * ax) &&
3854                                    ((mSnapPositive &&
3855                                    deltaY < -mMinLockSnapReverseDistance)
3856                                    || (!mSnapPositive &&
3857                                    deltaY > mMinLockSnapReverseDistance))) {
3858                                mSnapScrollMode = SNAP_Y_LOCK;
3859                            }
3860                        }
3861                    }
3862
3863                    if (mSnapScrollMode == SNAP_X
3864                            || mSnapScrollMode == SNAP_X_LOCK) {
3865                        scrollBy(deltaX, 0);
3866                        mLastTouchX = x;
3867                    } else if (mSnapScrollMode == SNAP_Y
3868                            || mSnapScrollMode == SNAP_Y_LOCK) {
3869                        scrollBy(0, deltaY);
3870                        mLastTouchY = y;
3871                    } else {
3872                        scrollBy(deltaX, deltaY);
3873                        mLastTouchX = x;
3874                        mLastTouchY = y;
3875                    }
3876                    mLastTouchTime = eventTime;
3877                    mUserScroll = true;
3878                }
3879
3880                if (!getSettings().getBuiltInZoomControls()) {
3881                    boolean showPlusMinus = mMinZoomScale < mMaxZoomScale;
3882                    boolean showMagnify = canZoomScrollOut();
3883                    if (mZoomControls != null && (showPlusMinus || showMagnify)) {
3884                        if (mZoomControls.getVisibility() == View.VISIBLE) {
3885                            mPrivateHandler.removeCallbacks(mZoomControlRunnable);
3886                        } else {
3887                            mZoomControls.show(showPlusMinus, showMagnify);
3888                        }
3889                        mPrivateHandler.postDelayed(mZoomControlRunnable,
3890                                ZOOM_CONTROLS_TIMEOUT);
3891                    }
3892                }
3893
3894                if (done) {
3895                    // return false to indicate that we can't pan out of the
3896                    // view space
3897                    return false;
3898                }
3899                break;
3900            }
3901            case MotionEvent.ACTION_UP: {
3902                mLastTouchUpTime = eventTime;
3903                switch (mTouchMode) {
3904                    case TOUCH_INIT_MODE: // tap
3905                    case TOUCH_SHORTPRESS_START_MODE:
3906                    case TOUCH_SHORTPRESS_MODE:
3907                        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
3908                        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
3909                        mTouchMode = TOUCH_DONE_MODE;
3910                        doShortPress();
3911                        break;
3912                    case TOUCH_SELECT_MODE:
3913                        commitCopy();
3914                        mTouchSelection = false;
3915                        break;
3916                    case SCROLL_ZOOM_ANIMATION_IN:
3917                    case SCROLL_ZOOM_ANIMATION_OUT:
3918                        // no action during scroll animation
3919                        break;
3920                    case SCROLL_ZOOM_OUT:
3921                        if (DebugFlags.WEB_VIEW) {
3922                            Log.v(LOGTAG, "ACTION_UP SCROLL_ZOOM_OUT"
3923                                    + " eventTime - mLastTouchTime="
3924                                    + (eventTime - mLastTouchTime));
3925                        }
3926                        // for now, always zoom back when the drag completes
3927                        if (true || eventTime - mLastTouchTime < TAP_TIMEOUT) {
3928                            // but if we tap, zoom in where we tap
3929                            if (eventTime - mLastTouchTime < TAP_TIMEOUT) {
3930                                zoomScrollTap(x, y);
3931                            }
3932                            // start zooming in back to the original view
3933                            setZoomScrollIn();
3934                            mTouchMode = SCROLL_ZOOM_ANIMATION_IN;
3935                            invalidate();
3936                        }
3937                        break;
3938                    case TOUCH_DRAG_MODE:
3939                        // if the user waits a while w/o moving before the
3940                        // up, we don't want to do a fling
3941                        if (eventTime - mLastTouchTime <= MIN_FLING_TIME) {
3942                            mVelocityTracker.addMovement(ev);
3943                            doFling();
3944                            break;
3945                        }
3946                        WebViewCore.resumeUpdate(mWebViewCore);
3947                        break;
3948                    case TOUCH_DRAG_START_MODE:
3949                    case TOUCH_DONE_MODE:
3950                        // do nothing
3951                        break;
3952                }
3953                // we also use mVelocityTracker == null to tell us that we are
3954                // not "moving around", so we can take the slower/prettier
3955                // mode in the drawing code
3956                if (mVelocityTracker != null) {
3957                    mVelocityTracker.recycle();
3958                    mVelocityTracker = null;
3959                }
3960                break;
3961            }
3962            case MotionEvent.ACTION_CANCEL: {
3963                // we also use mVelocityTracker == null to tell us that we are
3964                // not "moving around", so we can take the slower/prettier
3965                // mode in the drawing code
3966                if (mVelocityTracker != null) {
3967                    mVelocityTracker.recycle();
3968                    mVelocityTracker = null;
3969                }
3970                if (mTouchMode == SCROLL_ZOOM_OUT ||
3971                        mTouchMode == SCROLL_ZOOM_ANIMATION_IN) {
3972                    scrollTo(mZoomScrollX, mZoomScrollY);
3973                } else if (mTouchMode == TOUCH_DRAG_MODE) {
3974                    WebViewCore.resumeUpdate(mWebViewCore);
3975                }
3976                mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
3977                mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
3978                mTouchMode = TOUCH_DONE_MODE;
3979                nativeHideCursor();
3980                break;
3981            }
3982        }
3983        return true;
3984    }
3985
3986    private long mTrackballFirstTime = 0;
3987    private long mTrackballLastTime = 0;
3988    private float mTrackballRemainsX = 0.0f;
3989    private float mTrackballRemainsY = 0.0f;
3990    private int mTrackballXMove = 0;
3991    private int mTrackballYMove = 0;
3992    private boolean mExtendSelection = false;
3993    private boolean mTouchSelection = false;
3994    private static final int TRACKBALL_KEY_TIMEOUT = 1000;
3995    private static final int TRACKBALL_TIMEOUT = 200;
3996    private static final int TRACKBALL_WAIT = 100;
3997    private static final int TRACKBALL_SCALE = 400;
3998    private static final int TRACKBALL_SCROLL_COUNT = 5;
3999    private static final int TRACKBALL_MOVE_COUNT = 10;
4000    private static final int TRACKBALL_MULTIPLIER = 3;
4001    private static final int SELECT_CURSOR_OFFSET = 16;
4002    private int mSelectX = 0;
4003    private int mSelectY = 0;
4004    private boolean mShiftIsPressed = false;
4005    private boolean mTrackballDown = false;
4006    private long mTrackballUpTime = 0;
4007    private long mLastCursorTime = 0;
4008    private Rect mLastCursorBounds;
4009
4010    // Set by default; BrowserActivity clears to interpret trackball data
4011    // directly for movement. Currently, the framework only passes
4012    // arrow key events, not trackball events, from one child to the next
4013    private boolean mMapTrackballToArrowKeys = true;
4014
4015    public void setMapTrackballToArrowKeys(boolean setMap) {
4016        mMapTrackballToArrowKeys = setMap;
4017    }
4018
4019    void resetTrackballTime() {
4020        mTrackballLastTime = 0;
4021    }
4022
4023    @Override
4024    public boolean onTrackballEvent(MotionEvent ev) {
4025        long time = ev.getEventTime();
4026        if ((ev.getMetaState() & KeyEvent.META_ALT_ON) != 0) {
4027            if (ev.getY() > 0) pageDown(true);
4028            if (ev.getY() < 0) pageUp(true);
4029            return true;
4030        }
4031        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
4032            mPrivateHandler.removeMessages(SWITCH_TO_CLICK);
4033            mTrackballDown = true;
4034            if (mNativeClass == 0) {
4035                return false;
4036            }
4037            nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true);
4038            if (time - mLastCursorTime <= TRACKBALL_TIMEOUT
4039                    && !mLastCursorBounds.equals(nativeGetCursorRingBounds())) {
4040                nativeSelectBestAt(mLastCursorBounds);
4041            }
4042            if (DebugFlags.WEB_VIEW) {
4043                Log.v(LOGTAG, "onTrackballEvent down ev=" + ev
4044                        + " time=" + time
4045                        + " mLastCursorTime=" + mLastCursorTime);
4046            }
4047            if (isInTouchMode()) requestFocusFromTouch();
4048            return false; // let common code in onKeyDown at it
4049        }
4050        if (ev.getAction() == MotionEvent.ACTION_UP) {
4051            // LONG_PRESS_CENTER is set in common onKeyDown
4052            mPrivateHandler.removeMessages(LONG_PRESS_CENTER);
4053            mTrackballDown = false;
4054            mTrackballUpTime = time;
4055            if (mShiftIsPressed) {
4056                if (mExtendSelection) {
4057                    commitCopy();
4058                } else {
4059                    mExtendSelection = true;
4060                }
4061            }
4062            if (DebugFlags.WEB_VIEW) {
4063                Log.v(LOGTAG, "onTrackballEvent up ev=" + ev
4064                        + " time=" + time
4065                );
4066            }
4067            return false; // let common code in onKeyUp at it
4068        }
4069        if (mMapTrackballToArrowKeys && mShiftIsPressed == false) {
4070            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent gmail quit");
4071            return false;
4072        }
4073        // no move if we're still waiting on SWITCH_TO_CLICK timeout
4074        if (mTouchMode == TOUCH_DOUBLECLICK_MODE) {
4075            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent 2 click quit");
4076            return true;
4077        }
4078        if (mTrackballDown) {
4079            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent down quit");
4080            return true; // discard move if trackball is down
4081        }
4082        if (time - mTrackballUpTime < TRACKBALL_TIMEOUT) {
4083            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent up timeout quit");
4084            return true;
4085        }
4086        // TODO: alternatively we can do panning as touch does
4087        switchOutDrawHistory();
4088        if (time - mTrackballLastTime > TRACKBALL_TIMEOUT) {
4089            if (DebugFlags.WEB_VIEW) {
4090                Log.v(LOGTAG, "onTrackballEvent time="
4091                        + time + " last=" + mTrackballLastTime);
4092            }
4093            mTrackballFirstTime = time;
4094            mTrackballXMove = mTrackballYMove = 0;
4095        }
4096        mTrackballLastTime = time;
4097        if (DebugFlags.WEB_VIEW) {
4098            Log.v(LOGTAG, "onTrackballEvent ev=" + ev + " time=" + time);
4099        }
4100        mTrackballRemainsX += ev.getX();
4101        mTrackballRemainsY += ev.getY();
4102        doTrackball(time);
4103        return true;
4104    }
4105
4106    void moveSelection(float xRate, float yRate) {
4107        if (mNativeClass == 0)
4108            return;
4109        int width = getViewWidth();
4110        int height = getViewHeight();
4111        mSelectX += scaleTrackballX(xRate, width);
4112        mSelectY += scaleTrackballY(yRate, height);
4113        int maxX = width + mScrollX;
4114        int maxY = height + mScrollY;
4115        mSelectX = Math.min(maxX, Math.max(mScrollX - SELECT_CURSOR_OFFSET
4116                , mSelectX));
4117        mSelectY = Math.min(maxY, Math.max(mScrollY - SELECT_CURSOR_OFFSET
4118                , mSelectY));
4119        if (DebugFlags.WEB_VIEW) {
4120            Log.v(LOGTAG, "moveSelection"
4121                    + " mSelectX=" + mSelectX
4122                    + " mSelectY=" + mSelectY
4123                    + " mScrollX=" + mScrollX
4124                    + " mScrollY=" + mScrollY
4125                    + " xRate=" + xRate
4126                    + " yRate=" + yRate
4127                    );
4128        }
4129        nativeMoveSelection(viewToContent(mSelectX)
4130                , viewToContent(mSelectY), mExtendSelection);
4131        int scrollX = mSelectX < mScrollX ? -SELECT_CURSOR_OFFSET
4132                : mSelectX > maxX - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET
4133                : 0;
4134        int scrollY = mSelectY < mScrollY ? -SELECT_CURSOR_OFFSET
4135                : mSelectY > maxY - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET
4136                : 0;
4137        pinScrollBy(scrollX, scrollY, true, 0);
4138        Rect select = new Rect(mSelectX, mSelectY, mSelectX + 1, mSelectY + 1);
4139        requestRectangleOnScreen(select);
4140        invalidate();
4141   }
4142
4143    private int scaleTrackballX(float xRate, int width) {
4144        int xMove = (int) (xRate / TRACKBALL_SCALE * width);
4145        int nextXMove = xMove;
4146        if (xMove > 0) {
4147            if (xMove > mTrackballXMove) {
4148                xMove -= mTrackballXMove;
4149            }
4150        } else if (xMove < mTrackballXMove) {
4151            xMove -= mTrackballXMove;
4152        }
4153        mTrackballXMove = nextXMove;
4154        return xMove;
4155    }
4156
4157    private int scaleTrackballY(float yRate, int height) {
4158        int yMove = (int) (yRate / TRACKBALL_SCALE * height);
4159        int nextYMove = yMove;
4160        if (yMove > 0) {
4161            if (yMove > mTrackballYMove) {
4162                yMove -= mTrackballYMove;
4163            }
4164        } else if (yMove < mTrackballYMove) {
4165            yMove -= mTrackballYMove;
4166        }
4167        mTrackballYMove = nextYMove;
4168        return yMove;
4169    }
4170
4171    private int keyCodeToSoundsEffect(int keyCode) {
4172        switch(keyCode) {
4173            case KeyEvent.KEYCODE_DPAD_UP:
4174                return SoundEffectConstants.NAVIGATION_UP;
4175            case KeyEvent.KEYCODE_DPAD_RIGHT:
4176                return SoundEffectConstants.NAVIGATION_RIGHT;
4177            case KeyEvent.KEYCODE_DPAD_DOWN:
4178                return SoundEffectConstants.NAVIGATION_DOWN;
4179            case KeyEvent.KEYCODE_DPAD_LEFT:
4180                return SoundEffectConstants.NAVIGATION_LEFT;
4181        }
4182        throw new IllegalArgumentException("keyCode must be one of " +
4183                "{KEYCODE_DPAD_UP, KEYCODE_DPAD_RIGHT, KEYCODE_DPAD_DOWN, " +
4184                "KEYCODE_DPAD_LEFT}.");
4185    }
4186
4187    private void doTrackball(long time) {
4188        int elapsed = (int) (mTrackballLastTime - mTrackballFirstTime);
4189        if (elapsed == 0) {
4190            elapsed = TRACKBALL_TIMEOUT;
4191        }
4192        float xRate = mTrackballRemainsX * 1000 / elapsed;
4193        float yRate = mTrackballRemainsY * 1000 / elapsed;
4194        if (mShiftIsPressed) {
4195            moveSelection(xRate, yRate);
4196            mTrackballRemainsX = mTrackballRemainsY = 0;
4197            return;
4198        }
4199        float ax = Math.abs(xRate);
4200        float ay = Math.abs(yRate);
4201        float maxA = Math.max(ax, ay);
4202        if (DebugFlags.WEB_VIEW) {
4203            Log.v(LOGTAG, "doTrackball elapsed=" + elapsed
4204                    + " xRate=" + xRate
4205                    + " yRate=" + yRate
4206                    + " mTrackballRemainsX=" + mTrackballRemainsX
4207                    + " mTrackballRemainsY=" + mTrackballRemainsY);
4208        }
4209        int width = mContentWidth - getViewWidth();
4210        int height = mContentHeight - getViewHeight();
4211        if (width < 0) width = 0;
4212        if (height < 0) height = 0;
4213        if (mTouchMode == SCROLL_ZOOM_OUT) {
4214            int oldX = mZoomScrollX;
4215            int oldY = mZoomScrollY;
4216            int maxWH = Math.max(width, height);
4217            mZoomScrollX += scaleTrackballX(xRate, maxWH);
4218            mZoomScrollY += scaleTrackballY(yRate, maxWH);
4219            if (DebugFlags.WEB_VIEW) {
4220                Log.v(LOGTAG, "doTrackball SCROLL_ZOOM_OUT"
4221                        + " mZoomScrollX=" + mZoomScrollX
4222                        + " mZoomScrollY=" + mZoomScrollY);
4223            }
4224            mZoomScrollX = Math.min(width, Math.max(0, mZoomScrollX));
4225            mZoomScrollY = Math.min(height, Math.max(0, mZoomScrollY));
4226            if (oldX != mZoomScrollX || oldY != mZoomScrollY) {
4227                invalidate();
4228            }
4229            mTrackballRemainsX = mTrackballRemainsY = 0;
4230            return;
4231        }
4232        ax = Math.abs(mTrackballRemainsX * TRACKBALL_MULTIPLIER);
4233        ay = Math.abs(mTrackballRemainsY * TRACKBALL_MULTIPLIER);
4234        maxA = Math.max(ax, ay);
4235        int count = Math.max(0, (int) maxA);
4236        int oldScrollX = mScrollX;
4237        int oldScrollY = mScrollY;
4238        if (count > 0) {
4239            int selectKeyCode = ax < ay ? mTrackballRemainsY < 0 ?
4240                    KeyEvent.KEYCODE_DPAD_UP : KeyEvent.KEYCODE_DPAD_DOWN :
4241                    mTrackballRemainsX < 0 ? KeyEvent.KEYCODE_DPAD_LEFT :
4242                    KeyEvent.KEYCODE_DPAD_RIGHT;
4243            count = Math.min(count, TRACKBALL_MOVE_COUNT);
4244            if (DebugFlags.WEB_VIEW) {
4245                Log.v(LOGTAG, "doTrackball keyCode=" + selectKeyCode
4246                        + " count=" + count
4247                        + " mTrackballRemainsX=" + mTrackballRemainsX
4248                        + " mTrackballRemainsY=" + mTrackballRemainsY);
4249            }
4250            if (navHandledKey(selectKeyCode, count, false, time, false)) {
4251                playSoundEffect(keyCodeToSoundsEffect(selectKeyCode));
4252            }
4253            mTrackballRemainsX = mTrackballRemainsY = 0;
4254        }
4255        if (count >= TRACKBALL_SCROLL_COUNT) {
4256            int xMove = scaleTrackballX(xRate, width);
4257            int yMove = scaleTrackballY(yRate, height);
4258            if (DebugFlags.WEB_VIEW) {
4259                Log.v(LOGTAG, "doTrackball pinScrollBy"
4260                        + " count=" + count
4261                        + " xMove=" + xMove + " yMove=" + yMove
4262                        + " mScrollX-oldScrollX=" + (mScrollX-oldScrollX)
4263                        + " mScrollY-oldScrollY=" + (mScrollY-oldScrollY)
4264                        );
4265            }
4266            if (Math.abs(mScrollX - oldScrollX) > Math.abs(xMove)) {
4267                xMove = 0;
4268            }
4269            if (Math.abs(mScrollY - oldScrollY) > Math.abs(yMove)) {
4270                yMove = 0;
4271            }
4272            if (xMove != 0 || yMove != 0) {
4273                pinScrollBy(xMove, yMove, true, 0);
4274            }
4275            mUserScroll = true;
4276        }
4277    }
4278
4279    public void flingScroll(int vx, int vy) {
4280        int maxX = Math.max(computeHorizontalScrollRange() - getViewWidth(), 0);
4281        int maxY = Math.max(computeVerticalScrollRange() - getViewHeight(), 0);
4282
4283        mScroller.fling(mScrollX, mScrollY, vx, vy, 0, maxX, 0, maxY);
4284        invalidate();
4285    }
4286
4287    private void doFling() {
4288        if (mVelocityTracker == null) {
4289            return;
4290        }
4291        int maxX = Math.max(computeHorizontalScrollRange() - getViewWidth(), 0);
4292        int maxY = Math.max(computeVerticalScrollRange() - getViewHeight(), 0);
4293
4294        mVelocityTracker.computeCurrentVelocity(1000);
4295        int vx = (int) mVelocityTracker.getXVelocity();
4296        int vy = (int) mVelocityTracker.getYVelocity();
4297
4298        if (mSnapScrollMode != SNAP_NONE) {
4299            if (mSnapScrollMode == SNAP_X || mSnapScrollMode == SNAP_X_LOCK) {
4300                vy = 0;
4301            } else {
4302                vx = 0;
4303            }
4304        }
4305
4306        if (true /* EMG release: make our fling more like Maps' */) {
4307            // maps cuts their velocity in half
4308            vx = vx * 3 / 4;
4309            vy = vy * 3 / 4;
4310        }
4311
4312        mScroller.fling(mScrollX, mScrollY, -vx, -vy, 0, maxX, 0, maxY);
4313        // TODO: duration is calculated based on velocity, if the range is
4314        // small, the animation will stop before duration is up. We may
4315        // want to calculate how long the animation is going to run to precisely
4316        // resume the webcore update.
4317        final int time = mScroller.getDuration();
4318        mPrivateHandler.sendEmptyMessageDelayed(RESUME_WEBCORE_UPDATE, time);
4319        invalidate();
4320    }
4321
4322    private boolean zoomWithPreview(float scale) {
4323        float oldScale = mActualScale;
4324
4325        // snap to DEFAULT_SCALE if it is close
4326        if (scale > (mDefaultScale - 0.05) && scale < (mDefaultScale + 0.05)) {
4327            scale = mDefaultScale;
4328        }
4329
4330        setNewZoomScale(scale, false);
4331
4332        if (oldScale != mActualScale) {
4333            // use mZoomPickerScale to see zoom preview first
4334            mZoomStart = SystemClock.uptimeMillis();
4335            mInvInitialZoomScale = 1.0f / oldScale;
4336            mInvFinalZoomScale = 1.0f / mActualScale;
4337            mZoomScale = mActualScale;
4338            invalidate();
4339            return true;
4340        } else {
4341            return false;
4342        }
4343    }
4344
4345    /**
4346     * Returns a view containing zoom controls i.e. +/- buttons. The caller is
4347     * in charge of installing this view to the view hierarchy. This view will
4348     * become visible when the user starts scrolling via touch and fade away if
4349     * the user does not interact with it.
4350     * <p/>
4351     * API version 3 introduces a built-in zoom mechanism that is shown
4352     * automatically by the MapView. This is the preferred approach for
4353     * showing the zoom UI.
4354     *
4355     * @deprecated The built-in zoom mechanism is preferred, see
4356     *             {@link WebSettings#setBuiltInZoomControls(boolean)}.
4357     */
4358    @Deprecated
4359    public View getZoomControls() {
4360        if (!getSettings().supportZoom()) {
4361            Log.w(LOGTAG, "This WebView doesn't support zoom.");
4362            return null;
4363        }
4364        if (mZoomControls == null) {
4365            mZoomControls = createZoomControls();
4366
4367            /*
4368             * need to be set to VISIBLE first so that getMeasuredHeight() in
4369             * {@link #onSizeChanged()} can return the measured value for proper
4370             * layout.
4371             */
4372            mZoomControls.setVisibility(View.VISIBLE);
4373            mZoomControlRunnable = new Runnable() {
4374                public void run() {
4375
4376                    /* Don't dismiss the controls if the user has
4377                     * focus on them. Wait and check again later.
4378                     */
4379                    if (!mZoomControls.hasFocus()) {
4380                        mZoomControls.hide();
4381                    } else {
4382                        mPrivateHandler.removeCallbacks(mZoomControlRunnable);
4383                        mPrivateHandler.postDelayed(mZoomControlRunnable,
4384                                ZOOM_CONTROLS_TIMEOUT);
4385                    }
4386                }
4387            };
4388        }
4389        return mZoomControls;
4390    }
4391
4392    private ExtendedZoomControls createZoomControls() {
4393        ExtendedZoomControls zoomControls = new ExtendedZoomControls(mContext
4394            , null);
4395        zoomControls.setOnZoomInClickListener(new OnClickListener() {
4396            public void onClick(View v) {
4397                // reset time out
4398                mPrivateHandler.removeCallbacks(mZoomControlRunnable);
4399                mPrivateHandler.postDelayed(mZoomControlRunnable,
4400                        ZOOM_CONTROLS_TIMEOUT);
4401                zoomIn();
4402            }
4403        });
4404        zoomControls.setOnZoomOutClickListener(new OnClickListener() {
4405            public void onClick(View v) {
4406                // reset time out
4407                mPrivateHandler.removeCallbacks(mZoomControlRunnable);
4408                mPrivateHandler.postDelayed(mZoomControlRunnable,
4409                        ZOOM_CONTROLS_TIMEOUT);
4410                zoomOut();
4411            }
4412        });
4413        zoomControls.setOnZoomMagnifyClickListener(new OnClickListener() {
4414            public void onClick(View v) {
4415                mPrivateHandler.removeCallbacks(mZoomControlRunnable);
4416                mPrivateHandler.postDelayed(mZoomControlRunnable,
4417                        ZOOM_CONTROLS_TIMEOUT);
4418                zoomScrollOut();
4419            }
4420        });
4421        return zoomControls;
4422    }
4423
4424    /**
4425     * Gets the {@link ZoomButtonsController} which can be used to add
4426     * additional buttons to the zoom controls window.
4427     *
4428     * @return The instance of {@link ZoomButtonsController} used by this class,
4429     *         or null if it is unavailable.
4430     * @hide
4431     */
4432    public ZoomButtonsController getZoomButtonsController() {
4433        return mZoomButtonsController;
4434    }
4435
4436    /**
4437     * Perform zoom in in the webview
4438     * @return TRUE if zoom in succeeds. FALSE if no zoom changes.
4439     */
4440    public boolean zoomIn() {
4441        // TODO: alternatively we can disallow this during draw history mode
4442        switchOutDrawHistory();
4443        return zoomWithPreview(mActualScale * 1.25f);
4444    }
4445
4446    /**
4447     * Perform zoom out in the webview
4448     * @return TRUE if zoom out succeeds. FALSE if no zoom changes.
4449     */
4450    public boolean zoomOut() {
4451        // TODO: alternatively we can disallow this during draw history mode
4452        switchOutDrawHistory();
4453        return zoomWithPreview(mActualScale * 0.8f);
4454    }
4455
4456    private void updateSelection() {
4457        if (mNativeClass == 0) {
4458            return;
4459        }
4460        // mLastTouchX and mLastTouchY are the point in the current viewport
4461        int contentX = viewToContent((int) mLastTouchX + mScrollX);
4462        int contentY = viewToContent((int) mLastTouchY + mScrollY);
4463        Rect rect = new Rect(contentX - mNavSlop, contentY - mNavSlop,
4464                contentX + mNavSlop, contentY + mNavSlop);
4465        nativeSelectBestAt(rect);
4466    }
4467
4468    /*package*/ void shortPressOnTextField() {
4469        if (inEditingMode()) {
4470            View v = mWebTextView;
4471            int x = viewToContent((v.getLeft() + v.getRight()) >> 1);
4472            int y = viewToContent((v.getTop() + v.getBottom()) >> 1);
4473            nativeMotionUp(x, y, mNavSlop);
4474        }
4475    }
4476
4477    private void doShortPress() {
4478        if (mNativeClass == 0) {
4479            return;
4480        }
4481        switchOutDrawHistory();
4482        // mLastTouchX and mLastTouchY are the point in the current viewport
4483        int contentX = viewToContent((int) mLastTouchX + mScrollX);
4484        int contentY = viewToContent((int) mLastTouchY + mScrollY);
4485        if (nativeMotionUp(contentX, contentY, mNavSlop)) {
4486            if (mLogEvent) {
4487                Checkin.updateStats(mContext.getContentResolver(),
4488                        Checkin.Stats.Tag.BROWSER_SNAP_CENTER, 1, 0.0);
4489            }
4490        }
4491        if (nativeHasCursorNode() && !nativeCursorIsTextInput()) {
4492            playSoundEffect(SoundEffectConstants.CLICK);
4493        }
4494    }
4495
4496    // Called by JNI to handle a touch on a node representing an email address,
4497    // address, or phone number
4498    private void overrideLoading(String url) {
4499        mCallbackProxy.uiOverrideUrlLoading(url);
4500    }
4501
4502    @Override
4503    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
4504        boolean result = false;
4505        if (inEditingMode()) {
4506            result = mWebTextView.requestFocus(direction,
4507                    previouslyFocusedRect);
4508        } else {
4509            result = super.requestFocus(direction, previouslyFocusedRect);
4510            if (mWebViewCore.getSettings().getNeedInitialFocus()) {
4511                // For cases such as GMail, where we gain focus from a direction,
4512                // we want to move to the first available link.
4513                // FIXME: If there are no visible links, we may not want to
4514                int fakeKeyDirection = 0;
4515                switch(direction) {
4516                    case View.FOCUS_UP:
4517                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_UP;
4518                        break;
4519                    case View.FOCUS_DOWN:
4520                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_DOWN;
4521                        break;
4522                    case View.FOCUS_LEFT:
4523                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_LEFT;
4524                        break;
4525                    case View.FOCUS_RIGHT:
4526                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_RIGHT;
4527                        break;
4528                    default:
4529                        return result;
4530                }
4531                if (mNativeClass != 0 && !nativeHasCursorNode()) {
4532                    navHandledKey(fakeKeyDirection, 1, true, 0, true);
4533                }
4534            }
4535        }
4536        return result;
4537    }
4538
4539    @Override
4540    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
4541        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
4542
4543        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
4544        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
4545        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
4546        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
4547
4548        int measuredHeight = heightSize;
4549        int measuredWidth = widthSize;
4550
4551        // Grab the content size from WebViewCore.
4552        int contentHeight = mContentHeight;
4553        int contentWidth = mContentWidth;
4554
4555//        Log.d(LOGTAG, "------- measure " + heightMode);
4556
4557        if (heightMode != MeasureSpec.EXACTLY) {
4558            mHeightCanMeasure = true;
4559            measuredHeight = contentHeight;
4560            if (heightMode == MeasureSpec.AT_MOST) {
4561                // If we are larger than the AT_MOST height, then our height can
4562                // no longer be measured and we should scroll internally.
4563                if (measuredHeight > heightSize) {
4564                    measuredHeight = heightSize;
4565                    mHeightCanMeasure = false;
4566                }
4567            }
4568        } else {
4569            mHeightCanMeasure = false;
4570        }
4571        if (mNativeClass != 0) {
4572            nativeSetHeightCanMeasure(mHeightCanMeasure);
4573        }
4574        // For the width, always use the given size unless unspecified.
4575        if (widthMode == MeasureSpec.UNSPECIFIED) {
4576            mWidthCanMeasure = true;
4577            measuredWidth = contentWidth;
4578        } else {
4579            mWidthCanMeasure = false;
4580        }
4581
4582        synchronized (this) {
4583            setMeasuredDimension(measuredWidth, measuredHeight);
4584        }
4585    }
4586
4587    @Override
4588    public boolean requestChildRectangleOnScreen(View child,
4589                                                 Rect rect,
4590                                                 boolean immediate) {
4591        rect.offset(child.getLeft() - child.getScrollX(),
4592                child.getTop() - child.getScrollY());
4593
4594        int height = getHeight() - getHorizontalScrollbarHeight();
4595        int screenTop = mScrollY;
4596        int screenBottom = screenTop + height;
4597
4598        int scrollYDelta = 0;
4599
4600        if (rect.bottom > screenBottom) {
4601            int oneThirdOfScreenHeight = height / 3;
4602            if (rect.height() > 2 * oneThirdOfScreenHeight) {
4603                // If the rectangle is too tall to fit in the bottom two thirds
4604                // of the screen, place it at the top.
4605                scrollYDelta = rect.top - screenTop;
4606            } else {
4607                // If the rectangle will still fit on screen, we want its
4608                // top to be in the top third of the screen.
4609                scrollYDelta = rect.top - (screenTop + oneThirdOfScreenHeight);
4610            }
4611        } else if (rect.top < screenTop) {
4612            scrollYDelta = rect.top - screenTop;
4613        }
4614
4615        int width = getWidth() - getVerticalScrollbarWidth();
4616        int screenLeft = mScrollX;
4617        int screenRight = screenLeft + width;
4618
4619        int scrollXDelta = 0;
4620
4621        if (rect.right > screenRight && rect.left > screenLeft) {
4622            if (rect.width() > width) {
4623                scrollXDelta += (rect.left - screenLeft);
4624            } else {
4625                scrollXDelta += (rect.right - screenRight);
4626            }
4627        } else if (rect.left < screenLeft) {
4628            scrollXDelta -= (screenLeft - rect.left);
4629        }
4630
4631        if ((scrollYDelta | scrollXDelta) != 0) {
4632            return pinScrollBy(scrollXDelta, scrollYDelta, !immediate, 0);
4633        }
4634
4635        return false;
4636    }
4637
4638    /* package */ void replaceTextfieldText(int oldStart, int oldEnd,
4639            String replace, int newStart, int newEnd) {
4640        WebViewCore.ReplaceTextData arg = new WebViewCore.ReplaceTextData();
4641        arg.mReplace = replace;
4642        arg.mNewStart = newStart;
4643        arg.mNewEnd = newEnd;
4644        mTextGeneration++;
4645        mWebViewCore.sendMessage(EventHub.REPLACE_TEXT, oldStart, oldEnd, arg);
4646    }
4647
4648    /* package */ void passToJavaScript(String currentText, KeyEvent event) {
4649        if (nativeCursorWantsKeyEvents() && !nativeCursorMatchesFocus()) {
4650            mWebViewCore.sendMessage(EventHub.CLICK);
4651        }
4652        WebViewCore.JSKeyData arg = new WebViewCore.JSKeyData();
4653        arg.mEvent = event;
4654        arg.mCurrentText = currentText;
4655        // Increase our text generation number, and pass it to webcore thread
4656        mTextGeneration++;
4657        mWebViewCore.sendMessage(EventHub.PASS_TO_JS, mTextGeneration, 0, arg);
4658        // WebKit's document state is not saved until about to leave the page.
4659        // To make sure the host application, like Browser, has the up to date
4660        // document state when it goes to background, we force to save the
4661        // document state.
4662        mWebViewCore.removeMessages(EventHub.SAVE_DOCUMENT_STATE);
4663        mWebViewCore.sendMessageDelayed(EventHub.SAVE_DOCUMENT_STATE,
4664                cursorData(), 1000);
4665    }
4666
4667    /* package */ WebViewCore getWebViewCore() {
4668        return mWebViewCore;
4669    }
4670
4671    //-------------------------------------------------------------------------
4672    // Methods can be called from a separate thread, like WebViewCore
4673    // If it needs to call the View system, it has to send message.
4674    //-------------------------------------------------------------------------
4675
4676    /**
4677     * General handler to receive message coming from webkit thread
4678     */
4679    class PrivateHandler extends Handler {
4680        @Override
4681        public void handleMessage(Message msg) {
4682            if (DebugFlags.WEB_VIEW) {
4683                Log.v(LOGTAG, msg.what < REMEMBER_PASSWORD || msg.what
4684                        > INVAL_RECT_MSG_ID ? Integer.toString(msg.what)
4685                        : HandlerDebugString[msg.what - REMEMBER_PASSWORD]);
4686            }
4687            switch (msg.what) {
4688                case REMEMBER_PASSWORD: {
4689                    mDatabase.setUsernamePassword(
4690                            msg.getData().getString("host"),
4691                            msg.getData().getString("username"),
4692                            msg.getData().getString("password"));
4693                    ((Message) msg.obj).sendToTarget();
4694                    break;
4695                }
4696                case NEVER_REMEMBER_PASSWORD: {
4697                    mDatabase.setUsernamePassword(
4698                            msg.getData().getString("host"), null, null);
4699                    ((Message) msg.obj).sendToTarget();
4700                    break;
4701                }
4702                case SWITCH_TO_SHORTPRESS: {
4703                    if (mTouchMode == TOUCH_INIT_MODE) {
4704                        mTouchMode = TOUCH_SHORTPRESS_START_MODE;
4705                        updateSelection();
4706                    }
4707                    break;
4708                }
4709                case SWITCH_TO_LONGPRESS: {
4710                    if (!mPreventDrag) {
4711                        mTouchMode = TOUCH_DONE_MODE;
4712                        performLongClick();
4713                        rebuildWebTextView();
4714                    }
4715                    break;
4716                }
4717                case SWITCH_TO_CLICK:
4718                    // The user clicked with the trackball, and did not click a
4719                    // second time, so perform the action of a trackball single
4720                    // click
4721                    mTouchMode = TOUCH_DONE_MODE;
4722                    Rect visibleRect = sendOurVisibleRect();
4723                    // Note that sendOurVisibleRect calls viewToContent, so the
4724                    // coordinates should be in content coordinates.
4725                    if (!nativeCursorIntersects(visibleRect)) {
4726                        break;
4727                    }
4728                    nativeSetFollowedLink(true);
4729                    nativeUpdatePluginReceivesEvents();
4730                    WebViewCore.CursorData data = cursorData();
4731                    mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE, data);
4732                    playSoundEffect(SoundEffectConstants.CLICK);
4733                    boolean isTextInput = nativeCursorIsTextInput();
4734                    if (isTextInput || !mCallbackProxy.uiOverrideUrlLoading(
4735                                nativeCursorText())) {
4736                        mWebViewCore.sendMessage(EventHub.CLICK, data.mFrame,
4737                                nativeCursorNodePointer());
4738                    }
4739                    if (isTextInput) {
4740                        rebuildWebTextView();
4741                    }
4742                    break;
4743                case SCROLL_BY_MSG_ID:
4744                    setContentScrollBy(msg.arg1, msg.arg2, (Boolean) msg.obj);
4745                    break;
4746                case SYNC_SCROLL_TO_MSG_ID:
4747                    if (mUserScroll) {
4748                        // if user has scrolled explicitly, don't sync the
4749                        // scroll position any more
4750                        mUserScroll = false;
4751                        break;
4752                    }
4753                    // fall through
4754                case SCROLL_TO_MSG_ID:
4755                    if (setContentScrollTo(msg.arg1, msg.arg2)) {
4756                        // if we can't scroll to the exact position due to pin,
4757                        // send a message to WebCore to re-scroll when we get a
4758                        // new picture
4759                        mUserScroll = false;
4760                        mWebViewCore.sendMessage(EventHub.SYNC_SCROLL,
4761                                msg.arg1, msg.arg2);
4762                    }
4763                    break;
4764                case SPAWN_SCROLL_TO_MSG_ID:
4765                    spawnContentScrollTo(msg.arg1, msg.arg2);
4766                    break;
4767                case NEW_PICTURE_MSG_ID:
4768                    // called for new content
4769                    final WebViewCore.DrawData draw =
4770                            (WebViewCore.DrawData) msg.obj;
4771                    final Point viewSize = draw.mViewPoint;
4772                    if (mZoomScale > 0) {
4773                        // use the same logic in sendViewSizeZoom() to make sure
4774                        // the mZoomScale has matched the viewSize so that we
4775                        // can clear mZoomScale
4776                        if (Math.round(getViewWidth() / mZoomScale) == viewSize.x) {
4777                            mZoomScale = 0;
4778                            mWebViewCore.sendMessage(EventHub.SET_SNAP_ANCHOR,
4779                                    0, 0);
4780                        }
4781                    }
4782                    if (!mMinZoomScaleFixed) {
4783                        mMinZoomScale = (float) getViewWidth()
4784                                / Math.max(ZOOM_OUT_WIDTH, draw.mWidthHeight.x);
4785                    }
4786                    // We update the layout (i.e. request a layout from the
4787                    // view system) if the last view size that we sent to
4788                    // WebCore matches the view size of the picture we just
4789                    // received in the fixed dimension.
4790                    final boolean updateLayout = viewSize.x == mLastWidthSent
4791                            && viewSize.y == mLastHeightSent;
4792                    recordNewContentSize(draw.mWidthHeight.x,
4793                            draw.mWidthHeight.y, updateLayout);
4794                    if (DebugFlags.WEB_VIEW) {
4795                        Rect b = draw.mInvalRegion.getBounds();
4796                        Log.v(LOGTAG, "NEW_PICTURE_MSG_ID {" +
4797                                b.left+","+b.top+","+b.right+","+b.bottom+"}");
4798                    }
4799                    invalidate(contentToView(draw.mInvalRegion.getBounds()));
4800                    if (mPictureListener != null) {
4801                        mPictureListener.onNewPicture(WebView.this, capturePicture());
4802                    }
4803                    break;
4804                case WEBCORE_INITIALIZED_MSG_ID:
4805                    // nativeCreate sets mNativeClass to a non-zero value
4806                    nativeCreate(msg.arg1);
4807                    break;
4808                case UPDATE_TEXTFIELD_TEXT_MSG_ID:
4809                    // Make sure that the textfield is currently focused
4810                    // and representing the same node as the pointer.
4811                    if (inEditingMode() &&
4812                            mWebTextView.isSameTextField(msg.arg1)) {
4813                        if (msg.getData().getBoolean("password")) {
4814                            Spannable text = (Spannable) mWebTextView.getText();
4815                            int start = Selection.getSelectionStart(text);
4816                            int end = Selection.getSelectionEnd(text);
4817                            mWebTextView.setInPassword(true);
4818                            // Restore the selection, which may have been
4819                            // ruined by setInPassword.
4820                            Spannable pword =
4821                                    (Spannable) mWebTextView.getText();
4822                            Selection.setSelection(pword, start, end);
4823                        // If the text entry has created more events, ignore
4824                        // this one.
4825                        } else if (msg.arg2 == mTextGeneration) {
4826                            mWebTextView.setTextAndKeepSelection(
4827                                    (String) msg.obj);
4828                        }
4829                    }
4830                    break;
4831                case DID_FIRST_LAYOUT_MSG_ID:
4832                    if (mNativeClass == 0) {
4833                        break;
4834                    }
4835                    ScaleLimitData scaleLimit = (ScaleLimitData) msg.obj;
4836                    int minScale = scaleLimit.mMinScale;
4837                    if (minScale == 0) {
4838                        mMinZoomScale = DEFAULT_MIN_ZOOM_SCALE;
4839                        mMinZoomScaleFixed = false;
4840                    } else {
4841                        mMinZoomScale = (float) (minScale / 100.0);
4842                        mMinZoomScaleFixed = true;
4843                    }
4844                    int maxScale = scaleLimit.mMaxScale;
4845                    if (maxScale == 0) {
4846                        mMaxZoomScale = DEFAULT_MAX_ZOOM_SCALE;
4847                    } else {
4848                        mMaxZoomScale = (float) (maxScale / 100.0);
4849                    }
4850                    // If history Picture is drawn, don't update zoomWidth
4851                    if (mDrawHistory) {
4852                        break;
4853                    }
4854                    int width = getViewWidth();
4855                    if (width == 0) {
4856                        break;
4857                    }
4858                    int initialScale = msg.arg1;
4859                    int viewportWidth = msg.arg2;
4860                    // start a new page with DEFAULT_SCALE zoom scale.
4861                    float scale = mDefaultScale;
4862                    if (mInitialScale > 0) {
4863                        scale = mInitialScale / 100.0f;
4864                    } else  {
4865                        if (initialScale < 0) break;
4866                        if (mWebViewCore.getSettings().getUseWideViewPort()) {
4867                            // force viewSizeChanged by setting mLastWidthSent
4868                            // to 0
4869                            mLastWidthSent = 0;
4870                        }
4871                        if (initialScale == 0) {
4872                            // if viewportWidth is defined and it is smaller
4873                            // than the view width, zoom in to fill the view
4874                            if (viewportWidth > 0 && viewportWidth < width) {
4875                                scale = (float) width / viewportWidth;
4876                            }
4877                        } else {
4878                            scale = initialScale / 100.0f;
4879                        }
4880                    }
4881                    setNewZoomScale(scale, false);
4882                    break;
4883                case MOVE_OUT_OF_PLUGIN:
4884                    if (nativePluginEatsNavKey()) {
4885                        navHandledKey(msg.arg1, 1, false, 0, true);
4886                    }
4887                    break;
4888                case UPDATE_TEXT_ENTRY_MSG_ID:
4889                    // this is sent after finishing resize in WebViewCore. Make
4890                    // sure the text edit box is still on the  screen.
4891                    if (inEditingMode() && nativeCursorIsTextInput()) {
4892                        mWebTextView.bringIntoView();
4893                    }
4894                    rebuildWebTextView();
4895                    break;
4896                case CLEAR_TEXT_ENTRY:
4897                    clearTextEntry();
4898                    break;
4899                case INVAL_RECT_MSG_ID: {
4900                    Rect r = (Rect)msg.obj;
4901                    if (r == null) {
4902                        invalidate();
4903                    } else {
4904                        // we need to scale r from content into view coords,
4905                        // which viewInvalidate() does for us
4906                        viewInvalidate(r.left, r.top, r.right, r.bottom);
4907                    }
4908                    break;
4909                }
4910                case REQUEST_FORM_DATA:
4911                    AutoCompleteAdapter adapter = (AutoCompleteAdapter) msg.obj;
4912                    if (mWebTextView.isSameTextField(msg.arg1)) {
4913                        mWebTextView.setAdapterCustom(adapter);
4914                    }
4915                    break;
4916                case UPDATE_CLIPBOARD:
4917                    String str = (String) msg.obj;
4918                    if (DebugFlags.WEB_VIEW) {
4919                        Log.v(LOGTAG, "UPDATE_CLIPBOARD " + str);
4920                    }
4921                    try {
4922                        IClipboard clip = IClipboard.Stub.asInterface(
4923                                ServiceManager.getService("clipboard"));
4924                                clip.setClipboardText(str);
4925                    } catch (android.os.RemoteException e) {
4926                        Log.e(LOGTAG, "Clipboard failed", e);
4927                    }
4928                    break;
4929                case RESUME_WEBCORE_UPDATE:
4930                    WebViewCore.resumeUpdate(mWebViewCore);
4931                    break;
4932
4933                case LONG_PRESS_CENTER:
4934                    // as this is shared by keydown and trackballdown, reset all
4935                    // the states
4936                    mGotCenterDown = false;
4937                    mTrackballDown = false;
4938                    // LONG_PRESS_CENTER is sent as a delayed message. If we
4939                    // switch to windows overview, the WebView will be
4940                    // temporarily removed from the view system. In that case,
4941                    // do nothing.
4942                    if (getParent() != null) {
4943                        performLongClick();
4944                    }
4945                    break;
4946
4947                case WEBCORE_NEED_TOUCH_EVENTS:
4948                    mForwardTouchEvents = (msg.arg1 != 0);
4949                    break;
4950
4951                case PREVENT_TOUCH_ID:
4952                    if (msg.arg1 == MotionEvent.ACTION_DOWN) {
4953                        mPreventDrag = msg.arg2 == 1;
4954                        if (mPreventDrag) {
4955                            mTouchMode = TOUCH_DONE_MODE;
4956                        }
4957                    }
4958                    break;
4959
4960                case REQUEST_KEYBOARD:
4961                    if (msg.arg1 == 0) {
4962                        hideSoftKeyboard();
4963                    } else {
4964                        displaySoftKeyboard(false);
4965                    }
4966                    break;
4967
4968                default:
4969                    super.handleMessage(msg);
4970                    break;
4971            }
4972        }
4973    }
4974
4975    // Class used to use a dropdown for a <select> element
4976    private class InvokeListBox implements Runnable {
4977        // Whether the listbox allows multiple selection.
4978        private boolean     mMultiple;
4979        // Passed in to a list with multiple selection to tell
4980        // which items are selected.
4981        private int[]       mSelectedArray;
4982        // Passed in to a list with single selection to tell
4983        // where the initial selection is.
4984        private int         mSelection;
4985
4986        private Container[] mContainers;
4987
4988        // Need these to provide stable ids to my ArrayAdapter,
4989        // which normally does not have stable ids. (Bug 1250098)
4990        private class Container extends Object {
4991            String  mString;
4992            boolean mEnabled;
4993            int     mId;
4994
4995            public String toString() {
4996                return mString;
4997            }
4998        }
4999
5000        /**
5001         *  Subclass ArrayAdapter so we can disable OptionGroupLabels,
5002         *  and allow filtering.
5003         */
5004        private class MyArrayListAdapter extends ArrayAdapter<Container> {
5005            public MyArrayListAdapter(Context context, Container[] objects, boolean multiple) {
5006                super(context,
5007                            multiple ? com.android.internal.R.layout.select_dialog_multichoice :
5008                            com.android.internal.R.layout.select_dialog_singlechoice,
5009                            objects);
5010            }
5011
5012            @Override
5013            public boolean hasStableIds() {
5014                // AdapterView's onChanged method uses this to determine whether
5015                // to restore the old state.  Return false so that the old (out
5016                // of date) state does not replace the new, valid state.
5017                return false;
5018            }
5019
5020            private Container item(int position) {
5021                if (position < 0 || position >= getCount()) {
5022                    return null;
5023                }
5024                return (Container) getItem(position);
5025            }
5026
5027            @Override
5028            public long getItemId(int position) {
5029                Container item = item(position);
5030                if (item == null) {
5031                    return -1;
5032                }
5033                return item.mId;
5034            }
5035
5036            @Override
5037            public boolean areAllItemsEnabled() {
5038                return false;
5039            }
5040
5041            @Override
5042            public boolean isEnabled(int position) {
5043                Container item = item(position);
5044                if (item == null) {
5045                    return false;
5046                }
5047                return item.mEnabled;
5048            }
5049        }
5050
5051        private InvokeListBox(String[] array,
5052                boolean[] enabled, int[] selected) {
5053            mMultiple = true;
5054            mSelectedArray = selected;
5055
5056            int length = array.length;
5057            mContainers = new Container[length];
5058            for (int i = 0; i < length; i++) {
5059                mContainers[i] = new Container();
5060                mContainers[i].mString = array[i];
5061                mContainers[i].mEnabled = enabled[i];
5062                mContainers[i].mId = i;
5063            }
5064        }
5065
5066        private InvokeListBox(String[] array, boolean[] enabled, int
5067                selection) {
5068            mSelection = selection;
5069            mMultiple = false;
5070
5071            int length = array.length;
5072            mContainers = new Container[length];
5073            for (int i = 0; i < length; i++) {
5074                mContainers[i] = new Container();
5075                mContainers[i].mString = array[i];
5076                mContainers[i].mEnabled = enabled[i];
5077                mContainers[i].mId = i;
5078            }
5079        }
5080
5081        /*
5082         * Whenever the data set changes due to filtering, this class ensures
5083         * that the checked item remains checked.
5084         */
5085        private class SingleDataSetObserver extends DataSetObserver {
5086            private long        mCheckedId;
5087            private ListView    mListView;
5088            private Adapter     mAdapter;
5089
5090            /*
5091             * Create a new observer.
5092             * @param id The ID of the item to keep checked.
5093             * @param l ListView for getting and clearing the checked states
5094             * @param a Adapter for getting the IDs
5095             */
5096            public SingleDataSetObserver(long id, ListView l, Adapter a) {
5097                mCheckedId = id;
5098                mListView = l;
5099                mAdapter = a;
5100            }
5101
5102            public void onChanged() {
5103                // The filter may have changed which item is checked.  Find the
5104                // item that the ListView thinks is checked.
5105                int position = mListView.getCheckedItemPosition();
5106                long id = mAdapter.getItemId(position);
5107                if (mCheckedId != id) {
5108                    // Clear the ListView's idea of the checked item, since
5109                    // it is incorrect
5110                    mListView.clearChoices();
5111                    // Search for mCheckedId.  If it is in the filtered list,
5112                    // mark it as checked
5113                    int count = mAdapter.getCount();
5114                    for (int i = 0; i < count; i++) {
5115                        if (mAdapter.getItemId(i) == mCheckedId) {
5116                            mListView.setItemChecked(i, true);
5117                            break;
5118                        }
5119                    }
5120                }
5121            }
5122
5123            public void onInvalidate() {}
5124        }
5125
5126        public void run() {
5127            final ListView listView = (ListView) LayoutInflater.from(mContext)
5128                    .inflate(com.android.internal.R.layout.select_dialog, null);
5129            final MyArrayListAdapter adapter = new
5130                    MyArrayListAdapter(mContext, mContainers, mMultiple);
5131            AlertDialog.Builder b = new AlertDialog.Builder(mContext)
5132                    .setView(listView).setCancelable(true)
5133                    .setInverseBackgroundForced(true);
5134
5135            if (mMultiple) {
5136                b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
5137                    public void onClick(DialogInterface dialog, int which) {
5138                        mWebViewCore.sendMessage(
5139                                EventHub.LISTBOX_CHOICES,
5140                                adapter.getCount(), 0,
5141                                listView.getCheckedItemPositions());
5142                    }});
5143                b.setNegativeButton(android.R.string.cancel,
5144                        new DialogInterface.OnClickListener() {
5145                    public void onClick(DialogInterface dialog, int which) {
5146                        mWebViewCore.sendMessage(
5147                                EventHub.SINGLE_LISTBOX_CHOICE, -2, 0);
5148                }});
5149            }
5150            final AlertDialog dialog = b.create();
5151            listView.setAdapter(adapter);
5152            listView.setFocusableInTouchMode(true);
5153            // There is a bug (1250103) where the checks in a ListView with
5154            // multiple items selected are associated with the positions, not
5155            // the ids, so the items do not properly retain their checks when
5156            // filtered.  Do not allow filtering on multiple lists until
5157            // that bug is fixed.
5158
5159            listView.setTextFilterEnabled(!mMultiple);
5160            if (mMultiple) {
5161                listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
5162                int length = mSelectedArray.length;
5163                for (int i = 0; i < length; i++) {
5164                    listView.setItemChecked(mSelectedArray[i], true);
5165                }
5166            } else {
5167                listView.setOnItemClickListener(new OnItemClickListener() {
5168                    public void onItemClick(AdapterView parent, View v,
5169                            int position, long id) {
5170                        mWebViewCore.sendMessage(
5171                                EventHub.SINGLE_LISTBOX_CHOICE, (int)id, 0);
5172                        dialog.dismiss();
5173                    }
5174                });
5175                if (mSelection != -1) {
5176                    listView.setSelection(mSelection);
5177                    listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
5178                    listView.setItemChecked(mSelection, true);
5179                    DataSetObserver observer = new SingleDataSetObserver(
5180                            adapter.getItemId(mSelection), listView, adapter);
5181                    adapter.registerDataSetObserver(observer);
5182                }
5183            }
5184            dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
5185                public void onCancel(DialogInterface dialog) {
5186                    mWebViewCore.sendMessage(
5187                                EventHub.SINGLE_LISTBOX_CHOICE, -2, 0);
5188                }
5189            });
5190            dialog.show();
5191        }
5192    }
5193
5194    /*
5195     * Request a dropdown menu for a listbox with multiple selection.
5196     *
5197     * @param array Labels for the listbox.
5198     * @param enabledArray  Which positions are enabled.
5199     * @param selectedArray Which positions are initally selected.
5200     */
5201    void requestListBox(String[] array, boolean[]enabledArray, int[]
5202            selectedArray) {
5203        mPrivateHandler.post(
5204                new InvokeListBox(array, enabledArray, selectedArray));
5205    }
5206
5207    /*
5208     * Request a dropdown menu for a listbox with single selection or a single
5209     * <select> element.
5210     *
5211     * @param array Labels for the listbox.
5212     * @param enabledArray  Which positions are enabled.
5213     * @param selection Which position is initally selected.
5214     */
5215    void requestListBox(String[] array, boolean[]enabledArray, int selection) {
5216        mPrivateHandler.post(
5217                new InvokeListBox(array, enabledArray, selection));
5218    }
5219
5220    // called by JNI
5221    private void sendMoveMouse(int frame, int node, int x, int y) {
5222        mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE,
5223                new WebViewCore.CursorData(frame, node, x, y));
5224    }
5225
5226    /*
5227     * Send a mouse move event to the webcore thread.
5228     *
5229     * @param removeFocus Pass true if the "mouse" cursor is now over a node
5230     *                    which wants key events, but it is not the focus. This
5231     *                    will make the visual appear as though nothing is in
5232     *                    focus.  Remove the WebTextView, if present, and stop
5233     *                    drawing the blinking caret.
5234     * called by JNI
5235     */
5236    private void sendMoveMouseIfLatest(boolean removeFocus) {
5237        if (removeFocus) {
5238            clearTextEntry();
5239            setFocusControllerInactive();
5240        }
5241        mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE_IF_LATEST,
5242                cursorData());
5243    }
5244
5245    // called by JNI
5246    private void sendMotionUp(int touchGeneration,
5247            int frame, int node, int x, int y, int size) {
5248        WebViewCore.TouchUpData touchUpData = new WebViewCore.TouchUpData();
5249        touchUpData.mMoveGeneration = touchGeneration;
5250        touchUpData.mSize = size;
5251        touchUpData.mFrame = frame;
5252        touchUpData.mNode = node;
5253        touchUpData.mX = x;
5254        touchUpData.mY = y;
5255        mWebViewCore.sendMessage(EventHub.TOUCH_UP, touchUpData);
5256    }
5257
5258
5259    private int getScaledMaxXScroll() {
5260        int width;
5261        if (mHeightCanMeasure == false) {
5262            width = getViewWidth() / 4;
5263        } else {
5264            Rect visRect = new Rect();
5265            calcOurVisibleRect(visRect);
5266            width = visRect.width() / 2;
5267        }
5268        // FIXME the divisor should be retrieved from somewhere
5269        return viewToContent(width);
5270    }
5271
5272    private int getScaledMaxYScroll() {
5273        int height;
5274        if (mHeightCanMeasure == false) {
5275            height = getViewHeight() / 4;
5276        } else {
5277            Rect visRect = new Rect();
5278            calcOurVisibleRect(visRect);
5279            height = visRect.height() / 2;
5280        }
5281        // FIXME the divisor should be retrieved from somewhere
5282        // the closest thing today is hard-coded into ScrollView.java
5283        // (from ScrollView.java, line 363)   int maxJump = height/2;
5284        return viewToContent(height);
5285    }
5286
5287    /**
5288     * Called by JNI to invalidate view
5289     */
5290    private void viewInvalidate() {
5291        invalidate();
5292    }
5293
5294    // return true if the key was handled
5295    private boolean navHandledKey(int keyCode, int count, boolean noScroll,
5296            long time, boolean ignorePlugin) {
5297        if (mNativeClass == 0) {
5298            return false;
5299        }
5300        if (ignorePlugin == false && nativePluginEatsNavKey()) {
5301            KeyEvent event = new KeyEvent(time, time, KeyEvent.ACTION_DOWN
5302                , keyCode, count, (mShiftIsPressed ? KeyEvent.META_SHIFT_ON : 0)
5303                | (false ? KeyEvent.META_ALT_ON : 0) // FIXME
5304                | (false ? KeyEvent.META_SYM_ON : 0) // FIXME
5305                , 0, 0, 0);
5306            mWebViewCore.sendMessage(EventHub.KEY_DOWN, event);
5307            mWebViewCore.sendMessage(EventHub.KEY_UP, event);
5308            return true;
5309        }
5310        mLastCursorTime = time;
5311        mLastCursorBounds = nativeGetCursorRingBounds();
5312        boolean keyHandled
5313                = nativeMoveCursor(keyCode, count, noScroll) == false;
5314        if (DebugFlags.WEB_VIEW) {
5315            Log.v(LOGTAG, "navHandledKey mLastCursorBounds=" + mLastCursorBounds
5316                    + " mLastCursorTime=" + mLastCursorTime
5317                    + " handled=" + keyHandled);
5318        }
5319        if (keyHandled == false || mHeightCanMeasure == false) {
5320            return keyHandled;
5321        }
5322        Rect contentCursorRingBounds = nativeGetCursorRingBounds();
5323        if (contentCursorRingBounds.isEmpty()) return keyHandled;
5324        Rect viewCursorRingBounds = contentToView(contentCursorRingBounds);
5325        Rect visRect = new Rect();
5326        calcOurVisibleRect(visRect);
5327        Rect outset = new Rect(visRect);
5328        int maxXScroll = visRect.width() / 2;
5329        int maxYScroll = visRect.height() / 2;
5330        outset.inset(-maxXScroll, -maxYScroll);
5331        if (Rect.intersects(outset, viewCursorRingBounds) == false) {
5332            return keyHandled;
5333        }
5334        // FIXME: Necessary because ScrollView/ListView do not scroll left/right
5335        int maxH = Math.min(viewCursorRingBounds.right - visRect.right,
5336                maxXScroll);
5337        if (maxH > 0) {
5338            pinScrollBy(maxH, 0, true, 0);
5339        } else {
5340            maxH = Math.max(viewCursorRingBounds.left - visRect.left,
5341                    -maxXScroll);
5342            if (maxH < 0) {
5343                pinScrollBy(maxH, 0, true, 0);
5344            }
5345        }
5346        if (mLastCursorBounds.isEmpty()) return keyHandled;
5347        if (mLastCursorBounds.equals(contentCursorRingBounds)) {
5348            return keyHandled;
5349        }
5350        if (DebugFlags.WEB_VIEW) {
5351            Log.v(LOGTAG, "navHandledKey contentCursorRingBounds="
5352                    + contentCursorRingBounds);
5353        }
5354        requestRectangleOnScreen(viewCursorRingBounds);
5355        mUserScroll = true;
5356        return keyHandled;
5357    }
5358
5359    /**
5360     * Set the background color. It's white by default. Pass
5361     * zero to make the view transparent.
5362     * @param color   the ARGB color described by Color.java
5363     */
5364    public void setBackgroundColor(int color) {
5365        mBackgroundColor = color;
5366        mWebViewCore.sendMessage(EventHub.SET_BACKGROUND_COLOR, color);
5367    }
5368
5369    public void debugDump() {
5370        nativeDebugDump();
5371        mWebViewCore.sendMessage(EventHub.DUMP_NAVTREE);
5372    }
5373
5374    /**
5375     *  Update our cache with updatedText.
5376     *  @param updatedText  The new text to put in our cache.
5377     */
5378    /* package */ void updateCachedTextfield(String updatedText) {
5379        // Also place our generation number so that when we look at the cache
5380        // we recognize that it is up to date.
5381        nativeUpdateCachedTextfield(updatedText, mTextGeneration);
5382    }
5383
5384    private native void     nativeClearCursor();
5385    private native void     nativeCreate(int ptr);
5386    private native int      nativeCursorFramePointer();
5387    private native Rect     nativeCursorNodeBounds();
5388    /* package */ native int nativeCursorNodePointer();
5389    /* package */ native boolean nativeCursorMatchesFocus();
5390    private native boolean  nativeCursorIntersects(Rect visibleRect);
5391    private native boolean  nativeCursorIsAnchor();
5392    private native boolean  nativeCursorIsPlugin();
5393    private native boolean  nativeCursorIsTextInput();
5394    private native Point    nativeCursorPosition();
5395    private native String   nativeCursorText();
5396    /**
5397     * Returns true if the native cursor node says it wants to handle key events
5398     * (ala plugins). This can only be called if mNativeClass is non-zero!
5399     */
5400    private native boolean  nativeCursorWantsKeyEvents();
5401    private native void     nativeDebugDump();
5402    private native void     nativeDestroy();
5403    private native void     nativeDrawCursorRing(Canvas content);
5404    private native void     nativeDrawMatches(Canvas canvas);
5405    private native void     nativeDrawSelection(Canvas content
5406            , int x, int y, boolean extendSelection);
5407    private native void     nativeDrawSelectionRegion(Canvas content);
5408    private native void     nativeDumpDisplayTree(String urlOrNull);
5409    private native int      nativeFindAll(String findLower, String findUpper);
5410    private native void     nativeFindNext(boolean forward);
5411    private native boolean  nativeFocusCandidateIsPassword();
5412    private native boolean  nativeFocusCandidateIsRtlText();
5413    private native boolean  nativeFocusCandidateIsTextField();
5414    private native boolean  nativeFocusCandidateIsTextInput();
5415    private native int      nativeFocusCandidateMaxLength();
5416    /* package */ native String   nativeFocusCandidateName();
5417    private native Rect     nativeFocusCandidateNodeBounds();
5418    /* package */ native int nativeFocusCandidatePointer();
5419    private native String   nativeFocusCandidateText();
5420    private native int      nativeFocusCandidateTextSize();
5421    private native Rect     nativeGetCursorRingBounds();
5422    private native Region   nativeGetSelection();
5423    private native boolean  nativeHasCursorNode();
5424    private native boolean  nativeHasFocusNode();
5425    private native void     nativeHideCursor();
5426    private native String   nativeImageURI(int x, int y);
5427    private native void     nativeInstrumentReport();
5428    // return true if the page has been scrolled
5429    private native boolean  nativeMotionUp(int x, int y, int slop);
5430    // returns false if it handled the key
5431    private native boolean  nativeMoveCursor(int keyCode, int count,
5432            boolean noScroll);
5433    private native int      nativeMoveGeneration();
5434    private native void     nativeMoveSelection(int x, int y,
5435            boolean extendSelection);
5436    private native boolean  nativePluginEatsNavKey();
5437    // Like many other of our native methods, you must make sure that
5438    // mNativeClass is not null before calling this method.
5439    private native void     nativeRecordButtons(boolean focused,
5440            boolean pressed, boolean invalidate);
5441    private native void     nativeSelectBestAt(Rect rect);
5442    private native void     nativeSetFindIsDown();
5443    private native void     nativeSetFollowedLink(boolean followed);
5444    private native void     nativeSetHeightCanMeasure(boolean measure);
5445    private native int      nativeTextGeneration();
5446    // Never call this version except by updateCachedTextfield(String) -
5447    // we always want to pass in our generation number.
5448    private native void     nativeUpdateCachedTextfield(String updatedText,
5449            int generation);
5450    private native void     nativeUpdatePluginReceivesEvents();
5451}
5452