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