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