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