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