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