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