WebView.java revision f6bd0ba6308673a8b6bb9f71dd40a09d11c0d90d
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                mWebTextView.setDefaultSelection();
3414                imm.showSoftInput(mWebTextView, 0);
3415                if (zoom) {
3416                    didUpdateTextViewBounds(true);
3417                }
3418                return;
3419            }
3420        }
3421        // Used by plugins.
3422        // Also used if the navigation cache is out of date, and
3423        // does not recognize that a textfield is in focus.  In that
3424        // case, use WebView as the targeted view.
3425        // see http://b/issue?id=2457459
3426        imm.showSoftInput(this, 0);
3427    }
3428
3429    // Called by WebKit to instruct the UI to hide the keyboard
3430    private void hideSoftKeyboard() {
3431        InputMethodManager imm = (InputMethodManager)
3432                getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
3433
3434        imm.hideSoftInputFromWindow(this.getWindowToken(), 0);
3435    }
3436
3437    /*
3438     * This method checks the current focus and cursor and potentially rebuilds
3439     * mWebTextView to have the appropriate properties, such as password,
3440     * multiline, and what text it contains.  It also removes it if necessary.
3441     */
3442    /* package */ void rebuildWebTextView() {
3443        // If the WebView does not have focus, do nothing until it gains focus.
3444        if (!hasFocus() && (null == mWebTextView || !mWebTextView.hasFocus())) {
3445            return;
3446        }
3447        boolean alreadyThere = inEditingMode();
3448        // inEditingMode can only return true if mWebTextView is non-null,
3449        // so we can safely call remove() if (alreadyThere)
3450        if (0 == mNativeClass || !nativeFocusCandidateIsTextInput()) {
3451            if (alreadyThere) {
3452                mWebTextView.remove();
3453            }
3454            return;
3455        }
3456        // At this point, we know we have found an input field, so go ahead
3457        // and create the WebTextView if necessary.
3458        if (mWebTextView == null) {
3459            mWebTextView = new WebTextView(mContext, WebView.this);
3460            // Initialize our generation number.
3461            mTextGeneration = 0;
3462        }
3463        mWebTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
3464                contentToViewDimension(nativeFocusCandidateTextSize()));
3465        Rect visibleRect = new Rect();
3466        calcOurContentVisibleRect(visibleRect);
3467        // Note that sendOurVisibleRect calls viewToContent, so the coordinates
3468        // should be in content coordinates.
3469        Rect bounds = nativeFocusCandidateNodeBounds();
3470        Rect vBox = contentToViewRect(bounds);
3471        mWebTextView.setRect(vBox.left, vBox.top, vBox.width(), vBox.height());
3472        if (!Rect.intersects(bounds, visibleRect)) {
3473            mWebTextView.bringIntoView();
3474        }
3475        String text = nativeFocusCandidateText();
3476        int nodePointer = nativeFocusCandidatePointer();
3477        if (alreadyThere && mWebTextView.isSameTextField(nodePointer)) {
3478            // It is possible that we have the same textfield, but it has moved,
3479            // i.e. In the case of opening/closing the screen.
3480            // In that case, we need to set the dimensions, but not the other
3481            // aspects.
3482            // If the text has been changed by webkit, update it.  However, if
3483            // there has been more UI text input, ignore it.  We will receive
3484            // another update when that text is recognized.
3485            if (text != null && !text.equals(mWebTextView.getText().toString())
3486                    && nativeTextGeneration() == mTextGeneration) {
3487                mWebTextView.setTextAndKeepSelection(text);
3488            }
3489        } else {
3490            mWebTextView.setGravity(nativeFocusCandidateIsRtlText() ?
3491                    Gravity.RIGHT : Gravity.NO_GRAVITY);
3492            // This needs to be called before setType, which may call
3493            // requestFormData, and it needs to have the correct nodePointer.
3494            mWebTextView.setNodePointer(nodePointer);
3495            mWebTextView.setType(nativeFocusCandidateType());
3496            if (null == text) {
3497                if (DebugFlags.WEB_VIEW) {
3498                    Log.v(LOGTAG, "rebuildWebTextView null == text");
3499                }
3500                text = "";
3501            }
3502            mWebTextView.setTextAndKeepSelection(text);
3503            InputMethodManager imm = InputMethodManager.peekInstance();
3504            if (imm != null && imm.isActive(mWebTextView)) {
3505                imm.restartInput(mWebTextView);
3506            }
3507        }
3508        mWebTextView.requestFocus();
3509    }
3510
3511    /**
3512     * Called by WebTextView to find saved form data associated with the
3513     * textfield
3514     * @param name Name of the textfield.
3515     * @param nodePointer Pointer to the node of the textfield, so it can be
3516     *          compared to the currently focused textfield when the data is
3517     *          retrieved.
3518     */
3519    /* package */ void requestFormData(String name, int nodePointer) {
3520        if (mWebViewCore.getSettings().getSaveFormData()) {
3521            Message update = mPrivateHandler.obtainMessage(REQUEST_FORM_DATA);
3522            update.arg1 = nodePointer;
3523            RequestFormData updater = new RequestFormData(name, getUrl(),
3524                    update);
3525            Thread t = new Thread(updater);
3526            t.start();
3527        }
3528    }
3529
3530    /**
3531     * Pass a message to find out the <label> associated with the <input>
3532     * identified by nodePointer
3533     * @param framePointer Pointer to the frame containing the <input> node
3534     * @param nodePointer Pointer to the node for which a <label> is desired.
3535     */
3536    /* package */ void requestLabel(int framePointer, int nodePointer) {
3537        mWebViewCore.sendMessage(EventHub.REQUEST_LABEL, framePointer,
3538                nodePointer);
3539    }
3540
3541    /*
3542     * This class requests an Adapter for the WebTextView which shows past
3543     * entries stored in the database.  It is a Runnable so that it can be done
3544     * in its own thread, without slowing down the UI.
3545     */
3546    private class RequestFormData implements Runnable {
3547        private String mName;
3548        private String mUrl;
3549        private Message mUpdateMessage;
3550
3551        public RequestFormData(String name, String url, Message msg) {
3552            mName = name;
3553            mUrl = url;
3554            mUpdateMessage = msg;
3555        }
3556
3557        public void run() {
3558            ArrayList<String> pastEntries = mDatabase.getFormData(mUrl, mName);
3559            if (pastEntries.size() > 0) {
3560                AutoCompleteAdapter adapter = new
3561                        AutoCompleteAdapter(mContext, pastEntries);
3562                mUpdateMessage.obj = adapter;
3563                mUpdateMessage.sendToTarget();
3564            }
3565        }
3566    }
3567
3568    /**
3569     * Dump the display tree to "/sdcard/displayTree.txt"
3570     *
3571     * @hide debug only
3572     */
3573    public void dumpDisplayTree() {
3574        nativeDumpDisplayTree(getUrl());
3575    }
3576
3577    /**
3578     * Dump the dom tree to adb shell if "toFile" is False, otherwise dump it to
3579     * "/sdcard/domTree.txt"
3580     *
3581     * @hide debug only
3582     */
3583    public void dumpDomTree(boolean toFile) {
3584        mWebViewCore.sendMessage(EventHub.DUMP_DOMTREE, toFile ? 1 : 0, 0);
3585    }
3586
3587    /**
3588     * Dump the render tree to adb shell if "toFile" is False, otherwise dump it
3589     * to "/sdcard/renderTree.txt"
3590     *
3591     * @hide debug only
3592     */
3593    public void dumpRenderTree(boolean toFile) {
3594        mWebViewCore.sendMessage(EventHub.DUMP_RENDERTREE, toFile ? 1 : 0, 0);
3595    }
3596
3597    /**
3598     * Dump the V8 counters to standard output.
3599     * Note that you need a build with V8 and WEBCORE_INSTRUMENTATION set to
3600     * true. Otherwise, this will do nothing.
3601     *
3602     * @hide debug only
3603     */
3604    public void dumpV8Counters() {
3605        mWebViewCore.sendMessage(EventHub.DUMP_V8COUNTERS);
3606    }
3607
3608    // This is used to determine long press with the center key.  Does not
3609    // affect long press with the trackball/touch.
3610    private boolean mGotCenterDown = false;
3611
3612    @Override
3613    public boolean onKeyDown(int keyCode, KeyEvent event) {
3614        if (DebugFlags.WEB_VIEW) {
3615            Log.v(LOGTAG, "keyDown at " + System.currentTimeMillis()
3616                    + ", " + event + ", unicode=" + event.getUnicodeChar());
3617        }
3618
3619        if (mNativeClass == 0) {
3620            return false;
3621        }
3622
3623        // do this hack up front, so it always works, regardless of touch-mode
3624        if (AUTO_REDRAW_HACK && (keyCode == KeyEvent.KEYCODE_CALL)) {
3625            mAutoRedraw = !mAutoRedraw;
3626            if (mAutoRedraw) {
3627                invalidate();
3628            }
3629            return true;
3630        }
3631
3632        // Bubble up the key event if
3633        // 1. it is a system key; or
3634        // 2. the host application wants to handle it;
3635        if (event.isSystem()
3636                || mCallbackProxy.uiOverrideKeyEvent(event)) {
3637            return false;
3638        }
3639
3640        if (mShiftIsPressed == false && nativeCursorWantsKeyEvents() == false
3641                && (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT
3642                || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT)) {
3643            setUpSelectXY();
3644        }
3645
3646        if (keyCode >= KeyEvent.KEYCODE_DPAD_UP
3647                && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) {
3648            // always handle the navigation keys in the UI thread
3649            switchOutDrawHistory();
3650            if (mShiftIsPressed) {
3651                int xRate = keyCode == KeyEvent.KEYCODE_DPAD_LEFT
3652                    ? -1 : keyCode == KeyEvent.KEYCODE_DPAD_RIGHT ? 1 : 0;
3653                int yRate = keyCode == KeyEvent.KEYCODE_DPAD_UP ?
3654                    -1 : keyCode == KeyEvent.KEYCODE_DPAD_DOWN ? 1 : 0;
3655                int multiplier = event.getRepeatCount() + 1;
3656                moveSelection(xRate * multiplier, yRate * multiplier);
3657                return true;
3658            }
3659            if (navHandledKey(keyCode, 1, false, event.getEventTime(), false)) {
3660                playSoundEffect(keyCodeToSoundsEffect(keyCode));
3661                return true;
3662            }
3663            // Bubble up the key event as WebView doesn't handle it
3664            return false;
3665        }
3666
3667        if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
3668            switchOutDrawHistory();
3669            if (event.getRepeatCount() == 0) {
3670                if (mShiftIsPressed) {
3671                    return true; // discard press if copy in progress
3672                }
3673                mGotCenterDown = true;
3674                mPrivateHandler.sendMessageDelayed(mPrivateHandler
3675                        .obtainMessage(LONG_PRESS_CENTER), LONG_PRESS_TIMEOUT);
3676                // Already checked mNativeClass, so we do not need to check it
3677                // again.
3678                nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true);
3679                return true;
3680            }
3681            // Bubble up the key event as WebView doesn't handle it
3682            return false;
3683        }
3684
3685        if (keyCode != KeyEvent.KEYCODE_SHIFT_LEFT
3686                && keyCode != KeyEvent.KEYCODE_SHIFT_RIGHT) {
3687            // turn off copy select if a shift-key combo is pressed
3688            mExtendSelection = mShiftIsPressed = false;
3689            if (mTouchMode == TOUCH_SELECT_MODE) {
3690                mTouchMode = TOUCH_INIT_MODE;
3691            }
3692        }
3693
3694        if (getSettings().getNavDump()) {
3695            switch (keyCode) {
3696                case KeyEvent.KEYCODE_4:
3697                    dumpDisplayTree();
3698                    break;
3699                case KeyEvent.KEYCODE_5:
3700                case KeyEvent.KEYCODE_6:
3701                    dumpDomTree(keyCode == KeyEvent.KEYCODE_5);
3702                    break;
3703                case KeyEvent.KEYCODE_7:
3704                case KeyEvent.KEYCODE_8:
3705                    dumpRenderTree(keyCode == KeyEvent.KEYCODE_7);
3706                    break;
3707                case KeyEvent.KEYCODE_9:
3708                    nativeInstrumentReport();
3709                    return true;
3710            }
3711        }
3712
3713        if (nativeCursorIsTextInput()) {
3714            // This message will put the node in focus, for the DOM's notion
3715            // of focus, and make the focuscontroller active
3716            mWebViewCore.sendMessage(EventHub.CLICK, nativeCursorFramePointer(),
3717                    nativeCursorNodePointer());
3718            // This will bring up the WebTextView and put it in focus, for
3719            // our view system's notion of focus
3720            rebuildWebTextView();
3721            // Now we need to pass the event to it
3722            if (inEditingMode()) {
3723                mWebTextView.setDefaultSelection();
3724                return mWebTextView.dispatchKeyEvent(event);
3725            }
3726        } else if (nativeHasFocusNode()) {
3727            // In this case, the cursor is not on a text input, but the focus
3728            // might be.  Check it, and if so, hand over to the WebTextView.
3729            rebuildWebTextView();
3730            if (inEditingMode()) {
3731                mWebTextView.setDefaultSelection();
3732                return mWebTextView.dispatchKeyEvent(event);
3733            }
3734        }
3735
3736        // TODO: should we pass all the keys to DOM or check the meta tag
3737        if (nativeCursorWantsKeyEvents() || true) {
3738            // pass the key to DOM
3739            mWebViewCore.sendMessage(EventHub.KEY_DOWN, event);
3740            // return true as DOM handles the key
3741            return true;
3742        }
3743
3744        // Bubble up the key event as WebView doesn't handle it
3745        return false;
3746    }
3747
3748    @Override
3749    public boolean onKeyUp(int keyCode, KeyEvent event) {
3750        if (DebugFlags.WEB_VIEW) {
3751            Log.v(LOGTAG, "keyUp at " + System.currentTimeMillis()
3752                    + ", " + event + ", unicode=" + event.getUnicodeChar());
3753        }
3754
3755        if (mNativeClass == 0) {
3756            return false;
3757        }
3758
3759        // special CALL handling when cursor node's href is "tel:XXX"
3760        if (keyCode == KeyEvent.KEYCODE_CALL && nativeHasCursorNode()) {
3761            String text = nativeCursorText();
3762            if (!nativeCursorIsTextInput() && text != null
3763                    && text.startsWith(SCHEME_TEL)) {
3764                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(text));
3765                getContext().startActivity(intent);
3766                return true;
3767            }
3768        }
3769
3770        // Bubble up the key event if
3771        // 1. it is a system key; or
3772        // 2. the host application wants to handle it;
3773        if (event.isSystem() || mCallbackProxy.uiOverrideKeyEvent(event)) {
3774            return false;
3775        }
3776
3777        if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT
3778                || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT) {
3779            if (commitCopy()) {
3780                return true;
3781            }
3782        }
3783
3784        if (keyCode >= KeyEvent.KEYCODE_DPAD_UP
3785                && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) {
3786            // always handle the navigation keys in the UI thread
3787            // Bubble up the key event as WebView doesn't handle it
3788            return false;
3789        }
3790
3791        if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
3792            // remove the long press message first
3793            mPrivateHandler.removeMessages(LONG_PRESS_CENTER);
3794            mGotCenterDown = false;
3795
3796            if (mShiftIsPressed) {
3797                if (mExtendSelection) {
3798                    commitCopy();
3799                } else {
3800                    mExtendSelection = true;
3801                    invalidate(); // draw the i-beam instead of the arrow
3802                }
3803                return true; // discard press if copy in progress
3804            }
3805
3806            // perform the single click
3807            Rect visibleRect = sendOurVisibleRect();
3808            // Note that sendOurVisibleRect calls viewToContent, so the
3809            // coordinates should be in content coordinates.
3810            if (!nativeCursorIntersects(visibleRect)) {
3811                return false;
3812            }
3813            WebViewCore.CursorData data = cursorData();
3814            mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE, data);
3815            playSoundEffect(SoundEffectConstants.CLICK);
3816            if (nativeCursorIsTextInput()) {
3817                rebuildWebTextView();
3818                centerKeyPressOnTextField();
3819                if (inEditingMode()) {
3820                    mWebTextView.setDefaultSelection();
3821                }
3822                return true;
3823            }
3824            clearTextEntry(true);
3825            nativeSetFollowedLink(true);
3826            if (!mCallbackProxy.uiOverrideUrlLoading(nativeCursorText())) {
3827                mWebViewCore.sendMessage(EventHub.CLICK, data.mFrame,
3828                        nativeCursorNodePointer());
3829            }
3830            return true;
3831        }
3832
3833        // TODO: should we pass all the keys to DOM or check the meta tag
3834        if (nativeCursorWantsKeyEvents() || true) {
3835            // pass the key to DOM
3836            mWebViewCore.sendMessage(EventHub.KEY_UP, event);
3837            // return true as DOM handles the key
3838            return true;
3839        }
3840
3841        // Bubble up the key event as WebView doesn't handle it
3842        return false;
3843    }
3844
3845    private void setUpSelectXY() {
3846        mExtendSelection = false;
3847        mShiftIsPressed = true;
3848        if (nativeHasCursorNode()) {
3849            Rect rect = nativeCursorNodeBounds();
3850            mSelectX = contentToViewX(rect.left);
3851            mSelectY = contentToViewY(rect.top);
3852        } else if (mLastTouchY > getVisibleTitleHeight()) {
3853            mSelectX = mScrollX + (int) mLastTouchX;
3854            mSelectY = mScrollY + (int) mLastTouchY;
3855        } else {
3856            mSelectX = mScrollX + getViewWidth() / 2;
3857            mSelectY = mScrollY + getViewHeightWithTitle() / 2;
3858        }
3859        nativeHideCursor();
3860    }
3861
3862    public void emulateShiftHeld() {
3863        if (0 == mNativeClass) return; // client isn't initialized
3864        setUpSelectXY();
3865    }
3866
3867    private boolean commitCopy() {
3868        boolean copiedSomething = false;
3869        if (mExtendSelection) {
3870            String selection = nativeGetSelection();
3871            if (selection != "") {
3872                if (DebugFlags.WEB_VIEW) {
3873                    Log.v(LOGTAG, "commitCopy \"" + selection + "\"");
3874                }
3875                Toast.makeText(mContext
3876                        , com.android.internal.R.string.text_copied
3877                        , Toast.LENGTH_SHORT).show();
3878                copiedSomething = true;
3879                try {
3880                    IClipboard clip = IClipboard.Stub.asInterface(
3881                            ServiceManager.getService("clipboard"));
3882                            clip.setClipboardText(selection);
3883                } catch (android.os.RemoteException e) {
3884                    Log.e(LOGTAG, "Clipboard failed", e);
3885                }
3886            }
3887            mExtendSelection = false;
3888        }
3889        mShiftIsPressed = false;
3890        invalidate(); // remove selection region and pointer
3891        if (mTouchMode == TOUCH_SELECT_MODE) {
3892            mTouchMode = TOUCH_INIT_MODE;
3893        }
3894        return copiedSomething;
3895    }
3896
3897    @Override
3898    protected void onAttachedToWindow() {
3899        super.onAttachedToWindow();
3900        if (hasWindowFocus()) onWindowFocusChanged(true);
3901    }
3902
3903    @Override
3904    protected void onDetachedFromWindow() {
3905        clearTextEntry(false);
3906        super.onDetachedFromWindow();
3907        // Clean up the zoom controller
3908        mZoomButtonsController.setVisible(false);
3909    }
3910
3911    /**
3912     * @deprecated WebView no longer needs to implement
3913     * ViewGroup.OnHierarchyChangeListener.  This method does nothing now.
3914     */
3915    @Deprecated
3916    public void onChildViewAdded(View parent, View child) {}
3917
3918    /**
3919     * @deprecated WebView no longer needs to implement
3920     * ViewGroup.OnHierarchyChangeListener.  This method does nothing now.
3921     */
3922    @Deprecated
3923    public void onChildViewRemoved(View p, View child) {}
3924
3925    /**
3926     * @deprecated WebView should not have implemented
3927     * ViewTreeObserver.OnGlobalFocusChangeListener.  This method
3928     * does nothing now.
3929     */
3930    @Deprecated
3931    public void onGlobalFocusChanged(View oldFocus, View newFocus) {
3932    }
3933
3934    // To avoid drawing the cursor ring, and remove the TextView when our window
3935    // loses focus.
3936    @Override
3937    public void onWindowFocusChanged(boolean hasWindowFocus) {
3938        if (hasWindowFocus) {
3939            if (hasFocus()) {
3940                // If our window regained focus, and we have focus, then begin
3941                // drawing the cursor ring
3942                mDrawCursorRing = true;
3943                if (mNativeClass != 0) {
3944                    nativeRecordButtons(true, false, true);
3945                    if (inEditingMode()) {
3946                        mWebViewCore.sendMessage(EventHub.SET_ACTIVE, 1, 0);
3947                    }
3948                }
3949            } else {
3950                // If our window gained focus, but we do not have it, do not
3951                // draw the cursor ring.
3952                mDrawCursorRing = false;
3953                // We do not call nativeRecordButtons here because we assume
3954                // that when we lost focus, or window focus, it got called with
3955                // false for the first parameter
3956            }
3957        } else {
3958            if (getSettings().getBuiltInZoomControls() && !mZoomButtonsController.isVisible()) {
3959                /*
3960                 * The zoom controls come in their own window, so our window
3961                 * loses focus. Our policy is to not draw the cursor ring if
3962                 * our window is not focused, but this is an exception since
3963                 * the user can still navigate the web page with the zoom
3964                 * controls showing.
3965                 */
3966                // If our window has lost focus, stop drawing the cursor ring
3967                mDrawCursorRing = false;
3968            }
3969            mGotKeyDown = false;
3970            mShiftIsPressed = false;
3971            if (mNativeClass != 0) {
3972                nativeRecordButtons(false, false, true);
3973            }
3974            setFocusControllerInactive();
3975        }
3976        invalidate();
3977        super.onWindowFocusChanged(hasWindowFocus);
3978    }
3979
3980    /*
3981     * Pass a message to WebCore Thread, telling the WebCore::Page's
3982     * FocusController to be  "inactive" so that it will
3983     * not draw the blinking cursor.  It gets set to "active" to draw the cursor
3984     * in WebViewCore.cpp, when the WebCore thread receives key events/clicks.
3985     */
3986    /* package */ void setFocusControllerInactive() {
3987        // Do not need to also check whether mWebViewCore is null, because
3988        // mNativeClass is only set if mWebViewCore is non null
3989        if (mNativeClass == 0) return;
3990        mWebViewCore.sendMessage(EventHub.SET_ACTIVE, 0, 0);
3991    }
3992
3993    @Override
3994    protected void onFocusChanged(boolean focused, int direction,
3995            Rect previouslyFocusedRect) {
3996        if (DebugFlags.WEB_VIEW) {
3997            Log.v(LOGTAG, "MT focusChanged " + focused + ", " + direction);
3998        }
3999        if (focused) {
4000            // When we regain focus, if we have window focus, resume drawing
4001            // the cursor ring
4002            if (hasWindowFocus()) {
4003                mDrawCursorRing = true;
4004                if (mNativeClass != 0) {
4005                    nativeRecordButtons(true, false, true);
4006                }
4007            //} else {
4008                // The WebView has gained focus while we do not have
4009                // windowfocus.  When our window lost focus, we should have
4010                // called nativeRecordButtons(false...)
4011            }
4012        } else {
4013            // When we lost focus, unless focus went to the TextView (which is
4014            // true if we are in editing mode), stop drawing the cursor ring.
4015            if (!inEditingMode()) {
4016                mDrawCursorRing = false;
4017                if (mNativeClass != 0) {
4018                    nativeRecordButtons(false, false, true);
4019                }
4020                setFocusControllerInactive();
4021            }
4022            mGotKeyDown = false;
4023        }
4024
4025        super.onFocusChanged(focused, direction, previouslyFocusedRect);
4026    }
4027
4028    /**
4029     * @hide
4030     */
4031    @Override
4032    protected boolean setFrame(int left, int top, int right, int bottom) {
4033        boolean changed = super.setFrame(left, top, right, bottom);
4034        if (!changed && mHeightCanMeasure) {
4035            // When mHeightCanMeasure is true, we will set mLastHeightSent to 0
4036            // in WebViewCore after we get the first layout. We do call
4037            // requestLayout() when we get contentSizeChanged(). But the View
4038            // system won't call onSizeChanged if the dimension is not changed.
4039            // In this case, we need to call sendViewSizeZoom() explicitly to
4040            // notify the WebKit about the new dimensions.
4041            sendViewSizeZoom();
4042        }
4043        return changed;
4044    }
4045
4046    private static class PostScale implements Runnable {
4047        final WebView mWebView;
4048        final boolean mUpdateTextWrap;
4049
4050        public PostScale(WebView webView, boolean updateTextWrap) {
4051            mWebView = webView;
4052            mUpdateTextWrap = updateTextWrap;
4053        }
4054
4055        public void run() {
4056            if (mWebView.mWebViewCore != null) {
4057                // we always force, in case our height changed, in which case we
4058                // still want to send the notification over to webkit.
4059                mWebView.setNewZoomScale(mWebView.mActualScale,
4060                        mUpdateTextWrap, true);
4061                // update the zoom buttons as the scale can be changed
4062                if (mWebView.getSettings().getBuiltInZoomControls()) {
4063                    mWebView.updateZoomButtonsEnabled();
4064                }
4065            }
4066        }
4067    }
4068
4069    @Override
4070    protected void onSizeChanged(int w, int h, int ow, int oh) {
4071        super.onSizeChanged(w, h, ow, oh);
4072        // Center zooming to the center of the screen.
4073        if (mZoomScale == 0) { // unless we're already zooming
4074            // To anchor at top left corner.
4075            mZoomCenterX = 0;
4076            mZoomCenterY = getVisibleTitleHeight();
4077            mAnchorX = viewToContentX((int) mZoomCenterX + mScrollX);
4078            mAnchorY = viewToContentY((int) mZoomCenterY + mScrollY);
4079        }
4080
4081        // adjust the max viewport width depending on the view dimensions. This
4082        // is to ensure the scaling is not going insane. So do not shrink it if
4083        // the view size is temporarily smaller, e.g. when soft keyboard is up.
4084        int newMaxViewportWidth = (int) (Math.max(w, h) / DEFAULT_MIN_ZOOM_SCALE);
4085        if (newMaxViewportWidth > sMaxViewportWidth) {
4086            sMaxViewportWidth = newMaxViewportWidth;
4087        }
4088
4089        // update mMinZoomScale if the minimum zoom scale is not fixed
4090        if (!mMinZoomScaleFixed) {
4091            // when change from narrow screen to wide screen, the new viewWidth
4092            // can be wider than the old content width. We limit the minimum
4093            // scale to 1.0f. The proper minimum scale will be calculated when
4094            // the new picture shows up.
4095            mMinZoomScale = Math.min(1.0f, (float) getViewWidth()
4096                    / (mDrawHistory ? mHistoryPicture.getWidth()
4097                            : mZoomOverviewWidth));
4098            if (mInitialScaleInPercent > 0) {
4099                // limit the minZoomScale to the initialScale if it is set
4100                float initialScale = mInitialScaleInPercent / 100.0f;
4101                if (mMinZoomScale > initialScale) {
4102                    mMinZoomScale = initialScale;
4103                }
4104            }
4105        }
4106
4107        // onSizeChanged() is called during WebView layout. And any
4108        // requestLayout() is blocked during layout. As setNewZoomScale() will
4109        // call its child View to reposition itself through ViewManager's
4110        // scaleAll(), we need to post a Runnable to ensure requestLayout().
4111        // <b/>
4112        // only update the text wrap scale if width changed.
4113        post(new PostScale(this, w != ow));
4114    }
4115
4116    @Override
4117    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
4118        super.onScrollChanged(l, t, oldl, oldt);
4119        sendOurVisibleRect();
4120        // update WebKit if visible title bar height changed. The logic is same
4121        // as getVisibleTitleHeight.
4122        int titleHeight = getTitleHeight();
4123        if (Math.max(titleHeight - t, 0) != Math.max(titleHeight - oldt, 0)) {
4124            sendViewSizeZoom();
4125        }
4126    }
4127
4128    @Override
4129    public boolean dispatchKeyEvent(KeyEvent event) {
4130        boolean dispatch = true;
4131
4132        if (!inEditingMode()) {
4133            if (event.getAction() == KeyEvent.ACTION_DOWN) {
4134                mGotKeyDown = true;
4135            } else {
4136                if (!mGotKeyDown) {
4137                    /*
4138                     * We got a key up for which we were not the recipient of
4139                     * the original key down. Don't give it to the view.
4140                     */
4141                    dispatch = false;
4142                }
4143                mGotKeyDown = false;
4144            }
4145        }
4146
4147        if (dispatch) {
4148            return super.dispatchKeyEvent(event);
4149        } else {
4150            // We didn't dispatch, so let something else handle the key
4151            return false;
4152        }
4153    }
4154
4155    // Here are the snap align logic:
4156    // 1. If it starts nearly horizontally or vertically, snap align;
4157    // 2. If there is a dramitic direction change, let it go;
4158    // 3. If there is a same direction back and forth, lock it.
4159
4160    // adjustable parameters
4161    private int mMinLockSnapReverseDistance;
4162    private static final float MAX_SLOPE_FOR_DIAG = 1.5f;
4163    private static final int MIN_BREAK_SNAP_CROSS_DISTANCE = 80;
4164
4165    private static int sign(float x) {
4166        return x > 0 ? 1 : (x < 0 ? -1 : 0);
4167    }
4168
4169    // if the page can scroll <= this value, we won't allow the drag tracker
4170    // to have any effect.
4171    private static final int MIN_SCROLL_AMOUNT_TO_DISABLE_DRAG_TRACKER = 4;
4172
4173    private class DragTrackerHandler {
4174        private final DragTracker mProxy;
4175        private final float mStartY, mStartX;
4176        private final float mMinDY, mMinDX;
4177        private final float mMaxDY, mMaxDX;
4178        private float mCurrStretchY, mCurrStretchX;
4179        private int mSX, mSY;
4180        private Interpolator mInterp;
4181        private float[] mXY = new float[2];
4182
4183        // inner (non-state) classes can't have enums :(
4184        private static final int DRAGGING_STATE = 0;
4185        private static final int ANIMATING_STATE = 1;
4186        private static final int FINISHED_STATE = 2;
4187        private int mState;
4188
4189        public DragTrackerHandler(float x, float y, DragTracker proxy) {
4190            mProxy = proxy;
4191
4192            int docBottom = computeVerticalScrollRange() + getTitleHeight();
4193            int viewTop = getScrollY();
4194            int viewBottom = viewTop + getHeight();
4195
4196            mStartY = y;
4197            mMinDY = -viewTop;
4198            mMaxDY = docBottom - viewBottom;
4199
4200            if (DebugFlags.DRAG_TRACKER || DEBUG_DRAG_TRACKER) {
4201                Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, " dragtracker y= " + y +
4202                      " up/down= " + mMinDY + " " + mMaxDY);
4203            }
4204
4205            int docRight = computeHorizontalScrollRange();
4206            int viewLeft = getScrollX();
4207            int viewRight = viewLeft + getWidth();
4208            mStartX = x;
4209            mMinDX = -viewLeft;
4210            mMaxDX = docRight - viewRight;
4211
4212            mState = DRAGGING_STATE;
4213            mProxy.onStartDrag(x, y);
4214
4215            // ensure we buildBitmap at least once
4216            mSX = -99999;
4217        }
4218
4219        private float computeStretch(float delta, float min, float max) {
4220            float stretch = 0;
4221            if (max - min > MIN_SCROLL_AMOUNT_TO_DISABLE_DRAG_TRACKER) {
4222                if (delta < min) {
4223                    stretch = delta - min;
4224                } else if (delta > max) {
4225                    stretch = delta - max;
4226                }
4227            }
4228            return stretch;
4229        }
4230
4231        public void dragTo(float x, float y) {
4232            float sy = computeStretch(mStartY - y, mMinDY, mMaxDY);
4233            float sx = computeStretch(mStartX - x, mMinDX, mMaxDX);
4234
4235            if ((mSnapScrollMode & SNAP_X) != 0) {
4236                sy = 0;
4237            } else if ((mSnapScrollMode & SNAP_Y) != 0) {
4238                sx = 0;
4239            }
4240
4241            if (mCurrStretchX != sx || mCurrStretchY != sy) {
4242                mCurrStretchX = sx;
4243                mCurrStretchY = sy;
4244                if (DebugFlags.DRAG_TRACKER || DEBUG_DRAG_TRACKER) {
4245                    Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, "---- stretch " + sx +
4246                          " " + sy);
4247                }
4248                if (mProxy.onStretchChange(sx, sy)) {
4249                    invalidate();
4250                }
4251            }
4252        }
4253
4254        public void stopDrag() {
4255            final int DURATION = 200;
4256            int now = (int)SystemClock.uptimeMillis();
4257            mInterp = new Interpolator(2);
4258            mXY[0] = mCurrStretchX;
4259            mXY[1] = mCurrStretchY;
4260         //   float[] blend = new float[] { 0.5f, 0, 0.75f, 1 };
4261            float[] blend = new float[] { 0, 0.5f, 0.75f, 1 };
4262            mInterp.setKeyFrame(0, now, mXY, blend);
4263            float[] zerozero = new float[] { 0, 0 };
4264            mInterp.setKeyFrame(1, now + DURATION, zerozero, null);
4265            mState = ANIMATING_STATE;
4266
4267            if (DebugFlags.DRAG_TRACKER || DEBUG_DRAG_TRACKER) {
4268                Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, "----- stopDrag, starting animation");
4269            }
4270        }
4271
4272        // Call this after each draw. If it ruturns null, the tracker is done
4273        public boolean isFinished() {
4274            return mState == FINISHED_STATE;
4275        }
4276
4277        private int hiddenHeightOfTitleBar() {
4278            return getTitleHeight() - getVisibleTitleHeight();
4279        }
4280
4281        // need a way to know if 565 or 8888 is the right config for
4282        // capturing the display and giving it to the drag proxy
4283        private Bitmap.Config offscreenBitmapConfig() {
4284            // hard code 565 for now
4285            return Bitmap.Config.RGB_565;
4286        }
4287
4288        /*  If the tracker draws, then this returns true, otherwise it will
4289            return false, and draw nothing.
4290         */
4291        public boolean draw(Canvas canvas) {
4292            if (mCurrStretchX != 0 || mCurrStretchY != 0) {
4293                int sx = getScrollX();
4294                int sy = getScrollY() - hiddenHeightOfTitleBar();
4295                if (mSX != sx || mSY != sy) {
4296                    buildBitmap(sx, sy);
4297                    mSX = sx;
4298                    mSY = sy;
4299                }
4300
4301                if (mState == ANIMATING_STATE) {
4302                    Interpolator.Result result = mInterp.timeToValues(mXY);
4303                    if (result == Interpolator.Result.FREEZE_END) {
4304                        mState = FINISHED_STATE;
4305                        return false;
4306                    } else {
4307                        mProxy.onStretchChange(mXY[0], mXY[1]);
4308                        invalidate();
4309                        // fall through to the draw
4310                    }
4311                }
4312                int count = canvas.save(Canvas.MATRIX_SAVE_FLAG);
4313                canvas.translate(sx, sy);
4314                mProxy.onDraw(canvas);
4315                canvas.restoreToCount(count);
4316                return true;
4317            }
4318            if (DebugFlags.DRAG_TRACKER || DEBUG_DRAG_TRACKER) {
4319                Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, " -- draw false " +
4320                      mCurrStretchX + " " + mCurrStretchY);
4321            }
4322            return false;
4323        }
4324
4325        private void buildBitmap(int sx, int sy) {
4326            int w = getWidth();
4327            int h = getViewHeight();
4328            Bitmap bm = Bitmap.createBitmap(w, h, offscreenBitmapConfig());
4329            Canvas canvas = new Canvas(bm);
4330            canvas.translate(-sx, -sy);
4331            drawContent(canvas);
4332
4333            if (DebugFlags.DRAG_TRACKER || DEBUG_DRAG_TRACKER) {
4334                Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, "--- buildBitmap " + sx +
4335                      " " + sy + " " + w + " " + h);
4336            }
4337            mProxy.onBitmapChange(bm);
4338        }
4339    }
4340
4341    /** @hide */
4342    public static class DragTracker {
4343        public void onStartDrag(float x, float y) {}
4344        public boolean onStretchChange(float sx, float sy) {
4345            // return true to have us inval the view
4346            return false;
4347        }
4348        public void onStopDrag() {}
4349        public void onBitmapChange(Bitmap bm) {}
4350        public void onDraw(Canvas canvas) {}
4351    }
4352
4353    /** @hide */
4354    public DragTracker getDragTracker() {
4355        return mDragTracker;
4356    }
4357
4358    /** @hide */
4359    public void setDragTracker(DragTracker tracker) {
4360        mDragTracker = tracker;
4361    }
4362
4363    private DragTracker mDragTracker;
4364    private DragTrackerHandler mDragTrackerHandler;
4365
4366    private class ScaleDetectorListener implements
4367            ScaleGestureDetector.OnScaleGestureListener {
4368
4369        public boolean onScaleBegin(ScaleGestureDetector detector) {
4370            // cancel the single touch handling
4371            cancelTouch();
4372            if (mZoomButtonsController.isVisible()) {
4373                mZoomButtonsController.setVisible(false);
4374            }
4375            // reset the zoom overview mode so that the page won't auto grow
4376            mInZoomOverview = false;
4377            // If it is in password mode, turn it off so it does not draw
4378            // misplaced.
4379            if (inEditingMode() && nativeFocusCandidateIsPassword()) {
4380                mWebTextView.setInPassword(false);
4381            }
4382            return true;
4383        }
4384
4385        public void onScaleEnd(ScaleGestureDetector detector) {
4386            if (mPreviewZoomOnly) {
4387                mPreviewZoomOnly = false;
4388                mAnchorX = viewToContentX((int) mZoomCenterX + mScrollX);
4389                mAnchorY = viewToContentY((int) mZoomCenterY + mScrollY);
4390                // don't reflow when zoom in; when zoom out, do reflow if the
4391                // new scale is almost minimum scale;
4392                boolean reflowNow = (mActualScale - mMinZoomScale <= 0.01f)
4393                        || ((mActualScale <= 0.8 * mTextWrapScale));
4394                // force zoom after mPreviewZoomOnly is set to false so that the
4395                // new view size will be passed to the WebKit
4396                setNewZoomScale(mActualScale, reflowNow, true);
4397                // call invalidate() to draw without zoom filter
4398                invalidate();
4399            }
4400            // adjust the edit text view if needed
4401            if (inEditingMode() && didUpdateTextViewBounds(false)
4402                    && nativeFocusCandidateIsPassword()) {
4403                // If it is a password field, start drawing the
4404                // WebTextView once again.
4405                mWebTextView.setInPassword(true);
4406            }
4407            // start a drag, TOUCH_PINCH_DRAG, can't use TOUCH_INIT_MODE as it
4408            // may trigger the unwanted click, can't use TOUCH_DRAG_MODE as it
4409            // may trigger the unwanted fling.
4410            mTouchMode = TOUCH_PINCH_DRAG;
4411            startTouch(detector.getFocusX(), detector.getFocusY(),
4412                    mLastTouchTime);
4413        }
4414
4415        public boolean onScale(ScaleGestureDetector detector) {
4416            float scale = (float) (Math.round(detector.getScaleFactor()
4417                    * mActualScale * 100) / 100.0);
4418            if (Math.abs(scale - mActualScale) >= PREVIEW_SCALE_INCREMENT) {
4419                mPreviewZoomOnly = true;
4420                // limit the scale change per step
4421                if (scale > mActualScale) {
4422                    scale = Math.min(scale, mActualScale * 1.25f);
4423                } else {
4424                    scale = Math.max(scale, mActualScale * 0.8f);
4425                }
4426                mZoomCenterX = detector.getFocusX();
4427                mZoomCenterY = detector.getFocusY();
4428                setNewZoomScale(scale, false, false);
4429                invalidate();
4430                return true;
4431            }
4432            return false;
4433        }
4434    }
4435
4436    @Override
4437    public boolean onTouchEvent(MotionEvent ev) {
4438        if (mNativeClass == 0 || !isClickable() || !isLongClickable()) {
4439            return false;
4440        }
4441
4442        if (DebugFlags.WEB_VIEW) {
4443            Log.v(LOGTAG, ev + " at " + ev.getEventTime() + " mTouchMode="
4444                    + mTouchMode);
4445        }
4446
4447        int action;
4448        float x, y;
4449        long eventTime = ev.getEventTime();
4450
4451        // FIXME: we may consider to give WebKit an option to handle multi-touch
4452        // events later.
4453        if (mSupportMultiTouch && ev.getPointerCount() > 1) {
4454            if (mMinZoomScale < mMaxZoomScale) {
4455                mScaleDetector.onTouchEvent(ev);
4456                if (mScaleDetector.isInProgress()) {
4457                    mLastTouchTime = eventTime;
4458                    return true;
4459                }
4460                x = mScaleDetector.getFocusX();
4461                y = mScaleDetector.getFocusY();
4462                action = ev.getAction() & MotionEvent.ACTION_MASK;
4463                if (action == MotionEvent.ACTION_POINTER_DOWN) {
4464                    cancelTouch();
4465                    action = MotionEvent.ACTION_DOWN;
4466                } else if (action == MotionEvent.ACTION_POINTER_UP) {
4467                    // set mLastTouchX/Y to the remaining point
4468                    mLastTouchX = x;
4469                    mLastTouchY = y;
4470                } else if (action == MotionEvent.ACTION_MOVE) {
4471                    // negative x or y indicate it is on the edge, skip it.
4472                    if (x < 0 || y < 0) {
4473                        return true;
4474                    }
4475                }
4476            } else {
4477                // if the page disallow zoom, skip multi-pointer action
4478                return true;
4479            }
4480        } else {
4481            action = ev.getAction();
4482            x = ev.getX();
4483            y = ev.getY();
4484        }
4485
4486        // Due to the touch screen edge effect, a touch closer to the edge
4487        // always snapped to the edge. As getViewWidth() can be different from
4488        // getWidth() due to the scrollbar, adjusting the point to match
4489        // getViewWidth(). Same applied to the height.
4490        if (x > getViewWidth() - 1) {
4491            x = getViewWidth() - 1;
4492        }
4493        if (y > getViewHeightWithTitle() - 1) {
4494            y = getViewHeightWithTitle() - 1;
4495        }
4496
4497        // pass the touch events, except ACTION_MOVE which will be handled
4498        // later, from UI thread to WebCore thread
4499        if (mFullScreenHolder != null || (mForwardTouchEvents
4500                && action != MotionEvent.ACTION_MOVE
4501                && (action == MotionEvent.ACTION_DOWN || mPreventDrag
4502                        != PREVENT_DRAG_CANCEL))) {
4503            WebViewCore.TouchEventData ted = new WebViewCore.TouchEventData();
4504            ted.mAction = action;
4505            ted.mX = viewToContentX((int) x + mScrollX);
4506            ted.mY = viewToContentY((int) y + mScrollY);
4507            ted.mEventTime = eventTime;
4508            ted.mMetaState = ev.getMetaState();
4509            mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
4510            mLastSentTouchTime = eventTime;
4511        }
4512
4513        float fDeltaX = mLastTouchX - x;
4514        float fDeltaY = mLastTouchY - y;
4515        int deltaX = (int) fDeltaX;
4516        int deltaY = (int) fDeltaY;
4517
4518        switch (action) {
4519            case MotionEvent.ACTION_DOWN: {
4520                mPreventDrag = PREVENT_DRAG_NO;
4521                if (!mScroller.isFinished()) {
4522                    // stop the current scroll animation, but if this is
4523                    // the start of a fling, allow it to add to the current
4524                    // fling's velocity
4525                    mScroller.abortAnimation();
4526                    mTouchMode = TOUCH_DRAG_START_MODE;
4527                    mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY);
4528                } else if (mShiftIsPressed) {
4529                    mSelectX = mScrollX + (int) x;
4530                    mSelectY = mScrollY + (int) y;
4531                    mTouchMode = TOUCH_SELECT_MODE;
4532                    if (DebugFlags.WEB_VIEW) {
4533                        Log.v(LOGTAG, "select=" + mSelectX + "," + mSelectY);
4534                    }
4535                    nativeMoveSelection(viewToContentX(mSelectX),
4536                            viewToContentY(mSelectY), false);
4537                    mTouchSelection = mExtendSelection = true;
4538                    invalidate(); // draw the i-beam instead of the arrow
4539                } else if (mPrivateHandler.hasMessages(RELEASE_SINGLE_TAP)) {
4540                    mPrivateHandler.removeMessages(RELEASE_SINGLE_TAP);
4541                    if (deltaX * deltaX + deltaY * deltaY < mDoubleTapSlopSquare) {
4542                        mTouchMode = TOUCH_DOUBLE_TAP_MODE;
4543                    } else {
4544                        // commit the short press action for the previous tap
4545                        doShortPress();
4546                        // continue, mTouchMode should be still TOUCH_INIT_MODE
4547                    }
4548                } else {
4549                    mPreviewZoomOnly = false;
4550                    mTouchMode = TOUCH_INIT_MODE;
4551                    mPreventDrag = mForwardTouchEvents ? PREVENT_DRAG_MAYBE_YES
4552                            : PREVENT_DRAG_NO;
4553                    mPreventLongPress = false;
4554                    mPreventDoubleTap = false;
4555                    mWebViewCore.sendMessage(
4556                            EventHub.UPDATE_FRAME_CACHE_IF_LOADING);
4557                    if (mLogEvent && eventTime - mLastTouchUpTime < 1000) {
4558                        EventLog.writeEvent(EventLogTags.BROWSER_DOUBLE_TAP_DURATION,
4559                                (eventTime - mLastTouchUpTime), eventTime);
4560                    }
4561                }
4562                // Trigger the link
4563                if (mTouchMode == TOUCH_INIT_MODE
4564                        || mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
4565                    mPrivateHandler.sendMessageDelayed(mPrivateHandler
4566                            .obtainMessage(SWITCH_TO_SHORTPRESS), TAP_TIMEOUT);
4567                }
4568                startTouch(x, y, eventTime);
4569                break;
4570            }
4571            case MotionEvent.ACTION_MOVE: {
4572                if (mTouchMode == TOUCH_DONE_MODE) {
4573                    // no dragging during scroll zoom animation
4574                    break;
4575                }
4576                mVelocityTracker.addMovement(ev);
4577
4578                if (mTouchMode != TOUCH_DRAG_MODE) {
4579                    if (mTouchMode == TOUCH_SELECT_MODE) {
4580                        mSelectX = mScrollX + (int) x;
4581                        mSelectY = mScrollY + (int) y;
4582                        if (DebugFlags.WEB_VIEW) {
4583                            Log.v(LOGTAG, "xtend=" + mSelectX + "," + mSelectY);
4584                        }
4585                        nativeMoveSelection(viewToContentX(mSelectX),
4586                               viewToContentY(mSelectY), true);
4587                        invalidate();
4588                        break;
4589                    }
4590                    if ((deltaX * deltaX + deltaY * deltaY) < mTouchSlopSquare) {
4591                        break;
4592                    }
4593
4594                    // pass the first ACTION_MOVE from UI thread to WebCore
4595                    // thread after the distance is confirmed that it is a drag
4596                    if (mFullScreenHolder == null && mForwardTouchEvents
4597                            && mPreventDrag != PREVENT_DRAG_CANCEL) {
4598                        WebViewCore.TouchEventData ted = new WebViewCore.TouchEventData();
4599                        ted.mAction = action;
4600                        ted.mX = viewToContentX((int) x + mScrollX);
4601                        ted.mY = viewToContentY((int) y + mScrollY);
4602                        ted.mEventTime = eventTime;
4603                        ted.mMetaState = ev.getMetaState();
4604                        mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
4605                        mLastSentTouchTime = eventTime;
4606                    }
4607
4608                    if (mPreventDrag == PREVENT_DRAG_MAYBE_YES) {
4609                        // track mLastTouchTime as we may need to do fling at
4610                        // ACTION_UP
4611                        mLastTouchTime = eventTime;
4612                        break;
4613                    }
4614                    if (mTouchMode == TOUCH_SHORTPRESS_MODE
4615                            || mTouchMode == TOUCH_SHORTPRESS_START_MODE) {
4616                        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
4617                    } else if (mTouchMode == TOUCH_INIT_MODE
4618                            || mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
4619                        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
4620                    }
4621                    if (mFullScreenHolder != null) {
4622                        // in full screen mode, the WebView can't be panned.
4623                        mTouchMode = TOUCH_DONE_MODE;
4624                        break;
4625                    }
4626
4627                    // if it starts nearly horizontal or vertical, enforce it
4628                    int ax = Math.abs(deltaX);
4629                    int ay = Math.abs(deltaY);
4630                    if (ax > MAX_SLOPE_FOR_DIAG * ay) {
4631                        mSnapScrollMode = SNAP_X;
4632                        mSnapPositive = deltaX > 0;
4633                    } else if (ay > MAX_SLOPE_FOR_DIAG * ax) {
4634                        mSnapScrollMode = SNAP_Y;
4635                        mSnapPositive = deltaY > 0;
4636                    }
4637
4638                    mTouchMode = TOUCH_DRAG_MODE;
4639                    mLastTouchX = x;
4640                    mLastTouchY = y;
4641                    fDeltaX = 0.0f;
4642                    fDeltaY = 0.0f;
4643                    deltaX = 0;
4644                    deltaY = 0;
4645
4646                    WebViewCore.reducePriority();
4647                    if (!mDragFromTextInput) {
4648                        nativeHideCursor();
4649                    }
4650                    WebSettings settings = getSettings();
4651                    if (settings.supportZoom()
4652                            && settings.getBuiltInZoomControls()
4653                            && !mZoomButtonsController.isVisible()
4654                            && mMinZoomScale < mMaxZoomScale) {
4655                        mZoomButtonsController.setVisible(true);
4656                        int count = settings.getDoubleTapToastCount();
4657                        if (mInZoomOverview && count > 0) {
4658                            settings.setDoubleTapToastCount(--count);
4659                            Toast.makeText(mContext,
4660                                    com.android.internal.R.string.double_tap_toast,
4661                                    Toast.LENGTH_LONG).show();
4662                        }
4663                    }
4664                } else {
4665                    // pass the touch events from UI thread to WebCore thread
4666                    if (mFullScreenHolder == null && mForwardTouchEvents
4667                            && eventTime - mLastSentTouchTime > mCurrentTouchInterval
4668                            && mPreventDrag != PREVENT_DRAG_CANCEL) {
4669                        WebViewCore.TouchEventData ted = new WebViewCore.TouchEventData();
4670                        ted.mAction = action;
4671                        ted.mX = viewToContentX((int) x + mScrollX);
4672                        ted.mY = viewToContentY((int) y + mScrollY);
4673                        ted.mEventTime = eventTime;
4674                        ted.mMetaState = ev.getMetaState();
4675                        mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
4676                        mLastSentTouchTime = eventTime;
4677                    }
4678                }
4679
4680                // do pan
4681                int newScrollX = pinLocX(mScrollX + deltaX);
4682                int newDeltaX = newScrollX - mScrollX;
4683                if (deltaX != newDeltaX) {
4684                    deltaX = newDeltaX;
4685                    fDeltaX = (float) newDeltaX;
4686                }
4687                int newScrollY = pinLocY(mScrollY + deltaY);
4688                int newDeltaY = newScrollY - mScrollY;
4689                if (deltaY != newDeltaY) {
4690                    deltaY = newDeltaY;
4691                    fDeltaY = (float) newDeltaY;
4692                }
4693                boolean done = false;
4694                boolean keepScrollBarsVisible = false;
4695                if (Math.abs(fDeltaX) < 1.0f && Math.abs(fDeltaY) < 1.0f) {
4696                    keepScrollBarsVisible = done = true;
4697                } else {
4698                    if (mSnapScrollMode == SNAP_X || mSnapScrollMode == SNAP_Y) {
4699                        int ax = Math.abs(deltaX);
4700                        int ay = Math.abs(deltaY);
4701                        if (mSnapScrollMode == SNAP_X) {
4702                            // radical change means getting out of snap mode
4703                            if (ay > MAX_SLOPE_FOR_DIAG * ax
4704                                    && ay > MIN_BREAK_SNAP_CROSS_DISTANCE) {
4705                                mSnapScrollMode = SNAP_NONE;
4706                            }
4707                            // reverse direction means lock in the snap mode
4708                            if (ax > MAX_SLOPE_FOR_DIAG * ay &&
4709                                    (mSnapPositive
4710                                    ? deltaX < -mMinLockSnapReverseDistance
4711                                    : deltaX > mMinLockSnapReverseDistance)) {
4712                                mSnapScrollMode |= SNAP_LOCK;
4713                            }
4714                        } else {
4715                            // radical change means getting out of snap mode
4716                            if (ax > MAX_SLOPE_FOR_DIAG * ay
4717                                    && ax > MIN_BREAK_SNAP_CROSS_DISTANCE) {
4718                                mSnapScrollMode = SNAP_NONE;
4719                            }
4720                            // reverse direction means lock in the snap mode
4721                            if (ay > MAX_SLOPE_FOR_DIAG * ax &&
4722                                    (mSnapPositive
4723                                    ? deltaY < -mMinLockSnapReverseDistance
4724                                    : deltaY > mMinLockSnapReverseDistance)) {
4725                                mSnapScrollMode |= SNAP_LOCK;
4726                            }
4727                        }
4728                    }
4729                    if (mSnapScrollMode != SNAP_NONE) {
4730                        if ((mSnapScrollMode & SNAP_X) == SNAP_X) {
4731                            deltaY = 0;
4732                        } else {
4733                            deltaX = 0;
4734                        }
4735                    }
4736                    if ((deltaX | deltaY) != 0) {
4737                        scrollBy(deltaX, deltaY);
4738                        if (deltaX != 0) {
4739                            mLastTouchX = x;
4740                        }
4741                        if (deltaY != 0) {
4742                            mLastTouchY = y;
4743                        }
4744                        mHeldMotionless = MOTIONLESS_FALSE;
4745                    } else {
4746                        // keep the scrollbar on the screen even there is no
4747                        // scroll
4748                        keepScrollBarsVisible = true;
4749                    }
4750                    mLastTouchTime = eventTime;
4751                    mUserScroll = true;
4752                }
4753
4754                if (!getSettings().getBuiltInZoomControls()) {
4755                    boolean showPlusMinus = mMinZoomScale < mMaxZoomScale;
4756                    if (mZoomControls != null && showPlusMinus) {
4757                        if (mZoomControls.getVisibility() == View.VISIBLE) {
4758                            mPrivateHandler.removeCallbacks(mZoomControlRunnable);
4759                        } else {
4760                            mZoomControls.show(showPlusMinus, false);
4761                        }
4762                        mPrivateHandler.postDelayed(mZoomControlRunnable,
4763                                ZOOM_CONTROLS_TIMEOUT);
4764                    }
4765                }
4766
4767                if (mDragTrackerHandler != null) {
4768                    mDragTrackerHandler.dragTo(x, y);
4769                }
4770
4771                if (keepScrollBarsVisible) {
4772                    if (mHeldMotionless != MOTIONLESS_TRUE) {
4773                        mHeldMotionless = MOTIONLESS_TRUE;
4774                        invalidate();
4775                    }
4776                    // keep the scrollbar on the screen even there is no scroll
4777                    awakenScrollBars(ViewConfiguration.getScrollDefaultDelay(),
4778                            false);
4779                    // return false to indicate that we can't pan out of the
4780                    // view space
4781                    return !done;
4782                }
4783                break;
4784            }
4785            case MotionEvent.ACTION_UP: {
4786                if (mDragTrackerHandler != null) {
4787                    mDragTrackerHandler.stopDrag();
4788                }
4789                mLastTouchUpTime = eventTime;
4790                switch (mTouchMode) {
4791                    case TOUCH_DOUBLE_TAP_MODE: // double tap
4792                        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
4793                        mTouchMode = TOUCH_DONE_MODE;
4794                        if (mPreventDoubleTap) {
4795                            WebViewCore.TouchEventData ted
4796                                    = new WebViewCore.TouchEventData();
4797                            ted.mAction = WebViewCore.ACTION_DOUBLETAP;
4798                            ted.mX = viewToContentX((int) x + mScrollX);
4799                            ted.mY = viewToContentY((int) y + mScrollY);
4800                            ted.mEventTime = eventTime;
4801                            ted.mMetaState = ev.getMetaState();
4802                            mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
4803                        } else if (mFullScreenHolder == null) {
4804                            doDoubleTap();
4805                        }
4806                        break;
4807                    case TOUCH_SELECT_MODE:
4808                        commitCopy();
4809                        mTouchSelection = false;
4810                        break;
4811                    case TOUCH_INIT_MODE: // tap
4812                    case TOUCH_SHORTPRESS_START_MODE:
4813                    case TOUCH_SHORTPRESS_MODE:
4814                        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
4815                        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
4816                        if ((deltaX * deltaX + deltaY * deltaY) > mTouchSlopSquare) {
4817                            Log.w(LOGTAG, "Miss a drag as we are waiting for" +
4818                                    " WebCore's response for touch down.");
4819                            if (mFullScreenHolder == null
4820                                    && (computeHorizontalScrollExtent() < computeHorizontalScrollRange()
4821                                    || computeVerticalScrollExtent() < computeVerticalScrollRange())) {
4822                                // remove the pending TOUCH_EVENT and send a
4823                                // cancel
4824                                mWebViewCore
4825                                        .removeMessages(EventHub.TOUCH_EVENT);
4826                                WebViewCore.TouchEventData ted = new WebViewCore.TouchEventData();
4827                                ted.mAction = MotionEvent.ACTION_CANCEL;
4828                                mWebViewCore.sendMessage(EventHub.TOUCH_EVENT,
4829                                        ted);
4830                                // we will not rewrite drag code here, but we
4831                                // will try fling if it applies.
4832                                WebViewCore.reducePriority();
4833                                // fall through to TOUCH_DRAG_MODE
4834                            } else {
4835                                break;
4836                            }
4837                        } else {
4838                            // mPreventDrag can be PREVENT_DRAG_MAYBE_YES in
4839                            // TOUCH_INIT_MODE. To give WebCoreThread a little
4840                            // more time to send PREVENT_TOUCH_ID, we check
4841                            // again in responding RELEASE_SINGLE_TAP.
4842                            if (mPreventDrag != PREVENT_DRAG_YES) {
4843                                if (mTouchMode == TOUCH_INIT_MODE) {
4844                                    mPrivateHandler.sendMessageDelayed(
4845                                            mPrivateHandler.obtainMessage(
4846                                            RELEASE_SINGLE_TAP),
4847                                            ViewConfiguration.getDoubleTapTimeout());
4848                                } else {
4849                                    mTouchMode = TOUCH_DONE_MODE;
4850                                    doShortPress();
4851                                }
4852                            }
4853                            break;
4854                        }
4855                    case TOUCH_DRAG_MODE:
4856                        mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
4857                        mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS);
4858                        mHeldMotionless = MOTIONLESS_TRUE;
4859                        // redraw in high-quality, as we're done dragging
4860                        invalidate();
4861                        // if the user waits a while w/o moving before the
4862                        // up, we don't want to do a fling
4863                        if (eventTime - mLastTouchTime <= MIN_FLING_TIME) {
4864                            mVelocityTracker.addMovement(ev);
4865                            doFling();
4866                            break;
4867                        }
4868                        mLastVelocity = 0;
4869                        WebViewCore.resumePriority();
4870                        break;
4871                    case TOUCH_DRAG_START_MODE:
4872                    case TOUCH_DONE_MODE:
4873                        // do nothing
4874                        break;
4875                }
4876                // we also use mVelocityTracker == null to tell us that we are
4877                // not "moving around", so we can take the slower/prettier
4878                // mode in the drawing code
4879                if (mVelocityTracker != null) {
4880                    mVelocityTracker.recycle();
4881                    mVelocityTracker = null;
4882                }
4883                break;
4884            }
4885            case MotionEvent.ACTION_CANCEL: {
4886                cancelTouch();
4887                break;
4888            }
4889        }
4890        return true;
4891    }
4892
4893    private void startTouch(float x, float y, long eventTime) {
4894        // Remember where the motion event started
4895        mLastTouchX = x;
4896        mLastTouchY = y;
4897        mLastTouchTime = eventTime;
4898        mVelocityTracker = VelocityTracker.obtain();
4899        mSnapScrollMode = SNAP_NONE;
4900        if (mDragTracker != null) {
4901            mDragTrackerHandler = new DragTrackerHandler(x, y, mDragTracker);
4902        }
4903    }
4904
4905    private void cancelTouch() {
4906        if (mDragTrackerHandler != null) {
4907            mDragTrackerHandler.stopDrag();
4908        }
4909        // we also use mVelocityTracker == null to tell us that we are
4910        // not "moving around", so we can take the slower/prettier
4911        // mode in the drawing code
4912        if (mVelocityTracker != null) {
4913            mVelocityTracker.recycle();
4914            mVelocityTracker = null;
4915        }
4916        if (mTouchMode == TOUCH_DRAG_MODE) {
4917            WebViewCore.resumePriority();
4918        }
4919        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
4920        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
4921        mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
4922        mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS);
4923        mHeldMotionless = MOTIONLESS_TRUE;
4924        mTouchMode = TOUCH_DONE_MODE;
4925        nativeHideCursor();
4926    }
4927
4928    private long mTrackballFirstTime = 0;
4929    private long mTrackballLastTime = 0;
4930    private float mTrackballRemainsX = 0.0f;
4931    private float mTrackballRemainsY = 0.0f;
4932    private int mTrackballXMove = 0;
4933    private int mTrackballYMove = 0;
4934    private boolean mExtendSelection = false;
4935    private boolean mTouchSelection = false;
4936    private static final int TRACKBALL_KEY_TIMEOUT = 1000;
4937    private static final int TRACKBALL_TIMEOUT = 200;
4938    private static final int TRACKBALL_WAIT = 100;
4939    private static final int TRACKBALL_SCALE = 400;
4940    private static final int TRACKBALL_SCROLL_COUNT = 5;
4941    private static final int TRACKBALL_MOVE_COUNT = 10;
4942    private static final int TRACKBALL_MULTIPLIER = 3;
4943    private static final int SELECT_CURSOR_OFFSET = 16;
4944    private int mSelectX = 0;
4945    private int mSelectY = 0;
4946    private boolean mFocusSizeChanged = false;
4947    private boolean mShiftIsPressed = false;
4948    private boolean mTrackballDown = false;
4949    private long mTrackballUpTime = 0;
4950    private long mLastCursorTime = 0;
4951    private Rect mLastCursorBounds;
4952
4953    // Set by default; BrowserActivity clears to interpret trackball data
4954    // directly for movement. Currently, the framework only passes
4955    // arrow key events, not trackball events, from one child to the next
4956    private boolean mMapTrackballToArrowKeys = true;
4957
4958    public void setMapTrackballToArrowKeys(boolean setMap) {
4959        mMapTrackballToArrowKeys = setMap;
4960    }
4961
4962    void resetTrackballTime() {
4963        mTrackballLastTime = 0;
4964    }
4965
4966    @Override
4967    public boolean onTrackballEvent(MotionEvent ev) {
4968        long time = ev.getEventTime();
4969        if ((ev.getMetaState() & KeyEvent.META_ALT_ON) != 0) {
4970            if (ev.getY() > 0) pageDown(true);
4971            if (ev.getY() < 0) pageUp(true);
4972            return true;
4973        }
4974        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
4975            if (mShiftIsPressed) {
4976                return true; // discard press if copy in progress
4977            }
4978            mTrackballDown = true;
4979            if (mNativeClass == 0) {
4980                return false;
4981            }
4982            nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true);
4983            if (time - mLastCursorTime <= TRACKBALL_TIMEOUT
4984                    && !mLastCursorBounds.equals(nativeGetCursorRingBounds())) {
4985                nativeSelectBestAt(mLastCursorBounds);
4986            }
4987            if (DebugFlags.WEB_VIEW) {
4988                Log.v(LOGTAG, "onTrackballEvent down ev=" + ev
4989                        + " time=" + time
4990                        + " mLastCursorTime=" + mLastCursorTime);
4991            }
4992            if (isInTouchMode()) requestFocusFromTouch();
4993            return false; // let common code in onKeyDown at it
4994        }
4995        if (ev.getAction() == MotionEvent.ACTION_UP) {
4996            // LONG_PRESS_CENTER is set in common onKeyDown
4997            mPrivateHandler.removeMessages(LONG_PRESS_CENTER);
4998            mTrackballDown = false;
4999            mTrackballUpTime = time;
5000            if (mShiftIsPressed) {
5001                if (mExtendSelection) {
5002                    commitCopy();
5003                } else {
5004                    mExtendSelection = true;
5005                    invalidate(); // draw the i-beam instead of the arrow
5006                }
5007                return true; // discard press if copy in progress
5008            }
5009            if (DebugFlags.WEB_VIEW) {
5010                Log.v(LOGTAG, "onTrackballEvent up ev=" + ev
5011                        + " time=" + time
5012                );
5013            }
5014            return false; // let common code in onKeyUp at it
5015        }
5016        if (mMapTrackballToArrowKeys && mShiftIsPressed == false) {
5017            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent gmail quit");
5018            return false;
5019        }
5020        if (mTrackballDown) {
5021            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent down quit");
5022            return true; // discard move if trackball is down
5023        }
5024        if (time - mTrackballUpTime < TRACKBALL_TIMEOUT) {
5025            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent up timeout quit");
5026            return true;
5027        }
5028        // TODO: alternatively we can do panning as touch does
5029        switchOutDrawHistory();
5030        if (time - mTrackballLastTime > TRACKBALL_TIMEOUT) {
5031            if (DebugFlags.WEB_VIEW) {
5032                Log.v(LOGTAG, "onTrackballEvent time="
5033                        + time + " last=" + mTrackballLastTime);
5034            }
5035            mTrackballFirstTime = time;
5036            mTrackballXMove = mTrackballYMove = 0;
5037        }
5038        mTrackballLastTime = time;
5039        if (DebugFlags.WEB_VIEW) {
5040            Log.v(LOGTAG, "onTrackballEvent ev=" + ev + " time=" + time);
5041        }
5042        mTrackballRemainsX += ev.getX();
5043        mTrackballRemainsY += ev.getY();
5044        doTrackball(time);
5045        return true;
5046    }
5047
5048    void moveSelection(float xRate, float yRate) {
5049        if (mNativeClass == 0)
5050            return;
5051        int width = getViewWidth();
5052        int height = getViewHeight();
5053        mSelectX += xRate;
5054        mSelectY += yRate;
5055        int maxX = width + mScrollX;
5056        int maxY = height + mScrollY;
5057        mSelectX = Math.min(maxX, Math.max(mScrollX - SELECT_CURSOR_OFFSET
5058                , mSelectX));
5059        mSelectY = Math.min(maxY, Math.max(mScrollY - SELECT_CURSOR_OFFSET
5060                , mSelectY));
5061        if (DebugFlags.WEB_VIEW) {
5062            Log.v(LOGTAG, "moveSelection"
5063                    + " mSelectX=" + mSelectX
5064                    + " mSelectY=" + mSelectY
5065                    + " mScrollX=" + mScrollX
5066                    + " mScrollY=" + mScrollY
5067                    + " xRate=" + xRate
5068                    + " yRate=" + yRate
5069                    );
5070        }
5071        nativeMoveSelection(viewToContentX(mSelectX),
5072                viewToContentY(mSelectY), mExtendSelection);
5073        int scrollX = mSelectX < mScrollX ? -SELECT_CURSOR_OFFSET
5074                : mSelectX > maxX - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET
5075                : 0;
5076        int scrollY = mSelectY < mScrollY ? -SELECT_CURSOR_OFFSET
5077                : mSelectY > maxY - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET
5078                : 0;
5079        pinScrollBy(scrollX, scrollY, true, 0);
5080        Rect select = new Rect(mSelectX, mSelectY, mSelectX + 1, mSelectY + 1);
5081        requestRectangleOnScreen(select);
5082        invalidate();
5083   }
5084
5085    private int scaleTrackballX(float xRate, int width) {
5086        int xMove = (int) (xRate / TRACKBALL_SCALE * width);
5087        int nextXMove = xMove;
5088        if (xMove > 0) {
5089            if (xMove > mTrackballXMove) {
5090                xMove -= mTrackballXMove;
5091            }
5092        } else if (xMove < mTrackballXMove) {
5093            xMove -= mTrackballXMove;
5094        }
5095        mTrackballXMove = nextXMove;
5096        return xMove;
5097    }
5098
5099    private int scaleTrackballY(float yRate, int height) {
5100        int yMove = (int) (yRate / TRACKBALL_SCALE * height);
5101        int nextYMove = yMove;
5102        if (yMove > 0) {
5103            if (yMove > mTrackballYMove) {
5104                yMove -= mTrackballYMove;
5105            }
5106        } else if (yMove < mTrackballYMove) {
5107            yMove -= mTrackballYMove;
5108        }
5109        mTrackballYMove = nextYMove;
5110        return yMove;
5111    }
5112
5113    private int keyCodeToSoundsEffect(int keyCode) {
5114        switch(keyCode) {
5115            case KeyEvent.KEYCODE_DPAD_UP:
5116                return SoundEffectConstants.NAVIGATION_UP;
5117            case KeyEvent.KEYCODE_DPAD_RIGHT:
5118                return SoundEffectConstants.NAVIGATION_RIGHT;
5119            case KeyEvent.KEYCODE_DPAD_DOWN:
5120                return SoundEffectConstants.NAVIGATION_DOWN;
5121            case KeyEvent.KEYCODE_DPAD_LEFT:
5122                return SoundEffectConstants.NAVIGATION_LEFT;
5123        }
5124        throw new IllegalArgumentException("keyCode must be one of " +
5125                "{KEYCODE_DPAD_UP, KEYCODE_DPAD_RIGHT, KEYCODE_DPAD_DOWN, " +
5126                "KEYCODE_DPAD_LEFT}.");
5127    }
5128
5129    private void doTrackball(long time) {
5130        int elapsed = (int) (mTrackballLastTime - mTrackballFirstTime);
5131        if (elapsed == 0) {
5132            elapsed = TRACKBALL_TIMEOUT;
5133        }
5134        float xRate = mTrackballRemainsX * 1000 / elapsed;
5135        float yRate = mTrackballRemainsY * 1000 / elapsed;
5136        int viewWidth = getViewWidth();
5137        int viewHeight = getViewHeight();
5138        if (mShiftIsPressed) {
5139            moveSelection(scaleTrackballX(xRate, viewWidth),
5140                    scaleTrackballY(yRate, viewHeight));
5141            mTrackballRemainsX = mTrackballRemainsY = 0;
5142            return;
5143        }
5144        float ax = Math.abs(xRate);
5145        float ay = Math.abs(yRate);
5146        float maxA = Math.max(ax, ay);
5147        if (DebugFlags.WEB_VIEW) {
5148            Log.v(LOGTAG, "doTrackball elapsed=" + elapsed
5149                    + " xRate=" + xRate
5150                    + " yRate=" + yRate
5151                    + " mTrackballRemainsX=" + mTrackballRemainsX
5152                    + " mTrackballRemainsY=" + mTrackballRemainsY);
5153        }
5154        int width = mContentWidth - viewWidth;
5155        int height = mContentHeight - viewHeight;
5156        if (width < 0) width = 0;
5157        if (height < 0) height = 0;
5158        ax = Math.abs(mTrackballRemainsX * TRACKBALL_MULTIPLIER);
5159        ay = Math.abs(mTrackballRemainsY * TRACKBALL_MULTIPLIER);
5160        maxA = Math.max(ax, ay);
5161        int count = Math.max(0, (int) maxA);
5162        int oldScrollX = mScrollX;
5163        int oldScrollY = mScrollY;
5164        if (count > 0) {
5165            int selectKeyCode = ax < ay ? mTrackballRemainsY < 0 ?
5166                    KeyEvent.KEYCODE_DPAD_UP : KeyEvent.KEYCODE_DPAD_DOWN :
5167                    mTrackballRemainsX < 0 ? KeyEvent.KEYCODE_DPAD_LEFT :
5168                    KeyEvent.KEYCODE_DPAD_RIGHT;
5169            count = Math.min(count, TRACKBALL_MOVE_COUNT);
5170            if (DebugFlags.WEB_VIEW) {
5171                Log.v(LOGTAG, "doTrackball keyCode=" + selectKeyCode
5172                        + " count=" + count
5173                        + " mTrackballRemainsX=" + mTrackballRemainsX
5174                        + " mTrackballRemainsY=" + mTrackballRemainsY);
5175            }
5176            if (navHandledKey(selectKeyCode, count, false, time, false)) {
5177                playSoundEffect(keyCodeToSoundsEffect(selectKeyCode));
5178            }
5179            mTrackballRemainsX = mTrackballRemainsY = 0;
5180        }
5181        if (count >= TRACKBALL_SCROLL_COUNT) {
5182            int xMove = scaleTrackballX(xRate, width);
5183            int yMove = scaleTrackballY(yRate, height);
5184            if (DebugFlags.WEB_VIEW) {
5185                Log.v(LOGTAG, "doTrackball pinScrollBy"
5186                        + " count=" + count
5187                        + " xMove=" + xMove + " yMove=" + yMove
5188                        + " mScrollX-oldScrollX=" + (mScrollX-oldScrollX)
5189                        + " mScrollY-oldScrollY=" + (mScrollY-oldScrollY)
5190                        );
5191            }
5192            if (Math.abs(mScrollX - oldScrollX) > Math.abs(xMove)) {
5193                xMove = 0;
5194            }
5195            if (Math.abs(mScrollY - oldScrollY) > Math.abs(yMove)) {
5196                yMove = 0;
5197            }
5198            if (xMove != 0 || yMove != 0) {
5199                pinScrollBy(xMove, yMove, true, 0);
5200            }
5201            mUserScroll = true;
5202        }
5203    }
5204
5205    private int computeMaxScrollY() {
5206        int maxContentH = computeVerticalScrollRange() + getTitleHeight();
5207        return Math.max(maxContentH - getViewHeightWithTitle(), getTitleHeight());
5208    }
5209
5210    public void flingScroll(int vx, int vy) {
5211        int maxX = Math.max(computeHorizontalScrollRange() - getViewWidth(), 0);
5212        int maxY = computeMaxScrollY();
5213
5214        mScroller.fling(mScrollX, mScrollY, vx, vy, 0, maxX, 0, maxY);
5215        invalidate();
5216    }
5217
5218    private void doFling() {
5219        if (mVelocityTracker == null) {
5220            return;
5221        }
5222        int maxX = Math.max(computeHorizontalScrollRange() - getViewWidth(), 0);
5223        int maxY = computeMaxScrollY();
5224
5225        mVelocityTracker.computeCurrentVelocity(1000, mMaximumFling);
5226        int vx = (int) mVelocityTracker.getXVelocity();
5227        int vy = (int) mVelocityTracker.getYVelocity();
5228
5229        if (mSnapScrollMode != SNAP_NONE) {
5230            if ((mSnapScrollMode & SNAP_X) == SNAP_X) {
5231                vy = 0;
5232            } else {
5233                vx = 0;
5234            }
5235        }
5236
5237        if (true /* EMG release: make our fling more like Maps' */) {
5238            // maps cuts their velocity in half
5239            vx = vx * 3 / 4;
5240            vy = vy * 3 / 4;
5241        }
5242        if ((maxX == 0 && vy == 0) || (maxY == 0 && vx == 0)) {
5243            WebViewCore.resumePriority();
5244            return;
5245        }
5246        float currentVelocity = mScroller.getCurrVelocity();
5247        if (mLastVelocity > 0 && currentVelocity > 0) {
5248            float deltaR = (float) (Math.abs(Math.atan2(mLastVelY, mLastVelX)
5249                    - Math.atan2(vy, vx)));
5250            final float circle = (float) (Math.PI) * 2.0f;
5251            if (deltaR > circle * 0.9f || deltaR < circle * 0.1f) {
5252                vx += currentVelocity * mLastVelX / mLastVelocity;
5253                vy += currentVelocity * mLastVelY / mLastVelocity;
5254                if (DebugFlags.WEB_VIEW) {
5255                    Log.v(LOGTAG, "doFling vx= " + vx + " vy=" + vy);
5256                }
5257            } else if (DebugFlags.WEB_VIEW) {
5258                Log.v(LOGTAG, "doFling missed " + deltaR / circle);
5259            }
5260        } else if (DebugFlags.WEB_VIEW) {
5261            Log.v(LOGTAG, "doFling start last=" + mLastVelocity
5262                    + " current=" + currentVelocity
5263                    + " vx=" + vx + " vy=" + vy
5264                    + " maxX=" + maxX + " maxY=" + maxY
5265                    + " mScrollX=" + mScrollX + " mScrollY=" + mScrollY);
5266        }
5267        mLastVelX = vx;
5268        mLastVelY = vy;
5269        mLastVelocity = (float) Math.hypot(vx, vy);
5270
5271        mScroller.fling(mScrollX, mScrollY, -vx, -vy, 0, maxX, 0, maxY);
5272        // TODO: duration is calculated based on velocity, if the range is
5273        // small, the animation will stop before duration is up. We may
5274        // want to calculate how long the animation is going to run to precisely
5275        // resume the webcore update.
5276        final int time = mScroller.getDuration();
5277        mPrivateHandler.sendEmptyMessageDelayed(RESUME_WEBCORE_PRIORITY, time);
5278        awakenScrollBars(time);
5279        invalidate();
5280    }
5281
5282    private boolean zoomWithPreview(float scale) {
5283        float oldScale = mActualScale;
5284        mInitialScrollX = mScrollX;
5285        mInitialScrollY = mScrollY;
5286
5287        // snap to DEFAULT_SCALE if it is close
5288        if (scale > (mDefaultScale - 0.05) && scale < (mDefaultScale + 0.05)) {
5289            scale = mDefaultScale;
5290        }
5291
5292        setNewZoomScale(scale, true, false);
5293
5294        if (oldScale != mActualScale) {
5295            // use mZoomPickerScale to see zoom preview first
5296            mZoomStart = SystemClock.uptimeMillis();
5297            mInvInitialZoomScale = 1.0f / oldScale;
5298            mInvFinalZoomScale = 1.0f / mActualScale;
5299            mZoomScale = mActualScale;
5300            WebViewCore.pauseUpdatePicture(mWebViewCore);
5301            invalidate();
5302            return true;
5303        } else {
5304            return false;
5305        }
5306    }
5307
5308    /**
5309     * Returns a view containing zoom controls i.e. +/- buttons. The caller is
5310     * in charge of installing this view to the view hierarchy. This view will
5311     * become visible when the user starts scrolling via touch and fade away if
5312     * the user does not interact with it.
5313     * <p/>
5314     * API version 3 introduces a built-in zoom mechanism that is shown
5315     * automatically by the MapView. This is the preferred approach for
5316     * showing the zoom UI.
5317     *
5318     * @deprecated The built-in zoom mechanism is preferred, see
5319     *             {@link WebSettings#setBuiltInZoomControls(boolean)}.
5320     */
5321    @Deprecated
5322    public View getZoomControls() {
5323        if (!getSettings().supportZoom()) {
5324            Log.w(LOGTAG, "This WebView doesn't support zoom.");
5325            return null;
5326        }
5327        if (mZoomControls == null) {
5328            mZoomControls = createZoomControls();
5329
5330            /*
5331             * need to be set to VISIBLE first so that getMeasuredHeight() in
5332             * {@link #onSizeChanged()} can return the measured value for proper
5333             * layout.
5334             */
5335            mZoomControls.setVisibility(View.VISIBLE);
5336            mZoomControlRunnable = new Runnable() {
5337                public void run() {
5338
5339                    /* Don't dismiss the controls if the user has
5340                     * focus on them. Wait and check again later.
5341                     */
5342                    if (!mZoomControls.hasFocus()) {
5343                        mZoomControls.hide();
5344                    } else {
5345                        mPrivateHandler.removeCallbacks(mZoomControlRunnable);
5346                        mPrivateHandler.postDelayed(mZoomControlRunnable,
5347                                ZOOM_CONTROLS_TIMEOUT);
5348                    }
5349                }
5350            };
5351        }
5352        return mZoomControls;
5353    }
5354
5355    private ExtendedZoomControls createZoomControls() {
5356        ExtendedZoomControls zoomControls = new ExtendedZoomControls(mContext
5357            , null);
5358        zoomControls.setOnZoomInClickListener(new OnClickListener() {
5359            public void onClick(View v) {
5360                // reset time out
5361                mPrivateHandler.removeCallbacks(mZoomControlRunnable);
5362                mPrivateHandler.postDelayed(mZoomControlRunnable,
5363                        ZOOM_CONTROLS_TIMEOUT);
5364                zoomIn();
5365            }
5366        });
5367        zoomControls.setOnZoomOutClickListener(new OnClickListener() {
5368            public void onClick(View v) {
5369                // reset time out
5370                mPrivateHandler.removeCallbacks(mZoomControlRunnable);
5371                mPrivateHandler.postDelayed(mZoomControlRunnable,
5372                        ZOOM_CONTROLS_TIMEOUT);
5373                zoomOut();
5374            }
5375        });
5376        return zoomControls;
5377    }
5378
5379    /**
5380     * Gets the {@link ZoomButtonsController} which can be used to add
5381     * additional buttons to the zoom controls window.
5382     *
5383     * @return The instance of {@link ZoomButtonsController} used by this class,
5384     *         or null if it is unavailable.
5385     * @hide
5386     */
5387    public ZoomButtonsController getZoomButtonsController() {
5388        return mZoomButtonsController;
5389    }
5390
5391    /**
5392     * Perform zoom in in the webview
5393     * @return TRUE if zoom in succeeds. FALSE if no zoom changes.
5394     */
5395    public boolean zoomIn() {
5396        // TODO: alternatively we can disallow this during draw history mode
5397        switchOutDrawHistory();
5398        mInZoomOverview = false;
5399        // Center zooming to the center of the screen.
5400        mZoomCenterX = getViewWidth() * .5f;
5401        mZoomCenterY = getViewHeight() * .5f;
5402        mAnchorX = viewToContentX((int) mZoomCenterX + mScrollX);
5403        mAnchorY = viewToContentY((int) mZoomCenterY + mScrollY);
5404        return zoomWithPreview(mActualScale * 1.25f);
5405    }
5406
5407    /**
5408     * Perform zoom out in the webview
5409     * @return TRUE if zoom out succeeds. FALSE if no zoom changes.
5410     */
5411    public boolean zoomOut() {
5412        // TODO: alternatively we can disallow this during draw history mode
5413        switchOutDrawHistory();
5414        // Center zooming to the center of the screen.
5415        mZoomCenterX = getViewWidth() * .5f;
5416        mZoomCenterY = getViewHeight() * .5f;
5417        mAnchorX = viewToContentX((int) mZoomCenterX + mScrollX);
5418        mAnchorY = viewToContentY((int) mZoomCenterY + mScrollY);
5419        return zoomWithPreview(mActualScale * 0.8f);
5420    }
5421
5422    private void updateSelection() {
5423        if (mNativeClass == 0) {
5424            return;
5425        }
5426        // mLastTouchX and mLastTouchY are the point in the current viewport
5427        int contentX = viewToContentX((int) mLastTouchX + mScrollX);
5428        int contentY = viewToContentY((int) mLastTouchY + mScrollY);
5429        Rect rect = new Rect(contentX - mNavSlop, contentY - mNavSlop,
5430                contentX + mNavSlop, contentY + mNavSlop);
5431        nativeSelectBestAt(rect);
5432    }
5433
5434    /**
5435     * Scroll the focused text field/area to match the WebTextView
5436     * @param xPercent New x position of the WebTextView from 0 to 1.
5437     * @param y New y position of the WebTextView in view coordinates
5438     */
5439    /*package*/ void scrollFocusedTextInput(float xPercent, int y) {
5440        if (!inEditingMode() || mWebViewCore == null) {
5441            return;
5442        }
5443        mWebViewCore.sendMessage(EventHub.SCROLL_TEXT_INPUT,
5444                // Since this position is relative to the top of the text input
5445                // field, we do not need to take the title bar's height into
5446                // consideration.
5447                viewToContentDimension(y),
5448                new Float(xPercent));
5449    }
5450
5451    /**
5452     * Set our starting point and time for a drag from the WebTextView.
5453     */
5454    /*package*/ void initiateTextFieldDrag(float x, float y, long eventTime) {
5455        if (!inEditingMode()) {
5456            return;
5457        }
5458        mLastTouchX = x + (float) (mWebTextView.getLeft() - mScrollX);
5459        mLastTouchY = y + (float) (mWebTextView.getTop() - mScrollY);
5460        mLastTouchTime = eventTime;
5461        if (!mScroller.isFinished()) {
5462            abortAnimation();
5463            mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY);
5464        }
5465        mSnapScrollMode = SNAP_NONE;
5466        mVelocityTracker = VelocityTracker.obtain();
5467        mTouchMode = TOUCH_DRAG_START_MODE;
5468    }
5469
5470    /**
5471     * Given a motion event from the WebTextView, set its location to our
5472     * coordinates, and handle the event.
5473     */
5474    /*package*/ boolean textFieldDrag(MotionEvent event) {
5475        if (!inEditingMode()) {
5476            return false;
5477        }
5478        mDragFromTextInput = true;
5479        event.offsetLocation((float) (mWebTextView.getLeft() - mScrollX),
5480                (float) (mWebTextView.getTop() - mScrollY));
5481        boolean result = onTouchEvent(event);
5482        mDragFromTextInput = false;
5483        return result;
5484    }
5485
5486    /**
5487     * Due a touch up from a WebTextView.  This will be handled by webkit to
5488     * change the selection.
5489     * @param event MotionEvent in the WebTextView's coordinates.
5490     */
5491    /*package*/ void touchUpOnTextField(MotionEvent event) {
5492        if (!inEditingMode()) {
5493            return;
5494        }
5495        int x = viewToContentX((int) event.getX() + mWebTextView.getLeft());
5496        int y = viewToContentY((int) event.getY() + mWebTextView.getTop());
5497        nativeMotionUp(x, y, mNavSlop);
5498    }
5499
5500    /**
5501     * Called when pressing the center key or trackball on a textfield.
5502     */
5503    /*package*/ void centerKeyPressOnTextField() {
5504        mWebViewCore.sendMessage(EventHub.CLICK, nativeCursorFramePointer(),
5505                    nativeCursorNodePointer());
5506    }
5507
5508    private void doShortPress() {
5509        if (mNativeClass == 0) {
5510            return;
5511        }
5512        switchOutDrawHistory();
5513        // mLastTouchX and mLastTouchY are the point in the current viewport
5514        int contentX = viewToContentX((int) mLastTouchX + mScrollX);
5515        int contentY = viewToContentY((int) mLastTouchY + mScrollY);
5516        if (nativePointInNavCache(contentX, contentY, mNavSlop)) {
5517            WebViewCore.MotionUpData motionUpData = new WebViewCore
5518                    .MotionUpData();
5519            motionUpData.mFrame = nativeCacheHitFramePointer();
5520            motionUpData.mNode = nativeCacheHitNodePointer();
5521            motionUpData.mBounds = nativeCacheHitNodeBounds();
5522            motionUpData.mX = contentX;
5523            motionUpData.mY = contentY;
5524            mWebViewCore.sendMessageAtFrontOfQueue(EventHub.VALID_NODE_BOUNDS,
5525                    motionUpData);
5526        } else {
5527            doMotionUp(contentX, contentY);
5528        }
5529    }
5530
5531    private void doMotionUp(int contentX, int contentY) {
5532        if (mLogEvent && nativeMotionUp(contentX, contentY, mNavSlop)) {
5533            EventLog.writeEvent(EventLogTags.BROWSER_SNAP_CENTER);
5534        }
5535        if (nativeHasCursorNode() && !nativeCursorIsTextInput()) {
5536            playSoundEffect(SoundEffectConstants.CLICK);
5537        }
5538    }
5539
5540    // Rule for double tap:
5541    // 1. if the current scale is not same as the text wrap scale and layout
5542    //    algorithm is NARROW_COLUMNS, fit to column;
5543    // 2. if the current state is not overview mode, change to overview mode;
5544    // 3. if the current state is overview mode, change to default scale.
5545    private void doDoubleTap() {
5546        if (mWebViewCore.getSettings().getUseWideViewPort() == false) {
5547            return;
5548        }
5549        mZoomCenterX = mLastTouchX;
5550        mZoomCenterY = mLastTouchY;
5551        mAnchorX = viewToContentX((int) mZoomCenterX + mScrollX);
5552        mAnchorY = viewToContentY((int) mZoomCenterY + mScrollY);
5553        WebSettings settings = getSettings();
5554        // remove the zoom control after double tap
5555        if (settings.getBuiltInZoomControls()) {
5556            if (mZoomButtonsController.isVisible()) {
5557                mZoomButtonsController.setVisible(false);
5558            }
5559        } else {
5560            if (mZoomControlRunnable != null) {
5561                mPrivateHandler.removeCallbacks(mZoomControlRunnable);
5562            }
5563            if (mZoomControls != null) {
5564                mZoomControls.hide();
5565            }
5566        }
5567        settings.setDoubleTapToastCount(0);
5568        boolean zoomToDefault = false;
5569        if ((settings.getLayoutAlgorithm() == WebSettings.LayoutAlgorithm.NARROW_COLUMNS)
5570                && (Math.abs(mActualScale - mTextWrapScale) >= 0.01f)) {
5571            setNewZoomScale(mActualScale, true, true);
5572            float overviewScale = (float) getViewWidth() / mZoomOverviewWidth;
5573            if (Math.abs(mActualScale - overviewScale) < 0.01f) {
5574                mInZoomOverview = true;
5575            }
5576        } else if (!mInZoomOverview) {
5577            float newScale = (float) getViewWidth() / mZoomOverviewWidth;
5578            if (Math.abs(mActualScale - newScale) >= 0.01f) {
5579                mInZoomOverview = true;
5580                // Force the titlebar fully reveal in overview mode
5581                if (mScrollY < getTitleHeight()) mScrollY = 0;
5582                zoomWithPreview(newScale);
5583            } else if (Math.abs(mActualScale - mDefaultScale) >= 0.01f) {
5584                zoomToDefault = true;
5585            }
5586        } else {
5587            zoomToDefault = true;
5588        }
5589        if (zoomToDefault) {
5590            mInZoomOverview = false;
5591            int left = nativeGetBlockLeftEdge(mAnchorX, mAnchorY, mActualScale);
5592            if (left != NO_LEFTEDGE) {
5593                // add a 5pt padding to the left edge.
5594                int viewLeft = contentToViewX(left < 5 ? 0 : (left - 5))
5595                        - mScrollX;
5596                // Re-calculate the zoom center so that the new scroll x will be
5597                // on the left edge.
5598                if (viewLeft > 0) {
5599                    mZoomCenterX = viewLeft * mDefaultScale
5600                            / (mDefaultScale - mActualScale);
5601                } else {
5602                    scrollBy(viewLeft, 0);
5603                    mZoomCenterX = 0;
5604                }
5605            }
5606            zoomWithPreview(mDefaultScale);
5607        }
5608    }
5609
5610    // Called by JNI to handle a touch on a node representing an email address,
5611    // address, or phone number
5612    private void overrideLoading(String url) {
5613        mCallbackProxy.uiOverrideUrlLoading(url);
5614    }
5615
5616    @Override
5617    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
5618        boolean result = false;
5619        if (inEditingMode()) {
5620            result = mWebTextView.requestFocus(direction,
5621                    previouslyFocusedRect);
5622        } else {
5623            result = super.requestFocus(direction, previouslyFocusedRect);
5624            if (mWebViewCore.getSettings().getNeedInitialFocus()) {
5625                // For cases such as GMail, where we gain focus from a direction,
5626                // we want to move to the first available link.
5627                // FIXME: If there are no visible links, we may not want to
5628                int fakeKeyDirection = 0;
5629                switch(direction) {
5630                    case View.FOCUS_UP:
5631                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_UP;
5632                        break;
5633                    case View.FOCUS_DOWN:
5634                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_DOWN;
5635                        break;
5636                    case View.FOCUS_LEFT:
5637                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_LEFT;
5638                        break;
5639                    case View.FOCUS_RIGHT:
5640                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_RIGHT;
5641                        break;
5642                    default:
5643                        return result;
5644                }
5645                if (mNativeClass != 0 && !nativeHasCursorNode()) {
5646                    navHandledKey(fakeKeyDirection, 1, true, 0, true);
5647                }
5648            }
5649        }
5650        return result;
5651    }
5652
5653    @Override
5654    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
5655        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
5656
5657        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
5658        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
5659        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
5660        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
5661
5662        int measuredHeight = heightSize;
5663        int measuredWidth = widthSize;
5664
5665        // Grab the content size from WebViewCore.
5666        int contentHeight = contentToViewDimension(mContentHeight);
5667        int contentWidth = contentToViewDimension(mContentWidth);
5668
5669//        Log.d(LOGTAG, "------- measure " + heightMode);
5670
5671        if (heightMode != MeasureSpec.EXACTLY) {
5672            mHeightCanMeasure = true;
5673            measuredHeight = contentHeight;
5674            if (heightMode == MeasureSpec.AT_MOST) {
5675                // If we are larger than the AT_MOST height, then our height can
5676                // no longer be measured and we should scroll internally.
5677                if (measuredHeight > heightSize) {
5678                    measuredHeight = heightSize;
5679                    mHeightCanMeasure = false;
5680                }
5681            }
5682        } else {
5683            mHeightCanMeasure = false;
5684        }
5685        if (mNativeClass != 0) {
5686            nativeSetHeightCanMeasure(mHeightCanMeasure);
5687        }
5688        // For the width, always use the given size unless unspecified.
5689        if (widthMode == MeasureSpec.UNSPECIFIED) {
5690            mWidthCanMeasure = true;
5691            measuredWidth = contentWidth;
5692        } else {
5693            mWidthCanMeasure = false;
5694        }
5695
5696        synchronized (this) {
5697            setMeasuredDimension(measuredWidth, measuredHeight);
5698        }
5699    }
5700
5701    @Override
5702    public boolean requestChildRectangleOnScreen(View child,
5703                                                 Rect rect,
5704                                                 boolean immediate) {
5705        rect.offset(child.getLeft() - child.getScrollX(),
5706                child.getTop() - child.getScrollY());
5707
5708        int height = getViewHeightWithTitle();
5709        int screenTop = mScrollY;
5710        int screenBottom = screenTop + height;
5711
5712        int scrollYDelta = 0;
5713
5714        if (rect.bottom > screenBottom) {
5715            int oneThirdOfScreenHeight = height / 3;
5716            if (rect.height() > 2 * oneThirdOfScreenHeight) {
5717                // If the rectangle is too tall to fit in the bottom two thirds
5718                // of the screen, place it at the top.
5719                scrollYDelta = rect.top - screenTop;
5720            } else {
5721                // If the rectangle will still fit on screen, we want its
5722                // top to be in the top third of the screen.
5723                scrollYDelta = rect.top - (screenTop + oneThirdOfScreenHeight);
5724            }
5725        } else if (rect.top < screenTop) {
5726            scrollYDelta = rect.top - screenTop;
5727        }
5728
5729        int width = getWidth() - getVerticalScrollbarWidth();
5730        int screenLeft = mScrollX;
5731        int screenRight = screenLeft + width;
5732
5733        int scrollXDelta = 0;
5734
5735        if (rect.right > screenRight && rect.left > screenLeft) {
5736            if (rect.width() > width) {
5737                scrollXDelta += (rect.left - screenLeft);
5738            } else {
5739                scrollXDelta += (rect.right - screenRight);
5740            }
5741        } else if (rect.left < screenLeft) {
5742            scrollXDelta -= (screenLeft - rect.left);
5743        }
5744
5745        if ((scrollYDelta | scrollXDelta) != 0) {
5746            return pinScrollBy(scrollXDelta, scrollYDelta, !immediate, 0);
5747        }
5748
5749        return false;
5750    }
5751
5752    /* package */ void replaceTextfieldText(int oldStart, int oldEnd,
5753            String replace, int newStart, int newEnd) {
5754        WebViewCore.ReplaceTextData arg = new WebViewCore.ReplaceTextData();
5755        arg.mReplace = replace;
5756        arg.mNewStart = newStart;
5757        arg.mNewEnd = newEnd;
5758        mTextGeneration++;
5759        arg.mTextGeneration = mTextGeneration;
5760        mWebViewCore.sendMessage(EventHub.REPLACE_TEXT, oldStart, oldEnd, arg);
5761    }
5762
5763    /* package */ void passToJavaScript(String currentText, KeyEvent event) {
5764        WebViewCore.JSKeyData arg = new WebViewCore.JSKeyData();
5765        arg.mEvent = event;
5766        arg.mCurrentText = currentText;
5767        // Increase our text generation number, and pass it to webcore thread
5768        mTextGeneration++;
5769        mWebViewCore.sendMessage(EventHub.PASS_TO_JS, mTextGeneration, 0, arg);
5770        // WebKit's document state is not saved until about to leave the page.
5771        // To make sure the host application, like Browser, has the up to date
5772        // document state when it goes to background, we force to save the
5773        // document state.
5774        mWebViewCore.removeMessages(EventHub.SAVE_DOCUMENT_STATE);
5775        mWebViewCore.sendMessageDelayed(EventHub.SAVE_DOCUMENT_STATE,
5776                cursorData(), 1000);
5777    }
5778
5779    /* package */ WebViewCore getWebViewCore() {
5780        return mWebViewCore;
5781    }
5782
5783    //-------------------------------------------------------------------------
5784    // Methods can be called from a separate thread, like WebViewCore
5785    // If it needs to call the View system, it has to send message.
5786    //-------------------------------------------------------------------------
5787
5788    /**
5789     * General handler to receive message coming from webkit thread
5790     */
5791    class PrivateHandler extends Handler {
5792        @Override
5793        public void handleMessage(Message msg) {
5794            // exclude INVAL_RECT_MSG_ID since it is frequently output
5795            if (DebugFlags.WEB_VIEW && msg.what != INVAL_RECT_MSG_ID) {
5796                Log.v(LOGTAG, msg.what < REMEMBER_PASSWORD || msg.what
5797                        > FIND_AGAIN ? Integer.toString(msg.what)
5798                        : HandlerDebugString[msg.what - REMEMBER_PASSWORD]);
5799            }
5800            if (mWebViewCore == null) {
5801                // after WebView's destroy() is called, skip handling messages.
5802                return;
5803            }
5804            switch (msg.what) {
5805                case REMEMBER_PASSWORD: {
5806                    mDatabase.setUsernamePassword(
5807                            msg.getData().getString("host"),
5808                            msg.getData().getString("username"),
5809                            msg.getData().getString("password"));
5810                    ((Message) msg.obj).sendToTarget();
5811                    break;
5812                }
5813                case NEVER_REMEMBER_PASSWORD: {
5814                    mDatabase.setUsernamePassword(
5815                            msg.getData().getString("host"), null, null);
5816                    ((Message) msg.obj).sendToTarget();
5817                    break;
5818                }
5819                case SWITCH_TO_SHORTPRESS: {
5820                    // if mPreventDrag is not confirmed, cancel it so that it
5821                    // won't block panning the page.
5822                    if (mPreventDrag == PREVENT_DRAG_MAYBE_YES) {
5823                        mPreventDrag = PREVENT_DRAG_CANCEL;
5824                        mPreventLongPress = false;
5825                        mPreventDoubleTap = false;
5826                        // remove the pending TOUCH_EVENT and send a cancel
5827                        mWebViewCore.removeMessages(EventHub.TOUCH_EVENT);
5828                        WebViewCore.TouchEventData ted = new WebViewCore.TouchEventData();
5829                        ted.mAction = MotionEvent.ACTION_CANCEL;
5830                        mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
5831                    }
5832                    if (mTouchMode == TOUCH_INIT_MODE) {
5833                        mTouchMode = mFullScreenHolder == null
5834                                ? TOUCH_SHORTPRESS_START_MODE
5835                                        : TOUCH_SHORTPRESS_MODE;
5836                        updateSelection();
5837                    } else if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
5838                        mTouchMode = TOUCH_DONE_MODE;
5839                    }
5840                    break;
5841                }
5842                case SWITCH_TO_LONGPRESS: {
5843                    if (mPreventLongPress) {
5844                        mTouchMode = TOUCH_DONE_MODE;
5845                        WebViewCore.TouchEventData ted
5846                                = new WebViewCore.TouchEventData();
5847                        ted.mAction = WebViewCore.ACTION_LONGPRESS;
5848                        ted.mX = viewToContentX((int) mLastTouchX + mScrollX);
5849                        ted.mY = viewToContentY((int) mLastTouchY + mScrollY);
5850                        ted.mEventTime = SystemClock.uptimeMillis();
5851                        // metaState for long press is tricky. Should it be the state
5852                        // when the press started or when the press was released? Or
5853                        // some intermediary key state? For simplicity for now, we
5854                        // don't set it.
5855                        ted.mMetaState = 0;
5856                        mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
5857                    } else if (mPreventDrag != PREVENT_DRAG_YES) {
5858                        mTouchMode = TOUCH_DONE_MODE;
5859                        if (mFullScreenHolder == null) {
5860                            performLongClick();
5861                            rebuildWebTextView();
5862                        }
5863                    }
5864                    break;
5865                }
5866                case RELEASE_SINGLE_TAP: {
5867                    if (mPreventDrag == PREVENT_DRAG_MAYBE_YES) {
5868                        // if mPreventDrag is not confirmed, cancel it so that
5869                        // it won't block panning the page.
5870                        mPreventDrag = PREVENT_DRAG_CANCEL;
5871                        mPreventLongPress = false;
5872                        mPreventDoubleTap = false;
5873                        // remove the pending TOUCH_EVENT and send a cancel
5874                        mWebViewCore.removeMessages(EventHub.TOUCH_EVENT);
5875                        WebViewCore.TouchEventData ted = new WebViewCore.TouchEventData();
5876                        ted.mAction = MotionEvent.ACTION_CANCEL;
5877                        mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
5878                    }
5879                    if (mPreventDrag != PREVENT_DRAG_YES) {
5880                        mTouchMode = TOUCH_DONE_MODE;
5881                        doShortPress();
5882                    }
5883                    break;
5884                }
5885                case SCROLL_BY_MSG_ID:
5886                    setContentScrollBy(msg.arg1, msg.arg2, (Boolean) msg.obj);
5887                    break;
5888                case SYNC_SCROLL_TO_MSG_ID:
5889                    if (mUserScroll) {
5890                        // if user has scrolled explicitly, don't sync the
5891                        // scroll position any more
5892                        mUserScroll = false;
5893                        break;
5894                    }
5895                    // fall through
5896                case SCROLL_TO_MSG_ID:
5897                    if (setContentScrollTo(msg.arg1, msg.arg2)) {
5898                        // if we can't scroll to the exact position due to pin,
5899                        // send a message to WebCore to re-scroll when we get a
5900                        // new picture
5901                        mUserScroll = false;
5902                        mWebViewCore.sendMessage(EventHub.SYNC_SCROLL,
5903                                msg.arg1, msg.arg2);
5904                    }
5905                    break;
5906                case SPAWN_SCROLL_TO_MSG_ID:
5907                    spawnContentScrollTo(msg.arg1, msg.arg2);
5908                    break;
5909                case UPDATE_ZOOM_RANGE: {
5910                    WebViewCore.RestoreState restoreState
5911                            = (WebViewCore.RestoreState) msg.obj;
5912                    // mScrollX contains the new minPrefWidth
5913                    updateZoomRange(restoreState, getViewWidth(),
5914                            restoreState.mScrollX, false);
5915                    break;
5916                }
5917                case NEW_PICTURE_MSG_ID: {
5918                    WebSettings settings = mWebViewCore.getSettings();
5919                    // called for new content
5920                    final int viewWidth = getViewWidth();
5921                    final WebViewCore.DrawData draw =
5922                            (WebViewCore.DrawData) msg.obj;
5923                    final Point viewSize = draw.mViewPoint;
5924                    boolean useWideViewport = settings.getUseWideViewPort();
5925                    WebViewCore.RestoreState restoreState = draw.mRestoreState;
5926                    boolean hasRestoreState = restoreState != null;
5927                    if (hasRestoreState) {
5928                        mInZoomOverview = false;
5929                        updateZoomRange(restoreState, viewSize.x,
5930                                draw.mMinPrefWidth, true);
5931                        if (mInitialScaleInPercent > 0) {
5932                            setNewZoomScale(mInitialScaleInPercent / 100.0f,
5933                                    mInitialScaleInPercent != mTextWrapScale * 100,
5934                                    false);
5935                        } else if (restoreState.mViewScale > 0) {
5936                            mTextWrapScale = restoreState.mTextWrapScale;
5937                            setNewZoomScale(restoreState.mViewScale, false,
5938                                    false);
5939                        } else {
5940                            mInZoomOverview = useWideViewport
5941                                    && settings.getLoadWithOverviewMode();
5942                            float scale;
5943                            if (mInZoomOverview) {
5944                                scale = (float) viewWidth
5945                                        / DEFAULT_VIEWPORT_WIDTH;
5946                            } else {
5947                                scale = restoreState.mTextWrapScale;
5948                            }
5949                            setNewZoomScale(scale, Math.abs(scale
5950                                    - mTextWrapScale) >= 0.01f, false);
5951                        }
5952                        setContentScrollTo(restoreState.mScrollX,
5953                                restoreState.mScrollY);
5954                        // As we are on a new page, remove the WebTextView. This
5955                        // is necessary for page loads driven by webkit, and in
5956                        // particular when the user was on a password field, so
5957                        // the WebTextView was visible.
5958                        clearTextEntry(false);
5959                        // update the zoom buttons as the scale can be changed
5960                        if (getSettings().getBuiltInZoomControls()) {
5961                            updateZoomButtonsEnabled();
5962                        }
5963                    }
5964                    // We update the layout (i.e. request a layout from the
5965                    // view system) if the last view size that we sent to
5966                    // WebCore matches the view size of the picture we just
5967                    // received in the fixed dimension.
5968                    final boolean updateLayout = viewSize.x == mLastWidthSent
5969                            && viewSize.y == mLastHeightSent;
5970                    recordNewContentSize(draw.mWidthHeight.x,
5971                            draw.mWidthHeight.y
5972                            + (mFindIsUp ? mFindHeight : 0), updateLayout);
5973                    if (DebugFlags.WEB_VIEW) {
5974                        Rect b = draw.mInvalRegion.getBounds();
5975                        Log.v(LOGTAG, "NEW_PICTURE_MSG_ID {" +
5976                                b.left+","+b.top+","+b.right+","+b.bottom+"}");
5977                    }
5978                    invalidateContentRect(draw.mInvalRegion.getBounds());
5979                    if (mPictureListener != null) {
5980                        mPictureListener.onNewPicture(WebView.this, capturePicture());
5981                    }
5982                    if (useWideViewport) {
5983                        // limit mZoomOverviewWidth upper bound to
5984                        // sMaxViewportWidth so that if the page doesn't behave
5985                        // well, the WebView won't go insane. limit the lower
5986                        // bound to match the default scale for mobile sites.
5987                        mZoomOverviewWidth = Math.min(sMaxViewportWidth, Math
5988                                .max((int) (viewWidth / mDefaultScale), Math
5989                                        .max(draw.mMinPrefWidth,
5990                                                draw.mViewPoint.x)));
5991                    }
5992                    if (!mMinZoomScaleFixed) {
5993                        mMinZoomScale = (float) viewWidth / mZoomOverviewWidth;
5994                    }
5995                    if (!mDrawHistory && mInZoomOverview) {
5996                        // fit the content width to the current view. Ignore
5997                        // the rounding error case.
5998                        if (Math.abs((viewWidth * mInvActualScale)
5999                                - mZoomOverviewWidth) > 1) {
6000                            setNewZoomScale((float) viewWidth
6001                                    / mZoomOverviewWidth, Math.abs(mActualScale
6002                                            - mTextWrapScale) < 0.01f, false);
6003                        }
6004                    }
6005                    if (draw.mFocusSizeChanged && inEditingMode()) {
6006                        mFocusSizeChanged = true;
6007                    }
6008                    if (hasRestoreState) {
6009                        mViewManager.postReadyToDrawAll();
6010                    }
6011                    break;
6012                }
6013                case WEBCORE_INITIALIZED_MSG_ID:
6014                    // nativeCreate sets mNativeClass to a non-zero value
6015                    nativeCreate(msg.arg1);
6016                    break;
6017                case UPDATE_TEXTFIELD_TEXT_MSG_ID:
6018                    // Make sure that the textfield is currently focused
6019                    // and representing the same node as the pointer.
6020                    if (inEditingMode() &&
6021                            mWebTextView.isSameTextField(msg.arg1)) {
6022                        if (msg.getData().getBoolean("password")) {
6023                            Spannable text = (Spannable) mWebTextView.getText();
6024                            int start = Selection.getSelectionStart(text);
6025                            int end = Selection.getSelectionEnd(text);
6026                            mWebTextView.setInPassword(true);
6027                            // Restore the selection, which may have been
6028                            // ruined by setInPassword.
6029                            Spannable pword =
6030                                    (Spannable) mWebTextView.getText();
6031                            Selection.setSelection(pword, start, end);
6032                        // If the text entry has created more events, ignore
6033                        // this one.
6034                        } else if (msg.arg2 == mTextGeneration) {
6035                            mWebTextView.setTextAndKeepSelection(
6036                                    (String) msg.obj);
6037                        }
6038                    }
6039                    break;
6040                case UPDATE_TEXT_SELECTION_MSG_ID:
6041                    // If no textfield was in focus, and the user touched one,
6042                    // causing it to send this message, then WebTextView has not
6043                    // been set up yet.  Rebuild it so it can set its selection.
6044                    rebuildWebTextView();
6045                    if (inEditingMode()
6046                            && mWebTextView.isSameTextField(msg.arg1)
6047                            && msg.arg2 == mTextGeneration) {
6048                        WebViewCore.TextSelectionData tData
6049                                = (WebViewCore.TextSelectionData) msg.obj;
6050                        mWebTextView.setSelectionFromWebKit(tData.mStart,
6051                                tData.mEnd);
6052                    }
6053                    break;
6054                case RETURN_LABEL:
6055                    if (inEditingMode()
6056                            && mWebTextView.isSameTextField(msg.arg1)) {
6057                        mWebTextView.setHint((String) msg.obj);
6058                        InputMethodManager imm
6059                                = InputMethodManager.peekInstance();
6060                        // The hint is propagated to the IME in
6061                        // onCreateInputConnection.  If the IME is already
6062                        // active, restart it so that its hint text is updated.
6063                        if (imm != null && imm.isActive(mWebTextView)) {
6064                            imm.restartInput(mWebTextView);
6065                        }
6066                    }
6067                    break;
6068                case MOVE_OUT_OF_PLUGIN:
6069                    navHandledKey(msg.arg1, 1, false, 0, true);
6070                    break;
6071                case UPDATE_TEXT_ENTRY_MSG_ID:
6072                    // this is sent after finishing resize in WebViewCore. Make
6073                    // sure the text edit box is still on the  screen.
6074                    if (inEditingMode() && nativeCursorIsTextInput()) {
6075                        mWebTextView.bringIntoView();
6076                        rebuildWebTextView();
6077                    }
6078                    break;
6079                case CLEAR_TEXT_ENTRY:
6080                    clearTextEntry(false);
6081                    break;
6082                case INVAL_RECT_MSG_ID: {
6083                    Rect r = (Rect)msg.obj;
6084                    if (r == null) {
6085                        invalidate();
6086                    } else {
6087                        // we need to scale r from content into view coords,
6088                        // which viewInvalidate() does for us
6089                        viewInvalidate(r.left, r.top, r.right, r.bottom);
6090                    }
6091                    break;
6092                }
6093                case IMMEDIATE_REPAINT_MSG_ID: {
6094                    invalidate();
6095                    break;
6096                }
6097                case SET_ROOT_LAYER_MSG_ID: {
6098                    nativeSetRootLayer(msg.arg1);
6099                    invalidate();
6100                    break;
6101                }
6102                case REQUEST_FORM_DATA:
6103                    AutoCompleteAdapter adapter = (AutoCompleteAdapter) msg.obj;
6104                    if (mWebTextView.isSameTextField(msg.arg1)) {
6105                        mWebTextView.setAdapterCustom(adapter);
6106                    }
6107                    break;
6108                case RESUME_WEBCORE_PRIORITY:
6109                    WebViewCore.resumePriority();
6110                    break;
6111
6112                case LONG_PRESS_CENTER:
6113                    // as this is shared by keydown and trackballdown, reset all
6114                    // the states
6115                    mGotCenterDown = false;
6116                    mTrackballDown = false;
6117                    performLongClick();
6118                    break;
6119
6120                case WEBCORE_NEED_TOUCH_EVENTS:
6121                    mForwardTouchEvents = (msg.arg1 != 0);
6122                    break;
6123
6124                case PREVENT_TOUCH_ID:
6125                    if (msg.arg1 == MotionEvent.ACTION_DOWN) {
6126                        // dont override if mPreventDrag has been set to no due
6127                        // to time out
6128                        if (mPreventDrag == PREVENT_DRAG_MAYBE_YES) {
6129                            mPreventDrag = (msg.arg2 & TOUCH_PREVENT_DRAG)
6130                                    == TOUCH_PREVENT_DRAG ? PREVENT_DRAG_YES
6131                                    : PREVENT_DRAG_NO;
6132                            if (mPreventDrag == PREVENT_DRAG_YES) {
6133                                mTouchMode = TOUCH_DONE_MODE;
6134                            } else {
6135                                mPreventLongPress =
6136                                        (msg.arg2 & TOUCH_PREVENT_LONGPRESS)
6137                                        == TOUCH_PREVENT_LONGPRESS;
6138                                mPreventDoubleTap =
6139                                        (msg.arg2 & TOUCH_PREVENT_DOUBLETAP)
6140                                        == TOUCH_PREVENT_DOUBLETAP;
6141                            }
6142                        }
6143                    }
6144                    break;
6145
6146                case REQUEST_KEYBOARD:
6147                    if (msg.arg1 == 0) {
6148                        hideSoftKeyboard();
6149                    } else {
6150                        displaySoftKeyboard(1 == msg.arg2);
6151                    }
6152                    break;
6153
6154                case FIND_AGAIN:
6155                    // Ignore if find has been dismissed.
6156                    if (mFindIsUp) {
6157                        findAll(mLastFind);
6158                    }
6159                    break;
6160
6161                case DRAG_HELD_MOTIONLESS:
6162                    mHeldMotionless = MOTIONLESS_TRUE;
6163                    invalidate();
6164                    // fall through to keep scrollbars awake
6165
6166                case AWAKEN_SCROLL_BARS:
6167                    if (mTouchMode == TOUCH_DRAG_MODE
6168                            && mHeldMotionless == MOTIONLESS_TRUE) {
6169                        awakenScrollBars(ViewConfiguration
6170                                .getScrollDefaultDelay(), false);
6171                        mPrivateHandler.sendMessageDelayed(mPrivateHandler
6172                                .obtainMessage(AWAKEN_SCROLL_BARS),
6173                                ViewConfiguration.getScrollDefaultDelay());
6174                    }
6175                    break;
6176
6177                case DO_MOTION_UP:
6178                    doMotionUp(msg.arg1, msg.arg2);
6179                    break;
6180
6181                case SHOW_FULLSCREEN: {
6182                    WebViewCore.PluginFullScreenData data
6183                            = (WebViewCore.PluginFullScreenData) msg.obj;
6184                    if (data.mNpp != 0 && data.mView != null) {
6185                        if (mFullScreenHolder != null) {
6186                            Log.w(LOGTAG,
6187                                    "Should not have another full screen.");
6188                            mFullScreenHolder.dismiss();
6189                        }
6190                        mFullScreenHolder = new PluginFullScreenHolder(
6191                                WebView.this, data.mNpp);
6192                        // as we are sharing the View between full screen and
6193                        // embedded mode, we have to remove the
6194                        // AbsoluteLayout.LayoutParams set by embedded mode to
6195                        // ViewGroup.LayoutParams before adding it to the dialog
6196                        data.mView.setLayoutParams(new ViewGroup.LayoutParams(
6197                                ViewGroup.LayoutParams.FILL_PARENT,
6198                                ViewGroup.LayoutParams.FILL_PARENT));
6199                        mFullScreenHolder.setContentView(data.mView);
6200                        mFullScreenHolder.setCancelable(false);
6201                        mFullScreenHolder.setCanceledOnTouchOutside(false);
6202                        mFullScreenHolder.show();
6203                    } else if (mFullScreenHolder == null) {
6204                        // this may happen if user dismisses the fullscreen and
6205                        // then the WebCore re-position message finally reached
6206                        // the UI thread.
6207                        break;
6208                    }
6209                    // move the matching embedded view fully into the view so
6210                    // that touch will be valid instead of rejected due to out
6211                    // of the visible bounds
6212                    // TODO: do we need to preserve the original position and
6213                    // scale so that we can revert it when leaving the full
6214                    // screen mode?
6215                    int x = contentToViewX(data.mDocX);
6216                    int y = contentToViewY(data.mDocY);
6217                    int width = contentToViewDimension(data.mDocWidth);
6218                    int height = contentToViewDimension(data.mDocHeight);
6219                    int viewWidth = getViewWidth();
6220                    int viewHeight = getViewHeight();
6221                    int newX = mScrollX;
6222                    int newY = mScrollY;
6223                    if (x < mScrollX) {
6224                        newX = x + (width > viewWidth
6225                                ? (width - viewWidth) / 2 : 0);
6226                    } else if (x + width > mScrollX + viewWidth) {
6227                        newX = x + width - viewWidth - (width > viewWidth
6228                                ? (width - viewWidth) / 2 : 0);
6229                    }
6230                    if (y < mScrollY) {
6231                        newY = y + (height > viewHeight
6232                                ? (height - viewHeight) / 2 : 0);
6233                    } else if (y + height > mScrollY + viewHeight) {
6234                        newY = y + height - viewHeight - (height > viewHeight
6235                                ? (height - viewHeight) / 2 : 0);
6236                    }
6237                    scrollTo(newX, newY);
6238                    if (width > viewWidth || height > viewHeight) {
6239                        mZoomCenterX = viewWidth * .5f;
6240                        mZoomCenterY = viewHeight * .5f;
6241                        // do not change text wrap scale so that there is no
6242                        // reflow
6243                        setNewZoomScale(mActualScale
6244                                / Math.max((float) width / viewWidth,
6245                                        (float) height / viewHeight), false,
6246                                false);
6247                    }
6248                    // Now update the bound
6249                    mFullScreenHolder.updateBound(contentToViewX(data.mDocX)
6250                            - mScrollX, contentToViewY(data.mDocY) - mScrollY,
6251                            contentToViewDimension(data.mDocWidth),
6252                            contentToViewDimension(data.mDocHeight));
6253                    }
6254                    break;
6255
6256                case HIDE_FULLSCREEN:
6257                    if (mFullScreenHolder != null) {
6258                        mFullScreenHolder.dismiss();
6259                        mFullScreenHolder = null;
6260                    }
6261                    break;
6262
6263                case DOM_FOCUS_CHANGED:
6264                    if (inEditingMode()) {
6265                        nativeClearCursor();
6266                        rebuildWebTextView();
6267                    }
6268                    break;
6269
6270                case SHOW_RECT_MSG_ID: {
6271                    WebViewCore.ShowRectData data = (WebViewCore.ShowRectData) msg.obj;
6272                    int x = mScrollX;
6273                    int left = contentToViewX(data.mLeft);
6274                    int width = contentToViewDimension(data.mWidth);
6275                    int maxWidth = contentToViewDimension(data.mContentWidth);
6276                    int viewWidth = getViewWidth();
6277                    if (width < viewWidth) {
6278                        // center align
6279                        x += left + width / 2 - mScrollX - viewWidth / 2;
6280                    } else {
6281                        x += (int) (left + data.mXPercentInDoc * width
6282                                - mScrollX - data.mXPercentInView * viewWidth);
6283                    }
6284                    if (DebugFlags.WEB_VIEW) {
6285                        Log.v(LOGTAG, "showRectMsg=(left=" + left + ",width=" +
6286                              width + ",maxWidth=" + maxWidth +
6287                              ",viewWidth=" + viewWidth + ",x="
6288                              + x + ",xPercentInDoc=" + data.mXPercentInDoc +
6289                              ",xPercentInView=" + data.mXPercentInView+ ")");
6290                    }
6291                    // use the passing content width to cap x as the current
6292                    // mContentWidth may not be updated yet
6293                    x = Math.max(0,
6294                            (Math.min(maxWidth, x + viewWidth)) - viewWidth);
6295                    int top = contentToViewY(data.mTop);
6296                    int height = contentToViewDimension(data.mHeight);
6297                    int maxHeight = contentToViewDimension(data.mContentHeight);
6298                    int viewHeight = getViewHeight();
6299                    int y = (int) (top + data.mYPercentInDoc * height -
6300                                   data.mYPercentInView * viewHeight);
6301                    if (DebugFlags.WEB_VIEW) {
6302                        Log.v(LOGTAG, "showRectMsg=(top=" + top + ",height=" +
6303                              height + ",maxHeight=" + maxHeight +
6304                              ",viewHeight=" + viewHeight + ",y="
6305                              + y + ",yPercentInDoc=" + data.mYPercentInDoc +
6306                              ",yPercentInView=" + data.mYPercentInView+ ")");
6307                    }
6308                    // use the passing content height to cap y as the current
6309                    // mContentHeight may not be updated yet
6310                    y = Math.max(0,
6311                            (Math.min(maxHeight, y + viewHeight) - viewHeight));
6312                    // We need to take into account the visible title height
6313                    // when scrolling since y is an absolute view position.
6314                    y = Math.max(0, y - getVisibleTitleHeight());
6315                    scrollTo(x, y);
6316                    }
6317                    break;
6318
6319                default:
6320                    super.handleMessage(msg);
6321                    break;
6322            }
6323        }
6324    }
6325
6326    // Class used to use a dropdown for a <select> element
6327    private class InvokeListBox implements Runnable {
6328        // Whether the listbox allows multiple selection.
6329        private boolean     mMultiple;
6330        // Passed in to a list with multiple selection to tell
6331        // which items are selected.
6332        private int[]       mSelectedArray;
6333        // Passed in to a list with single selection to tell
6334        // where the initial selection is.
6335        private int         mSelection;
6336
6337        private Container[] mContainers;
6338
6339        // Need these to provide stable ids to my ArrayAdapter,
6340        // which normally does not have stable ids. (Bug 1250098)
6341        private class Container extends Object {
6342            /**
6343             * Possible values for mEnabled.  Keep in sync with OptionStatus in
6344             * WebViewCore.cpp
6345             */
6346            final static int OPTGROUP = -1;
6347            final static int OPTION_DISABLED = 0;
6348            final static int OPTION_ENABLED = 1;
6349
6350            String  mString;
6351            int     mEnabled;
6352            int     mId;
6353
6354            public String toString() {
6355                return mString;
6356            }
6357        }
6358
6359        /**
6360         *  Subclass ArrayAdapter so we can disable OptionGroupLabels,
6361         *  and allow filtering.
6362         */
6363        private class MyArrayListAdapter extends ArrayAdapter<Container> {
6364            public MyArrayListAdapter(Context context, Container[] objects, boolean multiple) {
6365                super(context,
6366                            multiple ? com.android.internal.R.layout.select_dialog_multichoice :
6367                            com.android.internal.R.layout.select_dialog_singlechoice,
6368                            objects);
6369            }
6370
6371            @Override
6372            public View getView(int position, View convertView,
6373                    ViewGroup parent) {
6374                // Always pass in null so that we will get a new CheckedTextView
6375                // Otherwise, an item which was previously used as an <optgroup>
6376                // element (i.e. has no check), could get used as an <option>
6377                // element, which needs a checkbox/radio, but it would not have
6378                // one.
6379                convertView = super.getView(position, null, parent);
6380                Container c = item(position);
6381                if (c != null && Container.OPTION_ENABLED != c.mEnabled) {
6382                    // ListView does not draw dividers between disabled and
6383                    // enabled elements.  Use a LinearLayout to provide dividers
6384                    LinearLayout layout = new LinearLayout(mContext);
6385                    layout.setOrientation(LinearLayout.VERTICAL);
6386                    if (position > 0) {
6387                        View dividerTop = new View(mContext);
6388                        dividerTop.setBackgroundResource(
6389                                android.R.drawable.divider_horizontal_bright);
6390                        layout.addView(dividerTop);
6391                    }
6392
6393                    if (Container.OPTGROUP == c.mEnabled) {
6394                        // Currently select_dialog_multichoice and
6395                        // select_dialog_singlechoice are CheckedTextViews.  If
6396                        // that changes, the class cast will no longer be valid.
6397                        Assert.assertTrue(
6398                                convertView instanceof CheckedTextView);
6399                        ((CheckedTextView) convertView).setCheckMarkDrawable(
6400                                null);
6401                    } else {
6402                        // c.mEnabled == Container.OPTION_DISABLED
6403                        // Draw the disabled element in a disabled state.
6404                        convertView.setEnabled(false);
6405                    }
6406
6407                    layout.addView(convertView);
6408                    if (position < getCount() - 1) {
6409                        View dividerBottom = new View(mContext);
6410                        dividerBottom.setBackgroundResource(
6411                                android.R.drawable.divider_horizontal_bright);
6412                        layout.addView(dividerBottom);
6413                    }
6414                    return layout;
6415                }
6416                return convertView;
6417            }
6418
6419            @Override
6420            public boolean hasStableIds() {
6421                // AdapterView's onChanged method uses this to determine whether
6422                // to restore the old state.  Return false so that the old (out
6423                // of date) state does not replace the new, valid state.
6424                return false;
6425            }
6426
6427            private Container item(int position) {
6428                if (position < 0 || position >= getCount()) {
6429                    return null;
6430                }
6431                return (Container) getItem(position);
6432            }
6433
6434            @Override
6435            public long getItemId(int position) {
6436                Container item = item(position);
6437                if (item == null) {
6438                    return -1;
6439                }
6440                return item.mId;
6441            }
6442
6443            @Override
6444            public boolean areAllItemsEnabled() {
6445                return false;
6446            }
6447
6448            @Override
6449            public boolean isEnabled(int position) {
6450                Container item = item(position);
6451                if (item == null) {
6452                    return false;
6453                }
6454                return Container.OPTION_ENABLED == item.mEnabled;
6455            }
6456        }
6457
6458        private InvokeListBox(String[] array, int[] enabled, int[] selected) {
6459            mMultiple = true;
6460            mSelectedArray = selected;
6461
6462            int length = array.length;
6463            mContainers = new Container[length];
6464            for (int i = 0; i < length; i++) {
6465                mContainers[i] = new Container();
6466                mContainers[i].mString = array[i];
6467                mContainers[i].mEnabled = enabled[i];
6468                mContainers[i].mId = i;
6469            }
6470        }
6471
6472        private InvokeListBox(String[] array, int[] enabled, int selection) {
6473            mSelection = selection;
6474            mMultiple = false;
6475
6476            int length = array.length;
6477            mContainers = new Container[length];
6478            for (int i = 0; i < length; i++) {
6479                mContainers[i] = new Container();
6480                mContainers[i].mString = array[i];
6481                mContainers[i].mEnabled = enabled[i];
6482                mContainers[i].mId = i;
6483            }
6484        }
6485
6486        /*
6487         * Whenever the data set changes due to filtering, this class ensures
6488         * that the checked item remains checked.
6489         */
6490        private class SingleDataSetObserver extends DataSetObserver {
6491            private long        mCheckedId;
6492            private ListView    mListView;
6493            private Adapter     mAdapter;
6494
6495            /*
6496             * Create a new observer.
6497             * @param id The ID of the item to keep checked.
6498             * @param l ListView for getting and clearing the checked states
6499             * @param a Adapter for getting the IDs
6500             */
6501            public SingleDataSetObserver(long id, ListView l, Adapter a) {
6502                mCheckedId = id;
6503                mListView = l;
6504                mAdapter = a;
6505            }
6506
6507            public void onChanged() {
6508                // The filter may have changed which item is checked.  Find the
6509                // item that the ListView thinks is checked.
6510                int position = mListView.getCheckedItemPosition();
6511                long id = mAdapter.getItemId(position);
6512                if (mCheckedId != id) {
6513                    // Clear the ListView's idea of the checked item, since
6514                    // it is incorrect
6515                    mListView.clearChoices();
6516                    // Search for mCheckedId.  If it is in the filtered list,
6517                    // mark it as checked
6518                    int count = mAdapter.getCount();
6519                    for (int i = 0; i < count; i++) {
6520                        if (mAdapter.getItemId(i) == mCheckedId) {
6521                            mListView.setItemChecked(i, true);
6522                            break;
6523                        }
6524                    }
6525                }
6526            }
6527
6528            public void onInvalidate() {}
6529        }
6530
6531        public void run() {
6532            final ListView listView = (ListView) LayoutInflater.from(mContext)
6533                    .inflate(com.android.internal.R.layout.select_dialog, null);
6534            final MyArrayListAdapter adapter = new
6535                    MyArrayListAdapter(mContext, mContainers, mMultiple);
6536            AlertDialog.Builder b = new AlertDialog.Builder(mContext)
6537                    .setView(listView).setCancelable(true)
6538                    .setInverseBackgroundForced(true);
6539
6540            if (mMultiple) {
6541                b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
6542                    public void onClick(DialogInterface dialog, int which) {
6543                        mWebViewCore.sendMessage(
6544                                EventHub.LISTBOX_CHOICES,
6545                                adapter.getCount(), 0,
6546                                listView.getCheckedItemPositions());
6547                    }});
6548                b.setNegativeButton(android.R.string.cancel,
6549                        new DialogInterface.OnClickListener() {
6550                    public void onClick(DialogInterface dialog, int which) {
6551                        mWebViewCore.sendMessage(
6552                                EventHub.SINGLE_LISTBOX_CHOICE, -2, 0);
6553                }});
6554            }
6555            final AlertDialog dialog = b.create();
6556            listView.setAdapter(adapter);
6557            listView.setFocusableInTouchMode(true);
6558            // There is a bug (1250103) where the checks in a ListView with
6559            // multiple items selected are associated with the positions, not
6560            // the ids, so the items do not properly retain their checks when
6561            // filtered.  Do not allow filtering on multiple lists until
6562            // that bug is fixed.
6563
6564            listView.setTextFilterEnabled(!mMultiple);
6565            if (mMultiple) {
6566                listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
6567                int length = mSelectedArray.length;
6568                for (int i = 0; i < length; i++) {
6569                    listView.setItemChecked(mSelectedArray[i], true);
6570                }
6571            } else {
6572                listView.setOnItemClickListener(new OnItemClickListener() {
6573                    public void onItemClick(AdapterView parent, View v,
6574                            int position, long id) {
6575                        mWebViewCore.sendMessage(
6576                                EventHub.SINGLE_LISTBOX_CHOICE, (int)id, 0);
6577                        dialog.dismiss();
6578                    }
6579                });
6580                if (mSelection != -1) {
6581                    listView.setSelection(mSelection);
6582                    listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
6583                    listView.setItemChecked(mSelection, true);
6584                    DataSetObserver observer = new SingleDataSetObserver(
6585                            adapter.getItemId(mSelection), listView, adapter);
6586                    adapter.registerDataSetObserver(observer);
6587                }
6588            }
6589            dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
6590                public void onCancel(DialogInterface dialog) {
6591                    mWebViewCore.sendMessage(
6592                                EventHub.SINGLE_LISTBOX_CHOICE, -2, 0);
6593                }
6594            });
6595            dialog.show();
6596        }
6597    }
6598
6599    /*
6600     * Request a dropdown menu for a listbox with multiple selection.
6601     *
6602     * @param array Labels for the listbox.
6603     * @param enabledArray  State for each element in the list.  See static
6604     *      integers in Container class.
6605     * @param selectedArray Which positions are initally selected.
6606     */
6607    void requestListBox(String[] array, int[] enabledArray, int[]
6608            selectedArray) {
6609        mPrivateHandler.post(
6610                new InvokeListBox(array, enabledArray, selectedArray));
6611    }
6612
6613    private void updateZoomRange(WebViewCore.RestoreState restoreState,
6614            int viewWidth, int minPrefWidth, boolean updateZoomOverview) {
6615        if (restoreState.mMinScale == 0) {
6616            if (restoreState.mMobileSite) {
6617                if (minPrefWidth > Math.max(0, viewWidth)) {
6618                    mMinZoomScale = (float) viewWidth / minPrefWidth;
6619                    mMinZoomScaleFixed = false;
6620                    if (updateZoomOverview) {
6621                        WebSettings settings = getSettings();
6622                        mInZoomOverview = settings.getUseWideViewPort() &&
6623                                settings.getLoadWithOverviewMode();
6624                    }
6625                } else {
6626                    mMinZoomScale = restoreState.mDefaultScale;
6627                    mMinZoomScaleFixed = true;
6628                }
6629            } else {
6630                mMinZoomScale = DEFAULT_MIN_ZOOM_SCALE;
6631                mMinZoomScaleFixed = false;
6632            }
6633        } else {
6634            mMinZoomScale = restoreState.mMinScale;
6635            mMinZoomScaleFixed = true;
6636        }
6637        if (restoreState.mMaxScale == 0) {
6638            mMaxZoomScale = DEFAULT_MAX_ZOOM_SCALE;
6639        } else {
6640            mMaxZoomScale = restoreState.mMaxScale;
6641        }
6642    }
6643
6644    /*
6645     * Request a dropdown menu for a listbox with single selection or a single
6646     * <select> element.
6647     *
6648     * @param array Labels for the listbox.
6649     * @param enabledArray  State for each element in the list.  See static
6650     *      integers in Container class.
6651     * @param selection Which position is initally selected.
6652     */
6653    void requestListBox(String[] array, int[] enabledArray, int selection) {
6654        mPrivateHandler.post(
6655                new InvokeListBox(array, enabledArray, selection));
6656    }
6657
6658    // called by JNI
6659    private void sendMoveFocus(int frame, int node) {
6660        mWebViewCore.sendMessage(EventHub.SET_MOVE_FOCUS,
6661                new WebViewCore.CursorData(frame, node, 0, 0));
6662    }
6663
6664    // called by JNI
6665    private void sendMoveMouse(int frame, int node, int x, int y) {
6666        mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE,
6667                new WebViewCore.CursorData(frame, node, x, y));
6668    }
6669
6670    /*
6671     * Send a mouse move event to the webcore thread.
6672     *
6673     * @param removeFocus Pass true if the "mouse" cursor is now over a node
6674     *                    which wants key events, but it is not the focus. This
6675     *                    will make the visual appear as though nothing is in
6676     *                    focus.  Remove the WebTextView, if present, and stop
6677     *                    drawing the blinking caret.
6678     * called by JNI
6679     */
6680    private void sendMoveMouseIfLatest(boolean removeFocus) {
6681        if (removeFocus) {
6682            clearTextEntry(true);
6683        }
6684        mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE_IF_LATEST,
6685                cursorData());
6686    }
6687
6688    // called by JNI
6689    private void sendMotionUp(int touchGeneration,
6690            int frame, int node, int x, int y) {
6691        WebViewCore.TouchUpData touchUpData = new WebViewCore.TouchUpData();
6692        touchUpData.mMoveGeneration = touchGeneration;
6693        touchUpData.mFrame = frame;
6694        touchUpData.mNode = node;
6695        touchUpData.mX = x;
6696        touchUpData.mY = y;
6697        mWebViewCore.sendMessage(EventHub.TOUCH_UP, touchUpData);
6698    }
6699
6700
6701    private int getScaledMaxXScroll() {
6702        int width;
6703        if (mHeightCanMeasure == false) {
6704            width = getViewWidth() / 4;
6705        } else {
6706            Rect visRect = new Rect();
6707            calcOurVisibleRect(visRect);
6708            width = visRect.width() / 2;
6709        }
6710        // FIXME the divisor should be retrieved from somewhere
6711        return viewToContentX(width);
6712    }
6713
6714    private int getScaledMaxYScroll() {
6715        int height;
6716        if (mHeightCanMeasure == false) {
6717            height = getViewHeight() / 4;
6718        } else {
6719            Rect visRect = new Rect();
6720            calcOurVisibleRect(visRect);
6721            height = visRect.height() / 2;
6722        }
6723        // FIXME the divisor should be retrieved from somewhere
6724        // the closest thing today is hard-coded into ScrollView.java
6725        // (from ScrollView.java, line 363)   int maxJump = height/2;
6726        return Math.round(height * mInvActualScale);
6727    }
6728
6729    /**
6730     * Called by JNI to invalidate view
6731     */
6732    private void viewInvalidate() {
6733        invalidate();
6734    }
6735
6736    // return true if the key was handled
6737    private boolean navHandledKey(int keyCode, int count, boolean noScroll,
6738            long time, boolean ignorePlugin) {
6739        if (mNativeClass == 0) {
6740            return false;
6741        }
6742        if (ignorePlugin == false && nativeFocusIsPlugin()) {
6743            KeyEvent event = new KeyEvent(time, time, KeyEvent.ACTION_DOWN
6744                , keyCode, count, (mShiftIsPressed ? KeyEvent.META_SHIFT_ON : 0)
6745                | (false ? KeyEvent.META_ALT_ON : 0) // FIXME
6746                | (false ? KeyEvent.META_SYM_ON : 0) // FIXME
6747                , 0, 0, 0);
6748            mWebViewCore.sendMessage(EventHub.KEY_DOWN, event);
6749            mWebViewCore.sendMessage(EventHub.KEY_UP, event);
6750            return true;
6751        }
6752        mLastCursorTime = time;
6753        mLastCursorBounds = nativeGetCursorRingBounds();
6754        boolean keyHandled
6755                = nativeMoveCursor(keyCode, count, noScroll) == false;
6756        if (DebugFlags.WEB_VIEW) {
6757            Log.v(LOGTAG, "navHandledKey mLastCursorBounds=" + mLastCursorBounds
6758                    + " mLastCursorTime=" + mLastCursorTime
6759                    + " handled=" + keyHandled);
6760        }
6761        if (keyHandled == false || mHeightCanMeasure == false) {
6762            return keyHandled;
6763        }
6764        Rect contentCursorRingBounds = nativeGetCursorRingBounds();
6765        if (contentCursorRingBounds.isEmpty()) return keyHandled;
6766        Rect viewCursorRingBounds = contentToViewRect(contentCursorRingBounds);
6767        Rect visRect = new Rect();
6768        calcOurVisibleRect(visRect);
6769        Rect outset = new Rect(visRect);
6770        int maxXScroll = visRect.width() / 2;
6771        int maxYScroll = visRect.height() / 2;
6772        outset.inset(-maxXScroll, -maxYScroll);
6773        if (Rect.intersects(outset, viewCursorRingBounds) == false) {
6774            return keyHandled;
6775        }
6776        // FIXME: Necessary because ScrollView/ListView do not scroll left/right
6777        int maxH = Math.min(viewCursorRingBounds.right - visRect.right,
6778                maxXScroll);
6779        if (maxH > 0) {
6780            pinScrollBy(maxH, 0, true, 0);
6781        } else {
6782            maxH = Math.max(viewCursorRingBounds.left - visRect.left,
6783                    -maxXScroll);
6784            if (maxH < 0) {
6785                pinScrollBy(maxH, 0, true, 0);
6786            }
6787        }
6788        if (mLastCursorBounds.isEmpty()) return keyHandled;
6789        if (mLastCursorBounds.equals(contentCursorRingBounds)) {
6790            return keyHandled;
6791        }
6792        if (DebugFlags.WEB_VIEW) {
6793            Log.v(LOGTAG, "navHandledKey contentCursorRingBounds="
6794                    + contentCursorRingBounds);
6795        }
6796        requestRectangleOnScreen(viewCursorRingBounds);
6797        mUserScroll = true;
6798        return keyHandled;
6799    }
6800
6801    /**
6802     * Set the background color. It's white by default. Pass
6803     * zero to make the view transparent.
6804     * @param color   the ARGB color described by Color.java
6805     */
6806    public void setBackgroundColor(int color) {
6807        mBackgroundColor = color;
6808        mWebViewCore.sendMessage(EventHub.SET_BACKGROUND_COLOR, color);
6809    }
6810
6811    public void debugDump() {
6812        nativeDebugDump();
6813        mWebViewCore.sendMessage(EventHub.DUMP_NAVTREE);
6814    }
6815
6816    /**
6817     * Draw the HTML page into the specified canvas. This call ignores any
6818     * view-specific zoom, scroll offset, or other changes. It does not draw
6819     * any view-specific chrome, such as progress or URL bars.
6820     *
6821     * @hide only needs to be accessible to Browser and testing
6822     */
6823    public void drawPage(Canvas canvas) {
6824        mWebViewCore.drawContentPicture(canvas, 0, false, false);
6825    }
6826
6827    /**
6828     * Set the time to wait between passing touches to WebCore. See also the
6829     * TOUCH_SENT_INTERVAL member for further discussion.
6830     *
6831     * @hide This is only used by the DRT test application.
6832     */
6833    public void setTouchInterval(int interval) {
6834        mCurrentTouchInterval = interval;
6835    }
6836
6837    /**
6838     *  Update our cache with updatedText.
6839     *  @param updatedText  The new text to put in our cache.
6840     */
6841    /* package */ void updateCachedTextfield(String updatedText) {
6842        // Also place our generation number so that when we look at the cache
6843        // we recognize that it is up to date.
6844        nativeUpdateCachedTextfield(updatedText, mTextGeneration);
6845    }
6846
6847    private native int nativeCacheHitFramePointer();
6848    private native Rect nativeCacheHitNodeBounds();
6849    private native int nativeCacheHitNodePointer();
6850    /* package */ native void nativeClearCursor();
6851    private native void     nativeCreate(int ptr);
6852    private native int      nativeCursorFramePointer();
6853    private native Rect     nativeCursorNodeBounds();
6854    private native int nativeCursorNodePointer();
6855    /* package */ native boolean nativeCursorMatchesFocus();
6856    private native boolean  nativeCursorIntersects(Rect visibleRect);
6857    private native boolean  nativeCursorIsAnchor();
6858    private native boolean  nativeCursorIsTextInput();
6859    private native Point    nativeCursorPosition();
6860    private native String   nativeCursorText();
6861    /**
6862     * Returns true if the native cursor node says it wants to handle key events
6863     * (ala plugins). This can only be called if mNativeClass is non-zero!
6864     */
6865    private native boolean  nativeCursorWantsKeyEvents();
6866    private native void     nativeDebugDump();
6867    private native void     nativeDestroy();
6868    private native boolean  nativeEvaluateLayersAnimations();
6869    private native void     nativeDrawExtras(Canvas canvas, int extra);
6870    private native void     nativeDumpDisplayTree(String urlOrNull);
6871    private native int      nativeFindAll(String findLower, String findUpper);
6872    private native void     nativeFindNext(boolean forward);
6873    /* package */ native int      nativeFocusCandidateFramePointer();
6874    private native boolean  nativeFocusCandidateIsPassword();
6875    private native boolean  nativeFocusCandidateIsRtlText();
6876    private native boolean  nativeFocusCandidateIsTextInput();
6877    /* package */ native int      nativeFocusCandidateMaxLength();
6878    /* package */ native String   nativeFocusCandidateName();
6879    private native Rect     nativeFocusCandidateNodeBounds();
6880    private native int      nativeFocusCandidatePointer();
6881    private native String   nativeFocusCandidateText();
6882    private native int      nativeFocusCandidateTextSize();
6883    /**
6884     * Returns an integer corresponding to WebView.cpp::type.
6885     * See WebTextView.setType()
6886     */
6887    private native int      nativeFocusCandidateType();
6888    private native boolean  nativeFocusIsPlugin();
6889    /* package */ native int nativeFocusNodePointer();
6890    private native Rect     nativeGetCursorRingBounds();
6891    private native String   nativeGetSelection();
6892    private native boolean  nativeHasCursorNode();
6893    private native boolean  nativeHasFocusNode();
6894    private native void     nativeHideCursor();
6895    private native String   nativeImageURI(int x, int y);
6896    private native void     nativeInstrumentReport();
6897    /* package */ native boolean nativeMoveCursorToNextTextInput();
6898    // return true if the page has been scrolled
6899    private native boolean  nativeMotionUp(int x, int y, int slop);
6900    // returns false if it handled the key
6901    private native boolean  nativeMoveCursor(int keyCode, int count,
6902            boolean noScroll);
6903    private native int      nativeMoveGeneration();
6904    private native void     nativeMoveSelection(int x, int y,
6905            boolean extendSelection);
6906    private native boolean  nativePointInNavCache(int x, int y, int slop);
6907    // Like many other of our native methods, you must make sure that
6908    // mNativeClass is not null before calling this method.
6909    private native void     nativeRecordButtons(boolean focused,
6910            boolean pressed, boolean invalidate);
6911    private native void     nativeSelectBestAt(Rect rect);
6912    private native void     nativeSetFindIsEmpty();
6913    private native void     nativeSetFindIsUp(boolean isUp);
6914    private native void     nativeSetFollowedLink(boolean followed);
6915    private native void     nativeSetHeightCanMeasure(boolean measure);
6916    private native void     nativeSetRootLayer(int layer);
6917    private native void     nativeSetSelectionPointer(boolean set,
6918            float scale, int x, int y, boolean extendSelection);
6919    private native void     nativeSetSelectionRegion(boolean set);
6920    private native int      nativeTextGeneration();
6921    // Never call this version except by updateCachedTextfield(String) -
6922    // we always want to pass in our generation number.
6923    private native void     nativeUpdateCachedTextfield(String updatedText,
6924            int generation);
6925    // return NO_LEFTEDGE means failure.
6926    private static final int NO_LEFTEDGE = -1;
6927    private native int      nativeGetBlockLeftEdge(int x, int y, float scale);
6928}
6929