WebView.java revision 200c13d37fb394c218a3824c428a116207266316
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.getDefaultScale();
3678        if (zoom) {
3679            mZoomManager.setZoomCenter(mLastTouchX, mLastTouchY);
3680            mZoomManager.setZoomScale(mZoomManager.getDefaultScale(), 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 and contentEditable.
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        if (imm.isActive(this)
3705                || (inEditingMode() && imm.isActive(mWebTextView))) {
3706            imm.hideSoftInputFromWindow(this.getWindowToken(), 0);
3707        }
3708    }
3709
3710    /*
3711     * This method checks the current focus and cursor and potentially rebuilds
3712     * mWebTextView to have the appropriate properties, such as password,
3713     * multiline, and what text it contains.  It also removes it if necessary.
3714     */
3715    /* package */ void rebuildWebTextView() {
3716        // If the WebView does not have focus, do nothing until it gains focus.
3717        if (!hasFocus() && (null == mWebTextView || !mWebTextView.hasFocus())) {
3718            return;
3719        }
3720        boolean alreadyThere = inEditingMode();
3721        // inEditingMode can only return true if mWebTextView is non-null,
3722        // so we can safely call remove() if (alreadyThere)
3723        if (0 == mNativeClass || !nativeFocusCandidateIsTextInput()) {
3724            if (alreadyThere) {
3725                mWebTextView.remove();
3726            }
3727            return;
3728        }
3729        // At this point, we know we have found an input field, so go ahead
3730        // and create the WebTextView if necessary.
3731        if (mWebTextView == null) {
3732            mWebTextView = new WebTextView(mContext, WebView.this);
3733            // Initialize our generation number.
3734            mTextGeneration = 0;
3735        }
3736        mWebTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
3737                contentToViewDimension(nativeFocusCandidateTextSize()));
3738        Rect visibleRect = new Rect();
3739        calcOurContentVisibleRect(visibleRect);
3740        // Note that sendOurVisibleRect calls viewToContent, so the coordinates
3741        // should be in content coordinates.
3742        Rect bounds = nativeFocusCandidateNodeBounds();
3743        Rect vBox = contentToViewRect(bounds);
3744        mWebTextView.setRect(vBox.left, vBox.top, vBox.width(), vBox.height());
3745        if (!Rect.intersects(bounds, visibleRect)) {
3746            mWebTextView.bringIntoView();
3747        }
3748        String text = nativeFocusCandidateText();
3749        int nodePointer = nativeFocusCandidatePointer();
3750        if (alreadyThere && mWebTextView.isSameTextField(nodePointer)) {
3751            // It is possible that we have the same textfield, but it has moved,
3752            // i.e. In the case of opening/closing the screen.
3753            // In that case, we need to set the dimensions, but not the other
3754            // aspects.
3755            // If the text has been changed by webkit, update it.  However, if
3756            // there has been more UI text input, ignore it.  We will receive
3757            // another update when that text is recognized.
3758            if (text != null && !text.equals(mWebTextView.getText().toString())
3759                    && nativeTextGeneration() == mTextGeneration) {
3760                mWebTextView.setTextAndKeepSelection(text);
3761            }
3762        } else {
3763            mWebTextView.setGravity(nativeFocusCandidateIsRtlText() ?
3764                    Gravity.RIGHT : Gravity.NO_GRAVITY);
3765            // This needs to be called before setType, which may call
3766            // requestFormData, and it needs to have the correct nodePointer.
3767            mWebTextView.setNodePointer(nodePointer);
3768            mWebTextView.setType(nativeFocusCandidateType());
3769            if (null == text) {
3770                if (DebugFlags.WEB_VIEW) {
3771                    Log.v(LOGTAG, "rebuildWebTextView null == text");
3772                }
3773                text = "";
3774            }
3775            mWebTextView.setTextAndKeepSelection(text);
3776            InputMethodManager imm = InputMethodManager.peekInstance();
3777            if (imm != null && imm.isActive(mWebTextView)) {
3778                imm.restartInput(mWebTextView);
3779            }
3780        }
3781        mWebTextView.requestFocus();
3782    }
3783
3784    /**
3785     * Tell webkit to put the cursor on screen.
3786     */
3787    /* package */ void revealSelection() {
3788        if (mWebViewCore != null) {
3789            mWebViewCore.sendMessage(EventHub.REVEAL_SELECTION);
3790        }
3791    }
3792
3793    /**
3794     * Called by WebTextView to find saved form data associated with the
3795     * textfield
3796     * @param name Name of the textfield.
3797     * @param nodePointer Pointer to the node of the textfield, so it can be
3798     *          compared to the currently focused textfield when the data is
3799     *          retrieved.
3800     */
3801    /* package */ void requestFormData(String name, int nodePointer) {
3802        if (mWebViewCore.getSettings().getSaveFormData()) {
3803            Message update = mPrivateHandler.obtainMessage(REQUEST_FORM_DATA);
3804            update.arg1 = nodePointer;
3805            RequestFormData updater = new RequestFormData(name, getUrl(),
3806                    update);
3807            Thread t = new Thread(updater);
3808            t.start();
3809        }
3810    }
3811
3812    /**
3813     * Pass a message to find out the <label> associated with the <input>
3814     * identified by nodePointer
3815     * @param framePointer Pointer to the frame containing the <input> node
3816     * @param nodePointer Pointer to the node for which a <label> is desired.
3817     */
3818    /* package */ void requestLabel(int framePointer, int nodePointer) {
3819        mWebViewCore.sendMessage(EventHub.REQUEST_LABEL, framePointer,
3820                nodePointer);
3821    }
3822
3823    /*
3824     * This class requests an Adapter for the WebTextView which shows past
3825     * entries stored in the database.  It is a Runnable so that it can be done
3826     * in its own thread, without slowing down the UI.
3827     */
3828    private class RequestFormData implements Runnable {
3829        private String mName;
3830        private String mUrl;
3831        private Message mUpdateMessage;
3832
3833        public RequestFormData(String name, String url, Message msg) {
3834            mName = name;
3835            mUrl = url;
3836            mUpdateMessage = msg;
3837        }
3838
3839        public void run() {
3840            ArrayList<String> pastEntries = mDatabase.getFormData(mUrl, mName);
3841            if (pastEntries.size() > 0) {
3842                AutoCompleteAdapter adapter = new
3843                        AutoCompleteAdapter(mContext, pastEntries);
3844                mUpdateMessage.obj = adapter;
3845                mUpdateMessage.sendToTarget();
3846            }
3847        }
3848    }
3849
3850    /**
3851     * Dump the display tree to "/sdcard/displayTree.txt"
3852     *
3853     * @hide debug only
3854     */
3855    public void dumpDisplayTree() {
3856        nativeDumpDisplayTree(getUrl());
3857    }
3858
3859    /**
3860     * Dump the dom tree to adb shell if "toFile" is False, otherwise dump it to
3861     * "/sdcard/domTree.txt"
3862     *
3863     * @hide debug only
3864     */
3865    public void dumpDomTree(boolean toFile) {
3866        mWebViewCore.sendMessage(EventHub.DUMP_DOMTREE, toFile ? 1 : 0, 0);
3867    }
3868
3869    /**
3870     * Dump the render tree to adb shell if "toFile" is False, otherwise dump it
3871     * to "/sdcard/renderTree.txt"
3872     *
3873     * @hide debug only
3874     */
3875    public void dumpRenderTree(boolean toFile) {
3876        mWebViewCore.sendMessage(EventHub.DUMP_RENDERTREE, toFile ? 1 : 0, 0);
3877    }
3878
3879    /**
3880     * Called by DRT on UI thread, need to proxy to WebCore thread.
3881     *
3882     * @hide debug only
3883     */
3884    public void useMockDeviceOrientation() {
3885        mWebViewCore.sendMessage(EventHub.USE_MOCK_DEVICE_ORIENTATION);
3886    }
3887
3888    /**
3889     * Called by DRT on WebCore thread.
3890     *
3891     * @hide debug only
3892     */
3893    public void setMockDeviceOrientation(boolean canProvideAlpha, double alpha,
3894            boolean canProvideBeta, double beta, boolean canProvideGamma, double gamma) {
3895        mWebViewCore.setMockDeviceOrientation(canProvideAlpha, alpha, canProvideBeta, beta,
3896                canProvideGamma, gamma);
3897    }
3898
3899    /**
3900     * Dump the V8 counters to standard output.
3901     * Note that you need a build with V8 and WEBCORE_INSTRUMENTATION set to
3902     * true. Otherwise, this will do nothing.
3903     *
3904     * @hide debug only
3905     */
3906    public void dumpV8Counters() {
3907        mWebViewCore.sendMessage(EventHub.DUMP_V8COUNTERS);
3908    }
3909
3910    // This is used to determine long press with the center key.  Does not
3911    // affect long press with the trackball/touch.
3912    private boolean mGotCenterDown = false;
3913
3914    @Override
3915    public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) {
3916        // send complex characters to webkit for use by JS and plugins
3917        if (keyCode == KeyEvent.KEYCODE_UNKNOWN && event.getCharacters() != null) {
3918            // pass the key to DOM
3919            mWebViewCore.sendMessage(EventHub.KEY_DOWN, event);
3920            mWebViewCore.sendMessage(EventHub.KEY_UP, event);
3921            // return true as DOM handles the key
3922            return true;
3923        }
3924        return false;
3925    }
3926
3927    @Override
3928    public boolean onKeyDown(int keyCode, KeyEvent event) {
3929        if (DebugFlags.WEB_VIEW) {
3930            Log.v(LOGTAG, "keyDown at " + System.currentTimeMillis()
3931                    + ", " + event + ", unicode=" + event.getUnicodeChar());
3932        }
3933
3934        if (mNativeClass == 0) {
3935            return false;
3936        }
3937
3938        // do this hack up front, so it always works, regardless of touch-mode
3939        if (AUTO_REDRAW_HACK && (keyCode == KeyEvent.KEYCODE_CALL)) {
3940            mAutoRedraw = !mAutoRedraw;
3941            if (mAutoRedraw) {
3942                invalidate();
3943            }
3944            return true;
3945        }
3946
3947        // Bubble up the key event if
3948        // 1. it is a system key; or
3949        // 2. the host application wants to handle it;
3950        // 3. the accessibility injector is present and wants to handle it;
3951        if (event.isSystem()
3952                || mCallbackProxy.uiOverrideKeyEvent(event)
3953                || (mAccessibilityInjector != null && mAccessibilityInjector.onKeyEvent(event))) {
3954            return false;
3955        }
3956
3957        if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT
3958                || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT) {
3959            if (nativePageShouldHandleShiftAndArrows()) {
3960                mShiftIsPressed = true;
3961            } else if (!nativeCursorWantsKeyEvents() && !mSelectingText) {
3962                setUpSelect();
3963            }
3964        }
3965
3966        if (keyCode == KeyEvent.KEYCODE_PAGE_UP) {
3967            pageUp(false);
3968            return true;
3969        }
3970
3971        if (keyCode == KeyEvent.KEYCODE_PAGE_DOWN) {
3972            pageDown(false);
3973            return true;
3974        }
3975
3976        if (keyCode >= KeyEvent.KEYCODE_DPAD_UP
3977                && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) {
3978            switchOutDrawHistory();
3979            if (nativePageShouldHandleShiftAndArrows()) {
3980                letPageHandleNavKey(keyCode, event.getEventTime(), true);
3981                return true;
3982            }
3983            if (mSelectingText) {
3984                int xRate = keyCode == KeyEvent.KEYCODE_DPAD_LEFT
3985                    ? -1 : keyCode == KeyEvent.KEYCODE_DPAD_RIGHT ? 1 : 0;
3986                int yRate = keyCode == KeyEvent.KEYCODE_DPAD_UP ?
3987                    -1 : keyCode == KeyEvent.KEYCODE_DPAD_DOWN ? 1 : 0;
3988                int multiplier = event.getRepeatCount() + 1;
3989                moveSelection(xRate * multiplier, yRate * multiplier);
3990                return true;
3991            }
3992            if (navHandledKey(keyCode, 1, false, event.getEventTime())) {
3993                playSoundEffect(keyCodeToSoundsEffect(keyCode));
3994                return true;
3995            }
3996            // Bubble up the key event as WebView doesn't handle it
3997            return false;
3998        }
3999
4000        if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
4001            switchOutDrawHistory();
4002            if (event.getRepeatCount() == 0) {
4003                if (mSelectingText) {
4004                    return true; // discard press if copy in progress
4005                }
4006                mGotCenterDown = true;
4007                mPrivateHandler.sendMessageDelayed(mPrivateHandler
4008                        .obtainMessage(LONG_PRESS_CENTER), LONG_PRESS_TIMEOUT);
4009                // Already checked mNativeClass, so we do not need to check it
4010                // again.
4011                nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true);
4012                return true;
4013            }
4014            // Bubble up the key event as WebView doesn't handle it
4015            return false;
4016        }
4017
4018        if (keyCode != KeyEvent.KEYCODE_SHIFT_LEFT
4019                && keyCode != KeyEvent.KEYCODE_SHIFT_RIGHT) {
4020            // turn off copy select if a shift-key combo is pressed
4021            selectionDone();
4022            mShiftIsPressed = false;
4023        }
4024
4025        if (getSettings().getNavDump()) {
4026            switch (keyCode) {
4027                case KeyEvent.KEYCODE_4:
4028                    dumpDisplayTree();
4029                    break;
4030                case KeyEvent.KEYCODE_5:
4031                case KeyEvent.KEYCODE_6:
4032                    dumpDomTree(keyCode == KeyEvent.KEYCODE_5);
4033                    break;
4034                case KeyEvent.KEYCODE_7:
4035                case KeyEvent.KEYCODE_8:
4036                    dumpRenderTree(keyCode == KeyEvent.KEYCODE_7);
4037                    break;
4038                case KeyEvent.KEYCODE_9:
4039                    nativeInstrumentReport();
4040                    return true;
4041            }
4042        }
4043
4044        if (nativeCursorIsTextInput()) {
4045            // This message will put the node in focus, for the DOM's notion
4046            // of focus, and make the focuscontroller active
4047            mWebViewCore.sendMessage(EventHub.CLICK, nativeCursorFramePointer(),
4048                    nativeCursorNodePointer());
4049            // This will bring up the WebTextView and put it in focus, for
4050            // our view system's notion of focus
4051            rebuildWebTextView();
4052            // Now we need to pass the event to it
4053            if (inEditingMode()) {
4054                mWebTextView.setDefaultSelection();
4055                return mWebTextView.dispatchKeyEvent(event);
4056            }
4057        } else if (nativeHasFocusNode()) {
4058            // In this case, the cursor is not on a text input, but the focus
4059            // might be.  Check it, and if so, hand over to the WebTextView.
4060            rebuildWebTextView();
4061            if (inEditingMode()) {
4062                mWebTextView.setDefaultSelection();
4063                return mWebTextView.dispatchKeyEvent(event);
4064            }
4065        }
4066
4067        // TODO: should we pass all the keys to DOM or check the meta tag
4068        if (nativeCursorWantsKeyEvents() || true) {
4069            // pass the key to DOM
4070            mWebViewCore.sendMessage(EventHub.KEY_DOWN, event);
4071            // return true as DOM handles the key
4072            return true;
4073        }
4074
4075        // Bubble up the key event as WebView doesn't handle it
4076        return false;
4077    }
4078
4079    @Override
4080    public boolean onKeyUp(int keyCode, KeyEvent event) {
4081        if (DebugFlags.WEB_VIEW) {
4082            Log.v(LOGTAG, "keyUp at " + System.currentTimeMillis()
4083                    + ", " + event + ", unicode=" + event.getUnicodeChar());
4084        }
4085
4086        if (mNativeClass == 0) {
4087            return false;
4088        }
4089
4090        // special CALL handling when cursor node's href is "tel:XXX"
4091        if (keyCode == KeyEvent.KEYCODE_CALL && nativeHasCursorNode()) {
4092            String text = nativeCursorText();
4093            if (!nativeCursorIsTextInput() && text != null
4094                    && text.startsWith(SCHEME_TEL)) {
4095                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(text));
4096                getContext().startActivity(intent);
4097                return true;
4098            }
4099        }
4100
4101        // Bubble up the key event if
4102        // 1. it is a system key; or
4103        // 2. the host application wants to handle it;
4104        // 3. the accessibility injector is present and wants to handle it;
4105        if (event.isSystem()
4106                || mCallbackProxy.uiOverrideKeyEvent(event)
4107                || (mAccessibilityInjector != null && mAccessibilityInjector.onKeyEvent(event))) {
4108            return false;
4109        }
4110
4111        if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT
4112                || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT) {
4113            if (nativePageShouldHandleShiftAndArrows()) {
4114                mShiftIsPressed = false;
4115            } else if (copySelection()) {
4116                selectionDone();
4117                return true;
4118            }
4119        }
4120
4121        if (keyCode >= KeyEvent.KEYCODE_DPAD_UP
4122                && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) {
4123            if (nativePageShouldHandleShiftAndArrows()) {
4124                letPageHandleNavKey(keyCode, event.getEventTime(), false);
4125                return true;
4126            }
4127            // always handle the navigation keys in the UI thread
4128            // Bubble up the key event as WebView doesn't handle it
4129            return false;
4130        }
4131
4132        if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
4133            // remove the long press message first
4134            mPrivateHandler.removeMessages(LONG_PRESS_CENTER);
4135            mGotCenterDown = false;
4136
4137            if (mSelectingText) {
4138                if (mExtendSelection) {
4139                    copySelection();
4140                    selectionDone();
4141                } else {
4142                    mExtendSelection = true;
4143                    nativeSetExtendSelection();
4144                    invalidate(); // draw the i-beam instead of the arrow
4145                }
4146                return true; // discard press if copy in progress
4147            }
4148
4149            // perform the single click
4150            Rect visibleRect = sendOurVisibleRect();
4151            // Note that sendOurVisibleRect calls viewToContent, so the
4152            // coordinates should be in content coordinates.
4153            if (!nativeCursorIntersects(visibleRect)) {
4154                return false;
4155            }
4156            WebViewCore.CursorData data = cursorData();
4157            mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE, data);
4158            playSoundEffect(SoundEffectConstants.CLICK);
4159            if (nativeCursorIsTextInput()) {
4160                rebuildWebTextView();
4161                centerKeyPressOnTextField();
4162                if (inEditingMode()) {
4163                    mWebTextView.setDefaultSelection();
4164                }
4165                return true;
4166            }
4167            clearTextEntry();
4168            nativeShowCursorTimed();
4169            if (!mCallbackProxy.uiOverrideUrlLoading(nativeCursorText())) {
4170                mWebViewCore.sendMessage(EventHub.CLICK, data.mFrame,
4171                        nativeCursorNodePointer());
4172            }
4173            return true;
4174        }
4175
4176        // TODO: should we pass all the keys to DOM or check the meta tag
4177        if (nativeCursorWantsKeyEvents() || true) {
4178            // pass the key to DOM
4179            mWebViewCore.sendMessage(EventHub.KEY_UP, event);
4180            // return true as DOM handles the key
4181            return true;
4182        }
4183
4184        // Bubble up the key event as WebView doesn't handle it
4185        return false;
4186    }
4187
4188    private void setUpSelect() {
4189        if (0 == mNativeClass) return; // client isn't initialized
4190        if (inFullScreenMode()) return;
4191        if (mSelectingText) return;
4192        mExtendSelection = false;
4193        mSelectingText = mDrawSelectionPointer = true;
4194        // don't let the picture change during text selection
4195        WebViewCore.pauseUpdatePicture(mWebViewCore);
4196        nativeResetSelection();
4197        if (nativeHasCursorNode()) {
4198            Rect rect = nativeCursorNodeBounds();
4199            mSelectX = contentToViewX(rect.left);
4200            mSelectY = contentToViewY(rect.top);
4201        } else if (mLastTouchY > getVisibleTitleHeight()) {
4202            mSelectX = mScrollX + (int) mLastTouchX;
4203            mSelectY = mScrollY + (int) mLastTouchY;
4204        } else {
4205            mSelectX = mScrollX + getViewWidth() / 2;
4206            mSelectY = mScrollY + getViewHeightWithTitle() / 2;
4207        }
4208        nativeHideCursor();
4209        mSelectCallback = new SelectActionModeCallback();
4210        mSelectCallback.setWebView(this);
4211        View titleBar = mTitleBar;
4212        // We do not want to show the embedded title bar during find or
4213        // select, but keep track of it so that it can be replaced when the
4214        // mode is exited.
4215        setEmbeddedTitleBar(null);
4216        mSelectCallback.setTitleBar(titleBar);
4217        startActionMode(mSelectCallback);
4218    }
4219
4220    /**
4221     * Use this method to put the WebView into text selection mode.
4222     * Do not rely on this functionality; it will be deprecated in the future.
4223     */
4224    public void emulateShiftHeld() {
4225        setUpSelect();
4226    }
4227
4228    /**
4229     * Select all of the text in this WebView.
4230     */
4231    void selectAll() {
4232        if (0 == mNativeClass) return; // client isn't initialized
4233        if (inFullScreenMode()) return;
4234        if (!mSelectingText) setUpSelect();
4235        nativeSelectAll();
4236        mDrawSelectionPointer = false;
4237        mExtendSelection = true;
4238        invalidate();
4239    }
4240
4241    /**
4242     * Called when the selection has been removed.
4243     */
4244    void selectionDone() {
4245        if (mSelectingText) {
4246            mSelectingText = false;
4247            // finish is idempotent, so this is fine even if selectionDone was
4248            // called by mSelectCallback.onDestroyActionMode
4249            mSelectCallback.finish();
4250            mSelectCallback = null;
4251            WebViewCore.resumeUpdatePicture(mWebViewCore);
4252            invalidate(); // redraw without selection
4253        }
4254    }
4255
4256    /**
4257     * Copy the selection to the clipboard
4258     */
4259    boolean copySelection() {
4260        boolean copiedSomething = false;
4261        String selection = getSelection();
4262        if (selection != "") {
4263            if (DebugFlags.WEB_VIEW) {
4264                Log.v(LOGTAG, "copySelection \"" + selection + "\"");
4265            }
4266            Toast.makeText(mContext
4267                    , com.android.internal.R.string.text_copied
4268                    , Toast.LENGTH_SHORT).show();
4269            copiedSomething = true;
4270            ClipboardManager cm = (ClipboardManager)getContext()
4271                    .getSystemService(Context.CLIPBOARD_SERVICE);
4272            cm.setText(selection);
4273        }
4274        invalidate(); // remove selection region and pointer
4275        return copiedSomething;
4276    }
4277
4278    /**
4279     * Returns the currently highlighted text as a string.
4280     */
4281    String getSelection() {
4282        if (mNativeClass == 0) return "";
4283        return nativeGetSelection();
4284    }
4285
4286    @Override
4287    protected void onAttachedToWindow() {
4288        super.onAttachedToWindow();
4289        if (hasWindowFocus()) setActive(true);
4290    }
4291
4292    @Override
4293    protected void onDetachedFromWindow() {
4294        clearTextEntry();
4295        mZoomManager.dismissZoomPicker();
4296        if (hasWindowFocus()) setActive(false);
4297        super.onDetachedFromWindow();
4298    }
4299
4300    @Override
4301    protected void onVisibilityChanged(View changedView, int visibility) {
4302        super.onVisibilityChanged(changedView, visibility);
4303        // The zoomManager may be null if the webview is created from XML that
4304        // specifies the view's visibility param as not visible (see http://b/2794841)
4305        if (visibility != View.VISIBLE && mZoomManager != null) {
4306            mZoomManager.dismissZoomPicker();
4307        }
4308    }
4309
4310    /**
4311     * @deprecated WebView no longer needs to implement
4312     * ViewGroup.OnHierarchyChangeListener.  This method does nothing now.
4313     */
4314    @Deprecated
4315    public void onChildViewAdded(View parent, View child) {}
4316
4317    /**
4318     * @deprecated WebView no longer needs to implement
4319     * ViewGroup.OnHierarchyChangeListener.  This method does nothing now.
4320     */
4321    @Deprecated
4322    public void onChildViewRemoved(View p, View child) {}
4323
4324    /**
4325     * @deprecated WebView should not have implemented
4326     * ViewTreeObserver.OnGlobalFocusChangeListener.  This method
4327     * does nothing now.
4328     */
4329    @Deprecated
4330    public void onGlobalFocusChanged(View oldFocus, View newFocus) {
4331    }
4332
4333    private void setActive(boolean active) {
4334        if (active) {
4335            if (hasFocus()) {
4336                // If our window regained focus, and we have focus, then begin
4337                // drawing the cursor ring
4338                mDrawCursorRing = true;
4339                setFocusControllerActive(true);
4340                if (mNativeClass != 0) {
4341                    nativeRecordButtons(true, false, true);
4342                }
4343            } else {
4344                if (!inEditingMode()) {
4345                    // If our window gained focus, but we do not have it, do not
4346                    // draw the cursor ring.
4347                    mDrawCursorRing = false;
4348                    setFocusControllerActive(false);
4349                }
4350                // We do not call nativeRecordButtons here because we assume
4351                // that when we lost focus, or window focus, it got called with
4352                // false for the first parameter
4353            }
4354        } else {
4355            if (!mZoomManager.isZoomPickerVisible()) {
4356                /*
4357                 * The external zoom controls come in their own window, so our
4358                 * window loses focus. Our policy is to not draw the cursor ring
4359                 * if our window is not focused, but this is an exception since
4360                 * the user can still navigate the web page with the zoom
4361                 * controls showing.
4362                 */
4363                mDrawCursorRing = false;
4364            }
4365            mGotKeyDown = false;
4366            mShiftIsPressed = false;
4367            mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
4368            mTouchMode = TOUCH_DONE_MODE;
4369            if (mNativeClass != 0) {
4370                nativeRecordButtons(false, false, true);
4371            }
4372            setFocusControllerActive(false);
4373        }
4374        invalidate();
4375    }
4376
4377    // To avoid drawing the cursor ring, and remove the TextView when our window
4378    // loses focus.
4379    @Override
4380    public void onWindowFocusChanged(boolean hasWindowFocus) {
4381        setActive(hasWindowFocus);
4382        if (hasWindowFocus) {
4383            JWebCoreJavaBridge.setActiveWebView(this);
4384        } else {
4385            JWebCoreJavaBridge.removeActiveWebView(this);
4386        }
4387        super.onWindowFocusChanged(hasWindowFocus);
4388    }
4389
4390    /*
4391     * Pass a message to WebCore Thread, telling the WebCore::Page's
4392     * FocusController to be  "inactive" so that it will
4393     * not draw the blinking cursor.  It gets set to "active" to draw the cursor
4394     * in WebViewCore.cpp, when the WebCore thread receives key events/clicks.
4395     */
4396    /* package */ void setFocusControllerActive(boolean active) {
4397        if (mWebViewCore == null) return;
4398        mWebViewCore.sendMessage(EventHub.SET_ACTIVE, active ? 1 : 0, 0);
4399    }
4400
4401    @Override
4402    protected void onFocusChanged(boolean focused, int direction,
4403            Rect previouslyFocusedRect) {
4404        if (DebugFlags.WEB_VIEW) {
4405            Log.v(LOGTAG, "MT focusChanged " + focused + ", " + direction);
4406        }
4407        if (focused) {
4408            // When we regain focus, if we have window focus, resume drawing
4409            // the cursor ring
4410            if (hasWindowFocus()) {
4411                mDrawCursorRing = true;
4412                if (mNativeClass != 0) {
4413                    nativeRecordButtons(true, false, true);
4414                }
4415                setFocusControllerActive(true);
4416            //} else {
4417                // The WebView has gained focus while we do not have
4418                // windowfocus.  When our window lost focus, we should have
4419                // called nativeRecordButtons(false...)
4420            }
4421        } else {
4422            // When we lost focus, unless focus went to the TextView (which is
4423            // true if we are in editing mode), stop drawing the cursor ring.
4424            if (!inEditingMode()) {
4425                mDrawCursorRing = false;
4426                if (mNativeClass != 0) {
4427                    nativeRecordButtons(false, false, true);
4428                }
4429                setFocusControllerActive(false);
4430            }
4431            mGotKeyDown = false;
4432        }
4433
4434        super.onFocusChanged(focused, direction, previouslyFocusedRect);
4435    }
4436
4437    /**
4438     * @hide
4439     */
4440    @Override
4441    protected boolean setFrame(int left, int top, int right, int bottom) {
4442        boolean changed = super.setFrame(left, top, right, bottom);
4443        if (!changed && mHeightCanMeasure) {
4444            // When mHeightCanMeasure is true, we will set mLastHeightSent to 0
4445            // in WebViewCore after we get the first layout. We do call
4446            // requestLayout() when we get contentSizeChanged(). But the View
4447            // system won't call onSizeChanged if the dimension is not changed.
4448            // In this case, we need to call sendViewSizeZoom() explicitly to
4449            // notify the WebKit about the new dimensions.
4450            sendViewSizeZoom(false);
4451        }
4452        return changed;
4453    }
4454
4455    @Override
4456    protected void onSizeChanged(int w, int h, int ow, int oh) {
4457        super.onSizeChanged(w, h, ow, oh);
4458
4459        // adjust the max viewport width depending on the view dimensions. This
4460        // is to ensure the scaling is not going insane. So do not shrink it if
4461        // the view size is temporarily smaller, e.g. when soft keyboard is up.
4462        int newMaxViewportWidth = (int) (Math.max(w, h) / mZoomManager.getDefaultMinZoomScale());
4463        if (newMaxViewportWidth > sMaxViewportWidth) {
4464            sMaxViewportWidth = newMaxViewportWidth;
4465        }
4466
4467        mZoomManager.onSizeChanged(w, h, ow, oh);
4468    }
4469
4470    @Override
4471    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
4472        super.onScrollChanged(l, t, oldl, oldt);
4473        sendOurVisibleRect();
4474        // update WebKit if visible title bar height changed. The logic is same
4475        // as getVisibleTitleHeight.
4476        int titleHeight = getTitleHeight();
4477        if (Math.max(titleHeight - t, 0) != Math.max(titleHeight - oldt, 0)) {
4478            sendViewSizeZoom(false);
4479        }
4480    }
4481
4482    @Override
4483    public boolean dispatchKeyEvent(KeyEvent event) {
4484        boolean dispatch = true;
4485
4486        // Textfields, plugins, and contentEditable nodes need to receive the
4487        // shift up key even if another key was released while the shift key
4488        // was held down.
4489        if (!inEditingMode() && (mNativeClass == 0
4490                || !nativePageShouldHandleShiftAndArrows())) {
4491            if (event.getAction() == KeyEvent.ACTION_DOWN) {
4492                mGotKeyDown = true;
4493            } else {
4494                if (!mGotKeyDown) {
4495                    /*
4496                     * We got a key up for which we were not the recipient of
4497                     * the original key down. Don't give it to the view.
4498                     */
4499                    dispatch = false;
4500                }
4501                mGotKeyDown = false;
4502            }
4503        }
4504
4505        if (dispatch) {
4506            return super.dispatchKeyEvent(event);
4507        } else {
4508            // We didn't dispatch, so let something else handle the key
4509            return false;
4510        }
4511    }
4512
4513    // Here are the snap align logic:
4514    // 1. If it starts nearly horizontally or vertically, snap align;
4515    // 2. If there is a dramitic direction change, let it go;
4516    // 3. If there is a same direction back and forth, lock it.
4517
4518    // adjustable parameters
4519    private int mMinLockSnapReverseDistance;
4520    private static final float MAX_SLOPE_FOR_DIAG = 1.5f;
4521    private static final int MIN_BREAK_SNAP_CROSS_DISTANCE = 80;
4522
4523    private static int sign(float x) {
4524        return x > 0 ? 1 : (x < 0 ? -1 : 0);
4525    }
4526
4527    // if the page can scroll <= this value, we won't allow the drag tracker
4528    // to have any effect.
4529    private static final int MIN_SCROLL_AMOUNT_TO_DISABLE_DRAG_TRACKER = 4;
4530
4531    private class DragTrackerHandler {
4532        private final DragTracker mProxy;
4533        private final float mStartY, mStartX;
4534        private final float mMinDY, mMinDX;
4535        private final float mMaxDY, mMaxDX;
4536        private float mCurrStretchY, mCurrStretchX;
4537        private int mSX, mSY;
4538        private Interpolator mInterp;
4539        private float[] mXY = new float[2];
4540
4541        // inner (non-state) classes can't have enums :(
4542        private static final int DRAGGING_STATE = 0;
4543        private static final int ANIMATING_STATE = 1;
4544        private static final int FINISHED_STATE = 2;
4545        private int mState;
4546
4547        public DragTrackerHandler(float x, float y, DragTracker proxy) {
4548            mProxy = proxy;
4549
4550            int docBottom = computeVerticalScrollRange() + getTitleHeight();
4551            int viewTop = getScrollY();
4552            int viewBottom = viewTop + getHeight();
4553
4554            mStartY = y;
4555            mMinDY = -viewTop;
4556            mMaxDY = docBottom - viewBottom;
4557
4558            if (DebugFlags.DRAG_TRACKER || DEBUG_DRAG_TRACKER) {
4559                Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, " dragtracker y= " + y +
4560                      " up/down= " + mMinDY + " " + mMaxDY);
4561            }
4562
4563            int docRight = computeHorizontalScrollRange();
4564            int viewLeft = getScrollX();
4565            int viewRight = viewLeft + getWidth();
4566            mStartX = x;
4567            mMinDX = -viewLeft;
4568            mMaxDX = docRight - viewRight;
4569
4570            mState = DRAGGING_STATE;
4571            mProxy.onStartDrag(x, y);
4572
4573            // ensure we buildBitmap at least once
4574            mSX = -99999;
4575        }
4576
4577        private float computeStretch(float delta, float min, float max) {
4578            float stretch = 0;
4579            if (max - min > MIN_SCROLL_AMOUNT_TO_DISABLE_DRAG_TRACKER) {
4580                if (delta < min) {
4581                    stretch = delta - min;
4582                } else if (delta > max) {
4583                    stretch = delta - max;
4584                }
4585            }
4586            return stretch;
4587        }
4588
4589        public void dragTo(float x, float y) {
4590            float sy = computeStretch(mStartY - y, mMinDY, mMaxDY);
4591            float sx = computeStretch(mStartX - x, mMinDX, mMaxDX);
4592
4593            if ((mSnapScrollMode & SNAP_X) != 0) {
4594                sy = 0;
4595            } else if ((mSnapScrollMode & SNAP_Y) != 0) {
4596                sx = 0;
4597            }
4598
4599            if (mCurrStretchX != sx || mCurrStretchY != sy) {
4600                mCurrStretchX = sx;
4601                mCurrStretchY = sy;
4602                if (DebugFlags.DRAG_TRACKER || DEBUG_DRAG_TRACKER) {
4603                    Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, "---- stretch " + sx +
4604                          " " + sy);
4605                }
4606                if (mProxy.onStretchChange(sx, sy)) {
4607                    invalidate();
4608                }
4609            }
4610        }
4611
4612        public void stopDrag() {
4613            final int DURATION = 200;
4614            int now = (int)SystemClock.uptimeMillis();
4615            mInterp = new Interpolator(2);
4616            mXY[0] = mCurrStretchX;
4617            mXY[1] = mCurrStretchY;
4618         //   float[] blend = new float[] { 0.5f, 0, 0.75f, 1 };
4619            float[] blend = new float[] { 0, 0.5f, 0.75f, 1 };
4620            mInterp.setKeyFrame(0, now, mXY, blend);
4621            float[] zerozero = new float[] { 0, 0 };
4622            mInterp.setKeyFrame(1, now + DURATION, zerozero, null);
4623            mState = ANIMATING_STATE;
4624
4625            if (DebugFlags.DRAG_TRACKER || DEBUG_DRAG_TRACKER) {
4626                Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, "----- stopDrag, starting animation");
4627            }
4628        }
4629
4630        // Call this after each draw. If it ruturns null, the tracker is done
4631        public boolean isFinished() {
4632            return mState == FINISHED_STATE;
4633        }
4634
4635        private int hiddenHeightOfTitleBar() {
4636            return getTitleHeight() - getVisibleTitleHeight();
4637        }
4638
4639        // need a way to know if 565 or 8888 is the right config for
4640        // capturing the display and giving it to the drag proxy
4641        private Bitmap.Config offscreenBitmapConfig() {
4642            // hard code 565 for now
4643            return Bitmap.Config.RGB_565;
4644        }
4645
4646        /*  If the tracker draws, then this returns true, otherwise it will
4647            return false, and draw nothing.
4648         */
4649        public boolean draw(Canvas canvas) {
4650            if (mCurrStretchX != 0 || mCurrStretchY != 0) {
4651                int sx = getScrollX();
4652                int sy = getScrollY() - hiddenHeightOfTitleBar();
4653                if (mSX != sx || mSY != sy) {
4654                    buildBitmap(sx, sy);
4655                    mSX = sx;
4656                    mSY = sy;
4657                }
4658
4659                if (mState == ANIMATING_STATE) {
4660                    Interpolator.Result result = mInterp.timeToValues(mXY);
4661                    if (result == Interpolator.Result.FREEZE_END) {
4662                        mState = FINISHED_STATE;
4663                        return false;
4664                    } else {
4665                        mProxy.onStretchChange(mXY[0], mXY[1]);
4666                        invalidate();
4667                        // fall through to the draw
4668                    }
4669                }
4670                int count = canvas.save(Canvas.MATRIX_SAVE_FLAG);
4671                canvas.translate(sx, sy);
4672                mProxy.onDraw(canvas);
4673                canvas.restoreToCount(count);
4674                return true;
4675            }
4676            if (DebugFlags.DRAG_TRACKER || DEBUG_DRAG_TRACKER) {
4677                Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, " -- draw false " +
4678                      mCurrStretchX + " " + mCurrStretchY);
4679            }
4680            return false;
4681        }
4682
4683        private void buildBitmap(int sx, int sy) {
4684            int w = getWidth();
4685            int h = getViewHeight();
4686            Bitmap bm = Bitmap.createBitmap(w, h, offscreenBitmapConfig());
4687            Canvas canvas = new Canvas(bm);
4688            canvas.translate(-sx, -sy);
4689            drawContent(canvas);
4690
4691            if (DebugFlags.DRAG_TRACKER || DEBUG_DRAG_TRACKER) {
4692                Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, "--- buildBitmap " + sx +
4693                      " " + sy + " " + w + " " + h);
4694            }
4695            mProxy.onBitmapChange(bm);
4696        }
4697    }
4698
4699    /** @hide */
4700    public static class DragTracker {
4701        public void onStartDrag(float x, float y) {}
4702        public boolean onStretchChange(float sx, float sy) {
4703            // return true to have us inval the view
4704            return false;
4705        }
4706        public void onStopDrag() {}
4707        public void onBitmapChange(Bitmap bm) {}
4708        public void onDraw(Canvas canvas) {}
4709    }
4710
4711    /** @hide */
4712    public DragTracker getDragTracker() {
4713        return mDragTracker;
4714    }
4715
4716    /** @hide */
4717    public void setDragTracker(DragTracker tracker) {
4718        mDragTracker = tracker;
4719    }
4720
4721    private DragTracker mDragTracker;
4722    private DragTrackerHandler mDragTrackerHandler;
4723
4724    private boolean hitFocusedPlugin(int contentX, int contentY) {
4725        if (DebugFlags.WEB_VIEW) {
4726            Log.v(LOGTAG, "nativeFocusIsPlugin()=" + nativeFocusIsPlugin());
4727            Rect r = nativeFocusNodeBounds();
4728            Log.v(LOGTAG, "nativeFocusNodeBounds()=(" + r.left + ", " + r.top
4729                    + ", " + r.right + ", " + r.bottom + ")");
4730        }
4731        return nativeFocusIsPlugin()
4732                && nativeFocusNodeBounds().contains(contentX, contentY);
4733    }
4734
4735    private boolean shouldForwardTouchEvent() {
4736        return mFullScreenHolder != null || (mForwardTouchEvents
4737                && !mSelectingText
4738                && mPreventDefault != PREVENT_DEFAULT_IGNORE);
4739    }
4740
4741    private boolean inFullScreenMode() {
4742        return mFullScreenHolder != null;
4743    }
4744
4745    void onPinchToZoomAnimationStart() {
4746        // cancel the single touch handling
4747        cancelTouch();
4748        onZoomAnimationStart();
4749    }
4750
4751    void onPinchToZoomAnimationEnd(ScaleGestureDetector detector) {
4752        onZoomAnimationEnd();
4753        // start a drag, TOUCH_PINCH_DRAG, can't use TOUCH_INIT_MODE as
4754        // it may trigger the unwanted click, can't use TOUCH_DRAG_MODE
4755        // as it may trigger the unwanted fling.
4756        mTouchMode = TOUCH_PINCH_DRAG;
4757        mConfirmMove = true;
4758        startTouch(detector.getFocusX(), detector.getFocusY(), mLastTouchTime);
4759    }
4760
4761    private void startScrollingLayer(float gestureX, float gestureY) {
4762        if (mTouchMode != TOUCH_DRAG_LAYER_MODE) {
4763            int contentX = viewToContentX((int) gestureX + mScrollX);
4764            int contentY = viewToContentY((int) gestureY + mScrollY);
4765            mScrollingLayer = nativeScrollableLayer(contentX, contentY);
4766            if (mScrollingLayer != 0) {
4767                mTouchMode = TOUCH_DRAG_LAYER_MODE;
4768            }
4769        }
4770    }
4771
4772    // 1/(density * density) used to compute the distance between points.
4773    // Computed in init().
4774    private float DRAG_LAYER_INVERSE_DENSITY_SQUARED;
4775
4776    // The distance between two points reported in onTouchEvent scaled by the
4777    // density of the screen.
4778    private static final int DRAG_LAYER_FINGER_DISTANCE = 20000;
4779
4780    @Override
4781    public boolean onTouchEvent(MotionEvent ev) {
4782        if (mNativeClass == 0 || !isClickable() || !isLongClickable()) {
4783            return false;
4784        }
4785
4786        if (DebugFlags.WEB_VIEW) {
4787            Log.v(LOGTAG, ev + " at " + ev.getEventTime() + " mTouchMode="
4788                    + mTouchMode);
4789        }
4790
4791        int action = ev.getAction();
4792        float x = ev.getX();
4793        float y = ev.getY();
4794        long eventTime = ev.getEventTime();
4795
4796        final ScaleGestureDetector detector =
4797                mZoomManager.getMultiTouchGestureDetector();
4798        boolean skipScaleGesture = false;
4799        // Set to the mid-point of a two-finger gesture used to detect if the
4800        // user has touched a layer.
4801        float gestureX = x;
4802        float gestureY = y;
4803        if (detector == null || !detector.isInProgress()) {
4804            // The gesture for scrolling a layer is two fingers close together.
4805            // FIXME: we may consider giving WebKit an option to handle
4806            // multi-touch events later.
4807            if (ev.getPointerCount() > 1) {
4808                float dx = ev.getX(1) - ev.getX(0);
4809                float dy = ev.getY(1) - ev.getY(0);
4810                float dist = (dx * dx + dy * dy) *
4811                        DRAG_LAYER_INVERSE_DENSITY_SQUARED;
4812                // Use the approximate center to determine if the gesture is in
4813                // a layer.
4814                gestureX = ev.getX(0) + (dx * .5f);
4815                gestureY = ev.getY(0) + (dy * .5f);
4816                // Now use a consistent point for tracking movement.
4817                if (ev.getX(0) < ev.getX(1)) {
4818                    x = ev.getX(0);
4819                    y = ev.getY(0);
4820                } else {
4821                    x = ev.getX(1);
4822                    y = ev.getY(1);
4823                }
4824                action = ev.getActionMasked();
4825                if (dist < DRAG_LAYER_FINGER_DISTANCE) {
4826                    skipScaleGesture = true;
4827                } else if (mTouchMode == TOUCH_DRAG_LAYER_MODE) {
4828                    // Fingers moved too far apart while dragging, the user
4829                    // might be trying to zoom.
4830                    mTouchMode = TOUCH_INIT_MODE;
4831                }
4832            }
4833        }
4834
4835        // FIXME: we may consider to give WebKit an option to handle multi-touch
4836        // events later.
4837        if (mZoomManager.supportsMultiTouchZoom() && ev.getPointerCount() > 1 &&
4838                mTouchMode != TOUCH_DRAG_LAYER_MODE && !skipScaleGesture) {
4839
4840            // if the page disallows zoom, skip multi-pointer action
4841            if (mZoomManager.isZoomScaleFixed()) {
4842                return true;
4843            }
4844
4845            if (!detector.isInProgress() &&
4846                    ev.getActionMasked() != MotionEvent.ACTION_POINTER_DOWN) {
4847                // Insert a fake pointer down event in order to start
4848                // the zoom scale detector.
4849                MotionEvent temp = MotionEvent.obtain(ev);
4850                // Clear the original event and set it to
4851                // ACTION_POINTER_DOWN.
4852                temp.setAction(temp.getAction() &
4853                        ~MotionEvent.ACTION_MASK |
4854                        MotionEvent.ACTION_POINTER_DOWN);
4855                detector.onTouchEvent(temp);
4856            }
4857
4858            detector.onTouchEvent(ev);
4859
4860            if (detector.isInProgress()) {
4861                mLastTouchTime = eventTime;
4862                return true;
4863            }
4864
4865            x = detector.getFocusX();
4866            y = detector.getFocusY();
4867            action = ev.getAction() & MotionEvent.ACTION_MASK;
4868            if (action == MotionEvent.ACTION_POINTER_DOWN) {
4869                cancelTouch();
4870                action = MotionEvent.ACTION_DOWN;
4871            } else if (action == MotionEvent.ACTION_POINTER_UP) {
4872                // set mLastTouchX/Y to the remaining point
4873                mLastTouchX = x;
4874                mLastTouchY = y;
4875            } else if (action == MotionEvent.ACTION_MOVE) {
4876                // negative x or y indicate it is on the edge, skip it.
4877                if (x < 0 || y < 0) {
4878                    return true;
4879                }
4880            }
4881        }
4882
4883        // Due to the touch screen edge effect, a touch closer to the edge
4884        // always snapped to the edge. As getViewWidth() can be different from
4885        // getWidth() due to the scrollbar, adjusting the point to match
4886        // getViewWidth(). Same applied to the height.
4887        x = Math.min(x, getViewWidth() - 1);
4888        y = Math.min(y, getViewHeightWithTitle() - 1);
4889
4890        float fDeltaX = mLastTouchX - x;
4891        float fDeltaY = mLastTouchY - y;
4892        int deltaX = (int) fDeltaX;
4893        int deltaY = (int) fDeltaY;
4894        int contentX = viewToContentX((int) x + mScrollX);
4895        int contentY = viewToContentY((int) y + mScrollY);
4896
4897        switch (action) {
4898            case MotionEvent.ACTION_DOWN: {
4899                mPreventDefault = PREVENT_DEFAULT_NO;
4900                mConfirmMove = false;
4901                if (!mScroller.isFinished()) {
4902                    // stop the current scroll animation, but if this is
4903                    // the start of a fling, allow it to add to the current
4904                    // fling's velocity
4905                    mScroller.abortAnimation();
4906                    mTouchMode = TOUCH_DRAG_START_MODE;
4907                    mConfirmMove = true;
4908                    mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY);
4909                } else if (mPrivateHandler.hasMessages(RELEASE_SINGLE_TAP)) {
4910                    mPrivateHandler.removeMessages(RELEASE_SINGLE_TAP);
4911                    if (getSettings().supportTouchOnly()) {
4912                        removeTouchHighlight(true);
4913                    }
4914                    if (deltaX * deltaX + deltaY * deltaY < mDoubleTapSlopSquare) {
4915                        mTouchMode = TOUCH_DOUBLE_TAP_MODE;
4916                    } else {
4917                        // commit the short press action for the previous tap
4918                        doShortPress();
4919                        mTouchMode = TOUCH_INIT_MODE;
4920                        mDeferTouchProcess = (!inFullScreenMode()
4921                                && mForwardTouchEvents) ? hitFocusedPlugin(
4922                                contentX, contentY) : false;
4923                    }
4924                } else { // the normal case
4925                    mTouchMode = TOUCH_INIT_MODE;
4926                    mDeferTouchProcess = (!inFullScreenMode()
4927                            && mForwardTouchEvents) ? hitFocusedPlugin(
4928                            contentX, contentY) : false;
4929                    mWebViewCore.sendMessage(
4930                            EventHub.UPDATE_FRAME_CACHE_IF_LOADING);
4931                    if (getSettings().supportTouchOnly()) {
4932                        TouchHighlightData data = new TouchHighlightData();
4933                        data.mX = contentX;
4934                        data.mY = contentY;
4935                        data.mSlop = viewToContentDimension(mNavSlop);
4936                        mWebViewCore.sendMessageDelayed(
4937                                EventHub.GET_TOUCH_HIGHLIGHT_RECTS, data,
4938                                ViewConfiguration.getTapTimeout());
4939                        if (DEBUG_TOUCH_HIGHLIGHT) {
4940                            if (getSettings().getNavDump()) {
4941                                mTouchHighlightX = (int) x + mScrollX;
4942                                mTouchHighlightY = (int) y + mScrollY;
4943                                mPrivateHandler.postDelayed(new Runnable() {
4944                                    public void run() {
4945                                        mTouchHighlightX = mTouchHighlightY = 0;
4946                                        invalidate();
4947                                    }
4948                                }, TOUCH_HIGHLIGHT_ELAPSE_TIME);
4949                            }
4950                        }
4951                    }
4952                    if (mLogEvent && eventTime - mLastTouchUpTime < 1000) {
4953                        EventLog.writeEvent(EventLogTags.BROWSER_DOUBLE_TAP_DURATION,
4954                                (eventTime - mLastTouchUpTime), eventTime);
4955                    }
4956                    if (mSelectingText) {
4957                        mDrawSelectionPointer = false;
4958                        mSelectionStarted = nativeStartSelection(contentX, contentY);
4959                        if (DebugFlags.WEB_VIEW) {
4960                            Log.v(LOGTAG, "select=" + contentX + "," + contentY);
4961                        }
4962                        invalidate();
4963                    }
4964                }
4965                // Trigger the link
4966                if (mTouchMode == TOUCH_INIT_MODE
4967                        || mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
4968                    mPrivateHandler.sendEmptyMessageDelayed(
4969                            SWITCH_TO_SHORTPRESS, TAP_TIMEOUT);
4970                    mPrivateHandler.sendEmptyMessageDelayed(
4971                            SWITCH_TO_LONGPRESS, LONG_PRESS_TIMEOUT);
4972                    if (inFullScreenMode() || mDeferTouchProcess) {
4973                        mPreventDefault = PREVENT_DEFAULT_YES;
4974                    } else if (mForwardTouchEvents) {
4975                        mPreventDefault = PREVENT_DEFAULT_MAYBE_YES;
4976                    } else {
4977                        mPreventDefault = PREVENT_DEFAULT_NO;
4978                    }
4979                    // pass the touch events from UI thread to WebCore thread
4980                    if (shouldForwardTouchEvent()) {
4981                        TouchEventData ted = new TouchEventData();
4982                        ted.mAction = action;
4983                        ted.mX = contentX;
4984                        ted.mY = contentY;
4985                        ted.mMetaState = ev.getMetaState();
4986                        ted.mReprocess = mDeferTouchProcess;
4987                        mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
4988                        if (mDeferTouchProcess) {
4989                            // still needs to set them for compute deltaX/Y
4990                            mLastTouchX = x;
4991                            mLastTouchY = y;
4992                            break;
4993                        }
4994                        if (!inFullScreenMode()) {
4995                            mPrivateHandler.removeMessages(PREVENT_DEFAULT_TIMEOUT);
4996                            mPrivateHandler.sendMessageDelayed(mPrivateHandler
4997                                    .obtainMessage(PREVENT_DEFAULT_TIMEOUT,
4998                                            action, 0), TAP_TIMEOUT);
4999                        }
5000                    }
5001                }
5002                startTouch(x, y, eventTime);
5003                break;
5004            }
5005            case MotionEvent.ACTION_MOVE: {
5006                boolean firstMove = false;
5007                if (!mConfirmMove && (deltaX * deltaX + deltaY * deltaY)
5008                        >= mTouchSlopSquare) {
5009                    mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
5010                    mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
5011                    mConfirmMove = true;
5012                    firstMove = true;
5013                    if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
5014                        mTouchMode = TOUCH_INIT_MODE;
5015                    }
5016                    if (getSettings().supportTouchOnly()) {
5017                        removeTouchHighlight(true);
5018                    }
5019                }
5020                // pass the touch events from UI thread to WebCore thread
5021                if (shouldForwardTouchEvent() && mConfirmMove && (firstMove
5022                        || eventTime - mLastSentTouchTime > mCurrentTouchInterval)) {
5023                    TouchEventData ted = new TouchEventData();
5024                    ted.mAction = action;
5025                    ted.mX = contentX;
5026                    ted.mY = contentY;
5027                    ted.mMetaState = ev.getMetaState();
5028                    ted.mReprocess = mDeferTouchProcess;
5029                    mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
5030                    mLastSentTouchTime = eventTime;
5031                    if (mDeferTouchProcess) {
5032                        break;
5033                    }
5034                    if (firstMove && !inFullScreenMode()) {
5035                        mPrivateHandler.sendMessageDelayed(mPrivateHandler
5036                                .obtainMessage(PREVENT_DEFAULT_TIMEOUT,
5037                                        action, 0), TAP_TIMEOUT);
5038                    }
5039                }
5040                if (mTouchMode == TOUCH_DONE_MODE
5041                        || mPreventDefault == PREVENT_DEFAULT_YES) {
5042                    // no dragging during scroll zoom animation, or when prevent
5043                    // default is yes
5044                    break;
5045                }
5046                if (mVelocityTracker == null) {
5047                    Log.e(LOGTAG, "Got null mVelocityTracker when "
5048                            + "mPreventDefault = " + mPreventDefault
5049                            + " mDeferTouchProcess = " + mDeferTouchProcess
5050                            + " mTouchMode = " + mTouchMode);
5051                }
5052                mVelocityTracker.addMovement(ev);
5053                if (mSelectingText && mSelectionStarted) {
5054                    if (DebugFlags.WEB_VIEW) {
5055                        Log.v(LOGTAG, "extend=" + contentX + "," + contentY);
5056                    }
5057                    nativeExtendSelection(contentX, contentY);
5058                    invalidate();
5059                    break;
5060                }
5061
5062                if (mTouchMode != TOUCH_DRAG_MODE &&
5063                        mTouchMode != TOUCH_DRAG_LAYER_MODE) {
5064
5065                    if (!mConfirmMove) {
5066                        break;
5067                    }
5068
5069                    if (mPreventDefault == PREVENT_DEFAULT_MAYBE_YES
5070                            || mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN) {
5071                        // track mLastTouchTime as we may need to do fling at
5072                        // ACTION_UP
5073                        mLastTouchTime = eventTime;
5074                        break;
5075                    }
5076                    // if it starts nearly horizontal or vertical, enforce it
5077                    int ax = Math.abs(deltaX);
5078                    int ay = Math.abs(deltaY);
5079                    if (ax > MAX_SLOPE_FOR_DIAG * ay) {
5080                        mSnapScrollMode = SNAP_X;
5081                        mSnapPositive = deltaX > 0;
5082                    } else if (ay > MAX_SLOPE_FOR_DIAG * ax) {
5083                        mSnapScrollMode = SNAP_Y;
5084                        mSnapPositive = deltaY > 0;
5085                    }
5086
5087                    mTouchMode = TOUCH_DRAG_MODE;
5088                    mLastTouchX = x;
5089                    mLastTouchY = y;
5090                    fDeltaX = 0.0f;
5091                    fDeltaY = 0.0f;
5092                    deltaX = 0;
5093                    deltaY = 0;
5094
5095                    if (skipScaleGesture) {
5096                        startScrollingLayer(gestureX, gestureY);
5097                    }
5098                    startDrag();
5099                }
5100
5101                if (mDragTrackerHandler != null) {
5102                    mDragTrackerHandler.dragTo(x, y);
5103                }
5104
5105                // do pan
5106                if (mTouchMode != TOUCH_DRAG_LAYER_MODE) {
5107                    int newScrollX = pinLocX(mScrollX + deltaX);
5108                    int newDeltaX = newScrollX - mScrollX;
5109                    if (deltaX != newDeltaX) {
5110                        deltaX = newDeltaX;
5111                        fDeltaX = (float) newDeltaX;
5112                    }
5113                    int newScrollY = pinLocY(mScrollY + deltaY);
5114                    int newDeltaY = newScrollY - mScrollY;
5115                    if (deltaY != newDeltaY) {
5116                        deltaY = newDeltaY;
5117                        fDeltaY = (float) newDeltaY;
5118                    }
5119                }
5120                boolean done = false;
5121                boolean keepScrollBarsVisible = false;
5122                if (Math.abs(fDeltaX) < 1.0f && Math.abs(fDeltaY) < 1.0f) {
5123                    mLastTouchX = x;
5124                    mLastTouchY = y;
5125                    keepScrollBarsVisible = done = true;
5126                } else {
5127                    if (mSnapScrollMode == SNAP_X || mSnapScrollMode == SNAP_Y) {
5128                        int ax = Math.abs(deltaX);
5129                        int ay = Math.abs(deltaY);
5130                        if (mSnapScrollMode == SNAP_X) {
5131                            // radical change means getting out of snap mode
5132                            if (ay > MAX_SLOPE_FOR_DIAG * ax
5133                                    && ay > MIN_BREAK_SNAP_CROSS_DISTANCE) {
5134                                mSnapScrollMode = SNAP_NONE;
5135                            }
5136                            // reverse direction means lock in the snap mode
5137                            if (ax > MAX_SLOPE_FOR_DIAG * ay &&
5138                                    (mSnapPositive
5139                                    ? deltaX < -mMinLockSnapReverseDistance
5140                                    : deltaX > mMinLockSnapReverseDistance)) {
5141                                mSnapScrollMode |= SNAP_LOCK;
5142                            }
5143                        } else {
5144                            // radical change means getting out of snap mode
5145                            if (ax > MAX_SLOPE_FOR_DIAG * ay
5146                                    && ax > MIN_BREAK_SNAP_CROSS_DISTANCE) {
5147                                mSnapScrollMode = SNAP_NONE;
5148                            }
5149                            // reverse direction means lock in the snap mode
5150                            if (ay > MAX_SLOPE_FOR_DIAG * ax &&
5151                                    (mSnapPositive
5152                                    ? deltaY < -mMinLockSnapReverseDistance
5153                                    : deltaY > mMinLockSnapReverseDistance)) {
5154                                mSnapScrollMode |= SNAP_LOCK;
5155                            }
5156                        }
5157                    }
5158                    if (mSnapScrollMode != SNAP_NONE) {
5159                        if ((mSnapScrollMode & SNAP_X) == SNAP_X) {
5160                            deltaY = 0;
5161                        } else {
5162                            deltaX = 0;
5163                        }
5164                    }
5165                    if ((deltaX | deltaY) != 0) {
5166                        if (deltaX != 0) {
5167                            mLastTouchX = x;
5168                        }
5169                        if (deltaY != 0) {
5170                            mLastTouchY = y;
5171                        }
5172                        mHeldMotionless = MOTIONLESS_FALSE;
5173                    } else {
5174                        // keep the scrollbar on the screen even there is no
5175                        // scroll
5176                        mLastTouchX = x;
5177                        mLastTouchY = y;
5178                        keepScrollBarsVisible = true;
5179                    }
5180                    mLastTouchTime = eventTime;
5181                    mUserScroll = true;
5182                }
5183
5184                doDrag(deltaX, deltaY);
5185
5186                // Turn off scrollbars when dragging a layer.
5187                if (keepScrollBarsVisible &&
5188                        mTouchMode != TOUCH_DRAG_LAYER_MODE) {
5189                    if (mHeldMotionless != MOTIONLESS_TRUE) {
5190                        mHeldMotionless = MOTIONLESS_TRUE;
5191                        invalidate();
5192                    }
5193                    // keep the scrollbar on the screen even there is no scroll
5194                    awakenScrollBars(ViewConfiguration.getScrollDefaultDelay(),
5195                            false);
5196                    // return false to indicate that we can't pan out of the
5197                    // view space
5198                    return !done;
5199                }
5200                break;
5201            }
5202            case MotionEvent.ACTION_UP: {
5203                if (!isFocused()) requestFocus();
5204                // pass the touch events from UI thread to WebCore thread
5205                if (shouldForwardTouchEvent()) {
5206                    TouchEventData ted = new TouchEventData();
5207                    ted.mAction = action;
5208                    ted.mX = contentX;
5209                    ted.mY = contentY;
5210                    ted.mMetaState = ev.getMetaState();
5211                    ted.mReprocess = mDeferTouchProcess;
5212                    mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
5213                }
5214                mLastTouchUpTime = eventTime;
5215                switch (mTouchMode) {
5216                    case TOUCH_DOUBLE_TAP_MODE: // double tap
5217                        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
5218                        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
5219                        if (inFullScreenMode() || mDeferTouchProcess) {
5220                            TouchEventData ted = new TouchEventData();
5221                            ted.mAction = WebViewCore.ACTION_DOUBLETAP;
5222                            ted.mX = contentX;
5223                            ted.mY = contentY;
5224                            ted.mMetaState = ev.getMetaState();
5225                            ted.mReprocess = mDeferTouchProcess;
5226                            mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
5227                        } else if (mPreventDefault != PREVENT_DEFAULT_YES){
5228                            mZoomManager.handleDoubleTap(mLastTouchX, mLastTouchY);
5229                            mTouchMode = TOUCH_DONE_MODE;
5230                        }
5231                        break;
5232                    case TOUCH_INIT_MODE: // tap
5233                    case TOUCH_SHORTPRESS_START_MODE:
5234                    case TOUCH_SHORTPRESS_MODE:
5235                        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
5236                        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
5237                        if (mConfirmMove) {
5238                            Log.w(LOGTAG, "Miss a drag as we are waiting for" +
5239                                    " WebCore's response for touch down.");
5240                            if (mPreventDefault != PREVENT_DEFAULT_YES
5241                                    && (computeMaxScrollX() > 0
5242                                            || computeMaxScrollY() > 0)) {
5243                                // If the user has performed a very quick touch
5244                                // sequence it is possible that we may get here
5245                                // before WebCore has had a chance to process the events.
5246                                // In this case, any call to preventDefault in the
5247                                // JS touch handler will not have been executed yet.
5248                                // Hence we will see both the UI (now) and WebCore
5249                                // (when context switches) handling the event,
5250                                // regardless of whether the web developer actually
5251                                // doeses preventDefault in their touch handler. This
5252                                // is the nature of our asynchronous touch model.
5253
5254                                // we will not rewrite drag code here, but we
5255                                // will try fling if it applies.
5256                                WebViewCore.reducePriority();
5257                                // to get better performance, pause updating the
5258                                // picture
5259                                WebViewCore.pauseUpdatePicture(mWebViewCore);
5260                                // fall through to TOUCH_DRAG_MODE
5261                            } else {
5262                                // WebKit may consume the touch event and modify
5263                                // DOM. drawContentPicture() will be called with
5264                                // animateSroll as true for better performance.
5265                                // Force redraw in high-quality.
5266                                invalidate();
5267                                break;
5268                            }
5269                        } else {
5270                            if (mSelectingText) {
5271                                // tapping on selection or controls does nothing
5272                                if (!nativeHitSelection(contentX, contentY)) {
5273                                    selectionDone();
5274                                }
5275                                break;
5276                            }
5277                            // only trigger double tap if the WebView is
5278                            // scalable
5279                            if (mTouchMode == TOUCH_INIT_MODE
5280                                    && (canZoomIn() || canZoomOut())) {
5281                                mPrivateHandler.sendEmptyMessageDelayed(
5282                                        RELEASE_SINGLE_TAP, ViewConfiguration
5283                                                .getDoubleTapTimeout());
5284                            } else {
5285                                doShortPress();
5286                            }
5287                            break;
5288                        }
5289                    case TOUCH_DRAG_MODE:
5290                        mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
5291                        mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS);
5292                        // if the user waits a while w/o moving before the
5293                        // up, we don't want to do a fling
5294                        if (eventTime - mLastTouchTime <= MIN_FLING_TIME) {
5295                            if (mVelocityTracker == null) {
5296                                Log.e(LOGTAG, "Got null mVelocityTracker when "
5297                                        + "mPreventDefault = "
5298                                        + mPreventDefault
5299                                        + " mDeferTouchProcess = "
5300                                        + mDeferTouchProcess);
5301                            }
5302                            mVelocityTracker.addMovement(ev);
5303                            // set to MOTIONLESS_IGNORE so that it won't keep
5304                            // removing and sending message in
5305                            // drawCoreAndCursorRing()
5306                            mHeldMotionless = MOTIONLESS_IGNORE;
5307                            doFling();
5308                            break;
5309                        }
5310                        // redraw in high-quality, as we're done dragging
5311                        mHeldMotionless = MOTIONLESS_TRUE;
5312                        invalidate();
5313                        // fall through
5314                    case TOUCH_DRAG_START_MODE:
5315                    case TOUCH_DRAG_LAYER_MODE:
5316                        // TOUCH_DRAG_START_MODE should not happen for the real
5317                        // device as we almost certain will get a MOVE. But this
5318                        // is possible on emulator.
5319                        mLastVelocity = 0;
5320                        WebViewCore.resumePriority();
5321                        WebViewCore.resumeUpdatePicture(mWebViewCore);
5322                        break;
5323                }
5324                stopTouch();
5325                break;
5326            }
5327            case MotionEvent.ACTION_CANCEL: {
5328                if (mTouchMode == TOUCH_DRAG_MODE) {
5329                    invalidate();
5330                }
5331                cancelWebCoreTouchEvent(contentX, contentY, false);
5332                cancelTouch();
5333                break;
5334            }
5335        }
5336        return true;
5337    }
5338
5339    private void cancelWebCoreTouchEvent(int x, int y, boolean removeEvents) {
5340        if (shouldForwardTouchEvent()) {
5341            if (removeEvents) {
5342                mWebViewCore.removeMessages(EventHub.TOUCH_EVENT);
5343            }
5344            TouchEventData ted = new TouchEventData();
5345            ted.mX = x;
5346            ted.mY = y;
5347            ted.mAction = MotionEvent.ACTION_CANCEL;
5348            mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
5349            mPreventDefault = PREVENT_DEFAULT_IGNORE;
5350        }
5351    }
5352
5353    private void startTouch(float x, float y, long eventTime) {
5354        // Remember where the motion event started
5355        mLastTouchX = x;
5356        mLastTouchY = y;
5357        mLastTouchTime = eventTime;
5358        mVelocityTracker = VelocityTracker.obtain();
5359        mSnapScrollMode = SNAP_NONE;
5360        if (mDragTracker != null) {
5361            mDragTrackerHandler = new DragTrackerHandler(x, y, mDragTracker);
5362        }
5363    }
5364
5365    private void startDrag() {
5366        WebViewCore.reducePriority();
5367        // to get better performance, pause updating the picture
5368        WebViewCore.pauseUpdatePicture(mWebViewCore);
5369        if (!mDragFromTextInput) {
5370            nativeHideCursor();
5371        }
5372
5373        if (mHorizontalScrollBarMode != SCROLLBAR_ALWAYSOFF
5374                || mVerticalScrollBarMode != SCROLLBAR_ALWAYSOFF) {
5375            mZoomManager.invokeZoomPicker();
5376        }
5377    }
5378
5379    private void doDrag(int deltaX, int deltaY) {
5380        if ((deltaX | deltaY) != 0) {
5381            if (mTouchMode == TOUCH_DRAG_LAYER_MODE) {
5382                deltaX = viewToContentDimension(deltaX);
5383                deltaY = viewToContentDimension(deltaY);
5384                if (nativeScrollLayer(mScrollingLayer, deltaX, deltaY)) {
5385                    invalidate();
5386                }
5387                return;
5388            }
5389            scrollBy(deltaX, deltaY);
5390        }
5391        mZoomManager.keepZoomPickerVisible();
5392    }
5393
5394    private void stopTouch() {
5395        if (mDragTrackerHandler != null) {
5396            mDragTrackerHandler.stopDrag();
5397        }
5398        // we also use mVelocityTracker == null to tell us that we are
5399        // not "moving around", so we can take the slower/prettier
5400        // mode in the drawing code
5401        if (mVelocityTracker != null) {
5402            mVelocityTracker.recycle();
5403            mVelocityTracker = null;
5404        }
5405    }
5406
5407    private void cancelTouch() {
5408        if (mDragTrackerHandler != null) {
5409            mDragTrackerHandler.stopDrag();
5410        }
5411        // we also use mVelocityTracker == null to tell us that we are
5412        // not "moving around", so we can take the slower/prettier
5413        // mode in the drawing code
5414        if (mVelocityTracker != null) {
5415            mVelocityTracker.recycle();
5416            mVelocityTracker = null;
5417        }
5418        if (mTouchMode == TOUCH_DRAG_MODE ||
5419                mTouchMode == TOUCH_DRAG_LAYER_MODE) {
5420            WebViewCore.resumePriority();
5421            WebViewCore.resumeUpdatePicture(mWebViewCore);
5422        }
5423        mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS);
5424        mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS);
5425        mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS);
5426        mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS);
5427        if (getSettings().supportTouchOnly()) {
5428            removeTouchHighlight(true);
5429        }
5430        mHeldMotionless = MOTIONLESS_TRUE;
5431        mTouchMode = TOUCH_DONE_MODE;
5432        nativeHideCursor();
5433    }
5434
5435    private long mTrackballFirstTime = 0;
5436    private long mTrackballLastTime = 0;
5437    private float mTrackballRemainsX = 0.0f;
5438    private float mTrackballRemainsY = 0.0f;
5439    private int mTrackballXMove = 0;
5440    private int mTrackballYMove = 0;
5441    private boolean mSelectingText = false;
5442    private boolean mSelectionStarted = false;
5443    private boolean mExtendSelection = false;
5444    private boolean mDrawSelectionPointer = false;
5445    private static final int TRACKBALL_KEY_TIMEOUT = 1000;
5446    private static final int TRACKBALL_TIMEOUT = 200;
5447    private static final int TRACKBALL_WAIT = 100;
5448    private static final int TRACKBALL_SCALE = 400;
5449    private static final int TRACKBALL_SCROLL_COUNT = 5;
5450    private static final int TRACKBALL_MOVE_COUNT = 10;
5451    private static final int TRACKBALL_MULTIPLIER = 3;
5452    private static final int SELECT_CURSOR_OFFSET = 16;
5453    private int mSelectX = 0;
5454    private int mSelectY = 0;
5455    private boolean mFocusSizeChanged = false;
5456    private boolean mShiftIsPressed = false;
5457    private boolean mTrackballDown = false;
5458    private long mTrackballUpTime = 0;
5459    private long mLastCursorTime = 0;
5460    private Rect mLastCursorBounds;
5461
5462    // Set by default; BrowserActivity clears to interpret trackball data
5463    // directly for movement. Currently, the framework only passes
5464    // arrow key events, not trackball events, from one child to the next
5465    private boolean mMapTrackballToArrowKeys = true;
5466
5467    public void setMapTrackballToArrowKeys(boolean setMap) {
5468        mMapTrackballToArrowKeys = setMap;
5469    }
5470
5471    void resetTrackballTime() {
5472        mTrackballLastTime = 0;
5473    }
5474
5475    @Override
5476    public boolean onTrackballEvent(MotionEvent ev) {
5477        long time = ev.getEventTime();
5478        if ((ev.getMetaState() & KeyEvent.META_ALT_ON) != 0) {
5479            if (ev.getY() > 0) pageDown(true);
5480            if (ev.getY() < 0) pageUp(true);
5481            return true;
5482        }
5483        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
5484            if (mSelectingText) {
5485                return true; // discard press if copy in progress
5486            }
5487            mTrackballDown = true;
5488            if (mNativeClass == 0) {
5489                return false;
5490            }
5491            nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true);
5492            if (time - mLastCursorTime <= TRACKBALL_TIMEOUT
5493                    && !mLastCursorBounds.equals(nativeGetCursorRingBounds())) {
5494                nativeSelectBestAt(mLastCursorBounds);
5495            }
5496            if (DebugFlags.WEB_VIEW) {
5497                Log.v(LOGTAG, "onTrackballEvent down ev=" + ev
5498                        + " time=" + time
5499                        + " mLastCursorTime=" + mLastCursorTime);
5500            }
5501            if (isInTouchMode()) requestFocusFromTouch();
5502            return false; // let common code in onKeyDown at it
5503        }
5504        if (ev.getAction() == MotionEvent.ACTION_UP) {
5505            // LONG_PRESS_CENTER is set in common onKeyDown
5506            mPrivateHandler.removeMessages(LONG_PRESS_CENTER);
5507            mTrackballDown = false;
5508            mTrackballUpTime = time;
5509            if (mSelectingText) {
5510                if (mExtendSelection) {
5511                    copySelection();
5512                    selectionDone();
5513                } else {
5514                    mExtendSelection = true;
5515                    nativeSetExtendSelection();
5516                    invalidate(); // draw the i-beam instead of the arrow
5517                }
5518                return true; // discard press if copy in progress
5519            }
5520            if (DebugFlags.WEB_VIEW) {
5521                Log.v(LOGTAG, "onTrackballEvent up ev=" + ev
5522                        + " time=" + time
5523                );
5524            }
5525            return false; // let common code in onKeyUp at it
5526        }
5527        if (mMapTrackballToArrowKeys && mShiftIsPressed == false) {
5528            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent gmail quit");
5529            return false;
5530        }
5531        if (mTrackballDown) {
5532            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent down quit");
5533            return true; // discard move if trackball is down
5534        }
5535        if (time - mTrackballUpTime < TRACKBALL_TIMEOUT) {
5536            if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent up timeout quit");
5537            return true;
5538        }
5539        // TODO: alternatively we can do panning as touch does
5540        switchOutDrawHistory();
5541        if (time - mTrackballLastTime > TRACKBALL_TIMEOUT) {
5542            if (DebugFlags.WEB_VIEW) {
5543                Log.v(LOGTAG, "onTrackballEvent time="
5544                        + time + " last=" + mTrackballLastTime);
5545            }
5546            mTrackballFirstTime = time;
5547            mTrackballXMove = mTrackballYMove = 0;
5548        }
5549        mTrackballLastTime = time;
5550        if (DebugFlags.WEB_VIEW) {
5551            Log.v(LOGTAG, "onTrackballEvent ev=" + ev + " time=" + time);
5552        }
5553        mTrackballRemainsX += ev.getX();
5554        mTrackballRemainsY += ev.getY();
5555        doTrackball(time);
5556        return true;
5557    }
5558
5559    void moveSelection(float xRate, float yRate) {
5560        if (mNativeClass == 0)
5561            return;
5562        int width = getViewWidth();
5563        int height = getViewHeight();
5564        mSelectX += xRate;
5565        mSelectY += yRate;
5566        int maxX = width + mScrollX;
5567        int maxY = height + mScrollY;
5568        mSelectX = Math.min(maxX, Math.max(mScrollX - SELECT_CURSOR_OFFSET
5569                , mSelectX));
5570        mSelectY = Math.min(maxY, Math.max(mScrollY - SELECT_CURSOR_OFFSET
5571                , mSelectY));
5572        if (DebugFlags.WEB_VIEW) {
5573            Log.v(LOGTAG, "moveSelection"
5574                    + " mSelectX=" + mSelectX
5575                    + " mSelectY=" + mSelectY
5576                    + " mScrollX=" + mScrollX
5577                    + " mScrollY=" + mScrollY
5578                    + " xRate=" + xRate
5579                    + " yRate=" + yRate
5580                    );
5581        }
5582        nativeMoveSelection(viewToContentX(mSelectX), viewToContentY(mSelectY));
5583        int scrollX = mSelectX < mScrollX ? -SELECT_CURSOR_OFFSET
5584                : mSelectX > maxX - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET
5585                : 0;
5586        int scrollY = mSelectY < mScrollY ? -SELECT_CURSOR_OFFSET
5587                : mSelectY > maxY - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET
5588                : 0;
5589        pinScrollBy(scrollX, scrollY, true, 0);
5590        Rect select = new Rect(mSelectX, mSelectY, mSelectX + 1, mSelectY + 1);
5591        requestRectangleOnScreen(select);
5592        invalidate();
5593   }
5594
5595    private int scaleTrackballX(float xRate, int width) {
5596        int xMove = (int) (xRate / TRACKBALL_SCALE * width);
5597        int nextXMove = xMove;
5598        if (xMove > 0) {
5599            if (xMove > mTrackballXMove) {
5600                xMove -= mTrackballXMove;
5601            }
5602        } else if (xMove < mTrackballXMove) {
5603            xMove -= mTrackballXMove;
5604        }
5605        mTrackballXMove = nextXMove;
5606        return xMove;
5607    }
5608
5609    private int scaleTrackballY(float yRate, int height) {
5610        int yMove = (int) (yRate / TRACKBALL_SCALE * height);
5611        int nextYMove = yMove;
5612        if (yMove > 0) {
5613            if (yMove > mTrackballYMove) {
5614                yMove -= mTrackballYMove;
5615            }
5616        } else if (yMove < mTrackballYMove) {
5617            yMove -= mTrackballYMove;
5618        }
5619        mTrackballYMove = nextYMove;
5620        return yMove;
5621    }
5622
5623    private int keyCodeToSoundsEffect(int keyCode) {
5624        switch(keyCode) {
5625            case KeyEvent.KEYCODE_DPAD_UP:
5626                return SoundEffectConstants.NAVIGATION_UP;
5627            case KeyEvent.KEYCODE_DPAD_RIGHT:
5628                return SoundEffectConstants.NAVIGATION_RIGHT;
5629            case KeyEvent.KEYCODE_DPAD_DOWN:
5630                return SoundEffectConstants.NAVIGATION_DOWN;
5631            case KeyEvent.KEYCODE_DPAD_LEFT:
5632                return SoundEffectConstants.NAVIGATION_LEFT;
5633        }
5634        throw new IllegalArgumentException("keyCode must be one of " +
5635                "{KEYCODE_DPAD_UP, KEYCODE_DPAD_RIGHT, KEYCODE_DPAD_DOWN, " +
5636                "KEYCODE_DPAD_LEFT}.");
5637    }
5638
5639    private void doTrackball(long time) {
5640        int elapsed = (int) (mTrackballLastTime - mTrackballFirstTime);
5641        if (elapsed == 0) {
5642            elapsed = TRACKBALL_TIMEOUT;
5643        }
5644        float xRate = mTrackballRemainsX * 1000 / elapsed;
5645        float yRate = mTrackballRemainsY * 1000 / elapsed;
5646        int viewWidth = getViewWidth();
5647        int viewHeight = getViewHeight();
5648        if (mSelectingText) {
5649            if (!mDrawSelectionPointer) {
5650                // The last selection was made by touch, disabling drawing the
5651                // selection pointer. Allow the trackball to adjust the
5652                // position of the touch control.
5653                mSelectX = contentToViewX(nativeSelectionX());
5654                mSelectY = contentToViewY(nativeSelectionY());
5655                mDrawSelectionPointer = mExtendSelection = true;
5656                nativeSetExtendSelection();
5657            }
5658            moveSelection(scaleTrackballX(xRate, viewWidth),
5659                    scaleTrackballY(yRate, viewHeight));
5660            mTrackballRemainsX = mTrackballRemainsY = 0;
5661            return;
5662        }
5663        float ax = Math.abs(xRate);
5664        float ay = Math.abs(yRate);
5665        float maxA = Math.max(ax, ay);
5666        if (DebugFlags.WEB_VIEW) {
5667            Log.v(LOGTAG, "doTrackball elapsed=" + elapsed
5668                    + " xRate=" + xRate
5669                    + " yRate=" + yRate
5670                    + " mTrackballRemainsX=" + mTrackballRemainsX
5671                    + " mTrackballRemainsY=" + mTrackballRemainsY);
5672        }
5673        int width = mContentWidth - viewWidth;
5674        int height = mContentHeight - viewHeight;
5675        if (width < 0) width = 0;
5676        if (height < 0) height = 0;
5677        ax = Math.abs(mTrackballRemainsX * TRACKBALL_MULTIPLIER);
5678        ay = Math.abs(mTrackballRemainsY * TRACKBALL_MULTIPLIER);
5679        maxA = Math.max(ax, ay);
5680        int count = Math.max(0, (int) maxA);
5681        int oldScrollX = mScrollX;
5682        int oldScrollY = mScrollY;
5683        if (count > 0) {
5684            int selectKeyCode = ax < ay ? mTrackballRemainsY < 0 ?
5685                    KeyEvent.KEYCODE_DPAD_UP : KeyEvent.KEYCODE_DPAD_DOWN :
5686                    mTrackballRemainsX < 0 ? KeyEvent.KEYCODE_DPAD_LEFT :
5687                    KeyEvent.KEYCODE_DPAD_RIGHT;
5688            count = Math.min(count, TRACKBALL_MOVE_COUNT);
5689            if (DebugFlags.WEB_VIEW) {
5690                Log.v(LOGTAG, "doTrackball keyCode=" + selectKeyCode
5691                        + " count=" + count
5692                        + " mTrackballRemainsX=" + mTrackballRemainsX
5693                        + " mTrackballRemainsY=" + mTrackballRemainsY);
5694            }
5695            if (mNativeClass != 0 && nativePageShouldHandleShiftAndArrows()) {
5696                for (int i = 0; i < count; i++) {
5697                    letPageHandleNavKey(selectKeyCode, time, true);
5698                }
5699                letPageHandleNavKey(selectKeyCode, time, false);
5700            } else if (navHandledKey(selectKeyCode, count, false, time)) {
5701                playSoundEffect(keyCodeToSoundsEffect(selectKeyCode));
5702            }
5703            mTrackballRemainsX = mTrackballRemainsY = 0;
5704        }
5705        if (count >= TRACKBALL_SCROLL_COUNT) {
5706            int xMove = scaleTrackballX(xRate, width);
5707            int yMove = scaleTrackballY(yRate, height);
5708            if (DebugFlags.WEB_VIEW) {
5709                Log.v(LOGTAG, "doTrackball pinScrollBy"
5710                        + " count=" + count
5711                        + " xMove=" + xMove + " yMove=" + yMove
5712                        + " mScrollX-oldScrollX=" + (mScrollX-oldScrollX)
5713                        + " mScrollY-oldScrollY=" + (mScrollY-oldScrollY)
5714                        );
5715            }
5716            if (Math.abs(mScrollX - oldScrollX) > Math.abs(xMove)) {
5717                xMove = 0;
5718            }
5719            if (Math.abs(mScrollY - oldScrollY) > Math.abs(yMove)) {
5720                yMove = 0;
5721            }
5722            if (xMove != 0 || yMove != 0) {
5723                pinScrollBy(xMove, yMove, true, 0);
5724            }
5725            mUserScroll = true;
5726        }
5727    }
5728
5729    private int computeMaxScrollX() {
5730        return Math.max(computeHorizontalScrollRange() - getViewWidth(), 0);
5731    }
5732
5733    private int computeMaxScrollY() {
5734        return Math.max(computeVerticalScrollRange() + getTitleHeight()
5735                - getViewHeightWithTitle(), 0);
5736    }
5737
5738    boolean updateScrollCoordinates(int x, int y) {
5739        int oldX = mScrollX;
5740        int oldY = mScrollY;
5741        mScrollX = x;
5742        mScrollY = y;
5743        if (oldX != mScrollX || oldY != mScrollY) {
5744            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
5745            return true;
5746        } else {
5747            return false;
5748        }
5749    }
5750
5751    public void flingScroll(int vx, int vy) {
5752        mScroller.fling(mScrollX, mScrollY, vx, vy, 0, computeMaxScrollX(), 0,
5753                computeMaxScrollY());
5754        invalidate();
5755    }
5756
5757    private void doFling() {
5758        if (mVelocityTracker == null) {
5759            return;
5760        }
5761        int maxX = computeMaxScrollX();
5762        int maxY = computeMaxScrollY();
5763
5764        mVelocityTracker.computeCurrentVelocity(1000, mMaximumFling);
5765        int vx = (int) mVelocityTracker.getXVelocity();
5766        int vy = (int) mVelocityTracker.getYVelocity();
5767
5768        if (mSnapScrollMode != SNAP_NONE) {
5769            if ((mSnapScrollMode & SNAP_X) == SNAP_X) {
5770                vy = 0;
5771            } else {
5772                vx = 0;
5773            }
5774        }
5775        if (true /* EMG release: make our fling more like Maps' */) {
5776            // maps cuts their velocity in half
5777            vx = vx * 3 / 4;
5778            vy = vy * 3 / 4;
5779        }
5780        if ((maxX == 0 && vy == 0) || (maxY == 0 && vx == 0)) {
5781            WebViewCore.resumePriority();
5782            WebViewCore.resumeUpdatePicture(mWebViewCore);
5783            return;
5784        }
5785        float currentVelocity = mScroller.getCurrVelocity();
5786        float velocity = (float) Math.hypot(vx, vy);
5787        if (mLastVelocity > 0 && currentVelocity > 0 && velocity
5788                > mLastVelocity * MINIMUM_VELOCITY_RATIO_FOR_ACCELERATION) {
5789            float deltaR = (float) (Math.abs(Math.atan2(mLastVelY, mLastVelX)
5790                    - Math.atan2(vy, vx)));
5791            final float circle = (float) (Math.PI) * 2.0f;
5792            if (deltaR > circle * 0.9f || deltaR < circle * 0.1f) {
5793                vx += currentVelocity * mLastVelX / mLastVelocity;
5794                vy += currentVelocity * mLastVelY / mLastVelocity;
5795                velocity = (float) Math.hypot(vx, vy);
5796                if (DebugFlags.WEB_VIEW) {
5797                    Log.v(LOGTAG, "doFling vx= " + vx + " vy=" + vy);
5798                }
5799            } else if (DebugFlags.WEB_VIEW) {
5800                Log.v(LOGTAG, "doFling missed " + deltaR / circle);
5801            }
5802        } else if (DebugFlags.WEB_VIEW) {
5803            Log.v(LOGTAG, "doFling start last=" + mLastVelocity
5804                    + " current=" + currentVelocity
5805                    + " vx=" + vx + " vy=" + vy
5806                    + " maxX=" + maxX + " maxY=" + maxY
5807                    + " mScrollX=" + mScrollX + " mScrollY=" + mScrollY);
5808        }
5809        mLastVelX = vx;
5810        mLastVelY = vy;
5811        mLastVelocity = velocity;
5812
5813        mScroller.fling(mScrollX, mScrollY, -vx, -vy, 0, maxX, 0, maxY);
5814        final int time = mScroller.getDuration();
5815        mPrivateHandler.sendEmptyMessageDelayed(RESUME_WEBCORE_PRIORITY, time);
5816        awakenScrollBars(time);
5817        invalidate();
5818    }
5819
5820    /**
5821     * Returns a view containing zoom controls i.e. +/- buttons. The caller is
5822     * in charge of installing this view to the view hierarchy. This view will
5823     * become visible when the user starts scrolling via touch and fade away if
5824     * the user does not interact with it.
5825     * <p/>
5826     * API version 3 introduces a built-in zoom mechanism that is shown
5827     * automatically by the MapView. This is the preferred approach for
5828     * showing the zoom UI.
5829     *
5830     * @deprecated The built-in zoom mechanism is preferred, see
5831     *             {@link WebSettings#setBuiltInZoomControls(boolean)}.
5832     */
5833    @Deprecated
5834    public View getZoomControls() {
5835        if (!getSettings().supportZoom()) {
5836            Log.w(LOGTAG, "This WebView doesn't support zoom.");
5837            return null;
5838        }
5839        return mZoomManager.getExternalZoomPicker();
5840    }
5841
5842    void dismissZoomControl() {
5843        mZoomManager.dismissZoomPicker();
5844    }
5845
5846    float getDefaultZoomScale() {
5847        return mZoomManager.getDefaultScale();
5848    }
5849
5850    /**
5851     * @return TRUE if the WebView can be zoomed in.
5852     */
5853    public boolean canZoomIn() {
5854        return mZoomManager.canZoomIn();
5855    }
5856
5857    /**
5858     * @return TRUE if the WebView can be zoomed out.
5859     */
5860    public boolean canZoomOut() {
5861        return mZoomManager.canZoomOut();
5862    }
5863
5864    /**
5865     * Perform zoom in in the webview
5866     * @return TRUE if zoom in succeeds. FALSE if no zoom changes.
5867     */
5868    public boolean zoomIn() {
5869        return mZoomManager.zoomIn();
5870    }
5871
5872    /**
5873     * Perform zoom out in the webview
5874     * @return TRUE if zoom out succeeds. FALSE if no zoom changes.
5875     */
5876    public boolean zoomOut() {
5877        return mZoomManager.zoomOut();
5878    }
5879
5880    private void updateSelection() {
5881        if (mNativeClass == 0) {
5882            return;
5883        }
5884        // mLastTouchX and mLastTouchY are the point in the current viewport
5885        int contentX = viewToContentX((int) mLastTouchX + mScrollX);
5886        int contentY = viewToContentY((int) mLastTouchY + mScrollY);
5887        Rect rect = new Rect(contentX - mNavSlop, contentY - mNavSlop,
5888                contentX + mNavSlop, contentY + mNavSlop);
5889        nativeSelectBestAt(rect);
5890    }
5891
5892    /**
5893     * Scroll the focused text field/area to match the WebTextView
5894     * @param xPercent New x position of the WebTextView from 0 to 1.
5895     * @param y New y position of the WebTextView in view coordinates
5896     */
5897    /*package*/ void scrollFocusedTextInput(float xPercent, int y) {
5898        if (!inEditingMode() || mWebViewCore == null) {
5899            return;
5900        }
5901        mWebViewCore.sendMessage(EventHub.SCROLL_TEXT_INPUT,
5902                // Since this position is relative to the top of the text input
5903                // field, we do not need to take the title bar's height into
5904                // consideration.
5905                viewToContentDimension(y),
5906                new Float(xPercent));
5907    }
5908
5909    /**
5910     * Set our starting point and time for a drag from the WebTextView.
5911     */
5912    /*package*/ void initiateTextFieldDrag(float x, float y, long eventTime) {
5913        if (!inEditingMode()) {
5914            return;
5915        }
5916        mLastTouchX = x + (float) (mWebTextView.getLeft() - mScrollX);
5917        mLastTouchY = y + (float) (mWebTextView.getTop() - mScrollY);
5918        mLastTouchTime = eventTime;
5919        if (!mScroller.isFinished()) {
5920            abortAnimation();
5921            mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY);
5922        }
5923        mSnapScrollMode = SNAP_NONE;
5924        mVelocityTracker = VelocityTracker.obtain();
5925        mTouchMode = TOUCH_DRAG_START_MODE;
5926    }
5927
5928    /**
5929     * Given a motion event from the WebTextView, set its location to our
5930     * coordinates, and handle the event.
5931     */
5932    /*package*/ boolean textFieldDrag(MotionEvent event) {
5933        if (!inEditingMode()) {
5934            return false;
5935        }
5936        mDragFromTextInput = true;
5937        event.offsetLocation((float) (mWebTextView.getLeft() - mScrollX),
5938                (float) (mWebTextView.getTop() - mScrollY));
5939        boolean result = onTouchEvent(event);
5940        mDragFromTextInput = false;
5941        return result;
5942    }
5943
5944    /**
5945     * Due a touch up from a WebTextView.  This will be handled by webkit to
5946     * change the selection.
5947     * @param event MotionEvent in the WebTextView's coordinates.
5948     */
5949    /*package*/ void touchUpOnTextField(MotionEvent event) {
5950        if (!inEditingMode()) {
5951            return;
5952        }
5953        int x = viewToContentX((int) event.getX() + mWebTextView.getLeft());
5954        int y = viewToContentY((int) event.getY() + mWebTextView.getTop());
5955        nativeMotionUp(x, y, mNavSlop);
5956    }
5957
5958    /**
5959     * Called when pressing the center key or trackball on a textfield.
5960     */
5961    /*package*/ void centerKeyPressOnTextField() {
5962        mWebViewCore.sendMessage(EventHub.CLICK, nativeCursorFramePointer(),
5963                    nativeCursorNodePointer());
5964    }
5965
5966    private void doShortPress() {
5967        if (mNativeClass == 0) {
5968            return;
5969        }
5970        if (mPreventDefault == PREVENT_DEFAULT_YES) {
5971            return;
5972        }
5973        mTouchMode = TOUCH_DONE_MODE;
5974        switchOutDrawHistory();
5975        // mLastTouchX and mLastTouchY are the point in the current viewport
5976        int contentX = viewToContentX((int) mLastTouchX + mScrollX);
5977        int contentY = viewToContentY((int) mLastTouchY + mScrollY);
5978        if (getSettings().supportTouchOnly()) {
5979            removeTouchHighlight(false);
5980            WebViewCore.TouchUpData touchUpData = new WebViewCore.TouchUpData();
5981            // use "0" as generation id to inform WebKit to use the same x/y as
5982            // it used when processing GET_TOUCH_HIGHLIGHT_RECTS
5983            touchUpData.mMoveGeneration = 0;
5984            mWebViewCore.sendMessage(EventHub.TOUCH_UP, touchUpData);
5985        } else if (nativePointInNavCache(contentX, contentY, mNavSlop)) {
5986            WebViewCore.MotionUpData motionUpData = new WebViewCore
5987                    .MotionUpData();
5988            motionUpData.mFrame = nativeCacheHitFramePointer();
5989            motionUpData.mNode = nativeCacheHitNodePointer();
5990            motionUpData.mBounds = nativeCacheHitNodeBounds();
5991            motionUpData.mX = contentX;
5992            motionUpData.mY = contentY;
5993            mWebViewCore.sendMessageAtFrontOfQueue(EventHub.VALID_NODE_BOUNDS,
5994                    motionUpData);
5995        } else {
5996            doMotionUp(contentX, contentY);
5997        }
5998    }
5999
6000    private void doMotionUp(int contentX, int contentY) {
6001        if (mLogEvent && nativeMotionUp(contentX, contentY, mNavSlop)) {
6002            EventLog.writeEvent(EventLogTags.BROWSER_SNAP_CENTER);
6003        }
6004        if (nativeHasCursorNode() && !nativeCursorIsTextInput()) {
6005            playSoundEffect(SoundEffectConstants.CLICK);
6006        }
6007    }
6008
6009    /*
6010     * Return true if the view (Plugin) is fully visible and maximized inside
6011     * the WebView.
6012     */
6013    boolean isPluginFitOnScreen(ViewManager.ChildView view) {
6014        final int viewWidth = getViewWidth();
6015        final int viewHeight = getViewHeightWithTitle();
6016        float scale = Math.min((float) viewWidth / view.width, (float) viewHeight / view.height);
6017        scale = mZoomManager.computeScaleWithLimits(scale);
6018        return !mZoomManager.willScaleTriggerZoom(scale)
6019                && contentToViewX(view.x) >= mScrollX
6020                && contentToViewX(view.x + view.width) <= mScrollX + viewWidth
6021                && contentToViewY(view.y) >= mScrollY
6022                && contentToViewY(view.y + view.height) <= mScrollY + viewHeight;
6023    }
6024
6025    /*
6026     * Maximize and center the rectangle, specified in the document coordinate
6027     * space, inside the WebView. If the zoom doesn't need to be changed, do an
6028     * animated scroll to center it. If the zoom needs to be changed, find the
6029     * zoom center and do a smooth zoom transition.
6030     */
6031    void centerFitRect(int docX, int docY, int docWidth, int docHeight) {
6032        int viewWidth = getViewWidth();
6033        int viewHeight = getViewHeightWithTitle();
6034        float scale = Math.min((float) viewWidth / docWidth, (float) viewHeight
6035                / docHeight);
6036        scale = mZoomManager.computeScaleWithLimits(scale);
6037        if (!mZoomManager.willScaleTriggerZoom(scale)) {
6038            pinScrollTo(contentToViewX(docX + docWidth / 2) - viewWidth / 2,
6039                    contentToViewY(docY + docHeight / 2) - viewHeight / 2,
6040                    true, 0);
6041        } else {
6042            float actualScale = mZoomManager.getScale();
6043            float oldScreenX = docX * actualScale - mScrollX;
6044            float rectViewX = docX * scale;
6045            float rectViewWidth = docWidth * scale;
6046            float newMaxWidth = mContentWidth * scale;
6047            float newScreenX = (viewWidth - rectViewWidth) / 2;
6048            // pin the newX to the WebView
6049            if (newScreenX > rectViewX) {
6050                newScreenX = rectViewX;
6051            } else if (newScreenX > (newMaxWidth - rectViewX - rectViewWidth)) {
6052                newScreenX = viewWidth - (newMaxWidth - rectViewX);
6053            }
6054            float zoomCenterX = (oldScreenX * scale - newScreenX * actualScale)
6055                    / (scale - actualScale);
6056            float oldScreenY = docY * actualScale + getTitleHeight()
6057                    - mScrollY;
6058            float rectViewY = docY * scale + getTitleHeight();
6059            float rectViewHeight = docHeight * scale;
6060            float newMaxHeight = mContentHeight * scale + getTitleHeight();
6061            float newScreenY = (viewHeight - rectViewHeight) / 2;
6062            // pin the newY to the WebView
6063            if (newScreenY > rectViewY) {
6064                newScreenY = rectViewY;
6065            } else if (newScreenY > (newMaxHeight - rectViewY - rectViewHeight)) {
6066                newScreenY = viewHeight - (newMaxHeight - rectViewY);
6067            }
6068            float zoomCenterY = (oldScreenY * scale - newScreenY * actualScale)
6069                    / (scale - actualScale);
6070            mZoomManager.setZoomCenter(zoomCenterX, zoomCenterY);
6071            mZoomManager.startZoomAnimation(scale, false);
6072        }
6073    }
6074
6075    // Called by JNI to handle a touch on a node representing an email address,
6076    // address, or phone number
6077    private void overrideLoading(String url) {
6078        mCallbackProxy.uiOverrideUrlLoading(url);
6079    }
6080
6081    @Override
6082    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
6083        // FIXME: If a subwindow is showing find, and the user touches the
6084        // background window, it can steal focus.
6085        if (mFindIsUp) return false;
6086        boolean result = false;
6087        if (inEditingMode()) {
6088            result = mWebTextView.requestFocus(direction,
6089                    previouslyFocusedRect);
6090        } else {
6091            result = super.requestFocus(direction, previouslyFocusedRect);
6092            if (mWebViewCore.getSettings().getNeedInitialFocus()) {
6093                // For cases such as GMail, where we gain focus from a direction,
6094                // we want to move to the first available link.
6095                // FIXME: If there are no visible links, we may not want to
6096                int fakeKeyDirection = 0;
6097                switch(direction) {
6098                    case View.FOCUS_UP:
6099                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_UP;
6100                        break;
6101                    case View.FOCUS_DOWN:
6102                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_DOWN;
6103                        break;
6104                    case View.FOCUS_LEFT:
6105                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_LEFT;
6106                        break;
6107                    case View.FOCUS_RIGHT:
6108                        fakeKeyDirection = KeyEvent.KEYCODE_DPAD_RIGHT;
6109                        break;
6110                    default:
6111                        return result;
6112                }
6113                if (mNativeClass != 0 && !nativeHasCursorNode()) {
6114                    navHandledKey(fakeKeyDirection, 1, true, 0);
6115                }
6116            }
6117        }
6118        return result;
6119    }
6120
6121    @Override
6122    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
6123        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
6124
6125        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
6126        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
6127        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
6128        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
6129
6130        int measuredHeight = heightSize;
6131        int measuredWidth = widthSize;
6132
6133        // Grab the content size from WebViewCore.
6134        int contentHeight = contentToViewDimension(mContentHeight);
6135        int contentWidth = contentToViewDimension(mContentWidth);
6136
6137//        Log.d(LOGTAG, "------- measure " + heightMode);
6138
6139        if (heightMode != MeasureSpec.EXACTLY) {
6140            mHeightCanMeasure = true;
6141            measuredHeight = contentHeight;
6142            if (heightMode == MeasureSpec.AT_MOST) {
6143                // If we are larger than the AT_MOST height, then our height can
6144                // no longer be measured and we should scroll internally.
6145                if (measuredHeight > heightSize) {
6146                    measuredHeight = heightSize;
6147                    mHeightCanMeasure = false;
6148                }
6149            }
6150        } else {
6151            mHeightCanMeasure = false;
6152        }
6153        if (mNativeClass != 0) {
6154            nativeSetHeightCanMeasure(mHeightCanMeasure);
6155        }
6156        // For the width, always use the given size unless unspecified.
6157        if (widthMode == MeasureSpec.UNSPECIFIED) {
6158            mWidthCanMeasure = true;
6159            measuredWidth = contentWidth;
6160        } else {
6161            mWidthCanMeasure = false;
6162        }
6163
6164        synchronized (this) {
6165            setMeasuredDimension(measuredWidth, measuredHeight);
6166        }
6167    }
6168
6169    @Override
6170    public boolean requestChildRectangleOnScreen(View child,
6171                                                 Rect rect,
6172                                                 boolean immediate) {
6173        // don't scroll while in zoom animation. When it is done, we will adjust
6174        // the necessary components (e.g., WebTextView if it is in editing mode)
6175        if (mZoomManager.isFixedLengthAnimationInProgress()) {
6176            return false;
6177        }
6178
6179        rect.offset(child.getLeft() - child.getScrollX(),
6180                child.getTop() - child.getScrollY());
6181
6182        Rect content = new Rect(viewToContentX(mScrollX),
6183                viewToContentY(mScrollY),
6184                viewToContentX(mScrollX + getWidth()
6185                - getVerticalScrollbarWidth()),
6186                viewToContentY(mScrollY + getViewHeightWithTitle()));
6187        content = nativeSubtractLayers(content);
6188        int screenTop = contentToViewY(content.top);
6189        int screenBottom = contentToViewY(content.bottom);
6190        int height = screenBottom - screenTop;
6191        int scrollYDelta = 0;
6192
6193        if (rect.bottom > screenBottom) {
6194            int oneThirdOfScreenHeight = height / 3;
6195            if (rect.height() > 2 * oneThirdOfScreenHeight) {
6196                // If the rectangle is too tall to fit in the bottom two thirds
6197                // of the screen, place it at the top.
6198                scrollYDelta = rect.top - screenTop;
6199            } else {
6200                // If the rectangle will still fit on screen, we want its
6201                // top to be in the top third of the screen.
6202                scrollYDelta = rect.top - (screenTop + oneThirdOfScreenHeight);
6203            }
6204        } else if (rect.top < screenTop) {
6205            scrollYDelta = rect.top - screenTop;
6206        }
6207
6208        int screenLeft = contentToViewX(content.left);
6209        int screenRight = contentToViewX(content.right);
6210        int width = screenRight - screenLeft;
6211        int scrollXDelta = 0;
6212
6213        if (rect.right > screenRight && rect.left > screenLeft) {
6214            if (rect.width() > width) {
6215                scrollXDelta += (rect.left - screenLeft);
6216            } else {
6217                scrollXDelta += (rect.right - screenRight);
6218            }
6219        } else if (rect.left < screenLeft) {
6220            scrollXDelta -= (screenLeft - rect.left);
6221        }
6222
6223        if ((scrollYDelta | scrollXDelta) != 0) {
6224            return pinScrollBy(scrollXDelta, scrollYDelta, !immediate, 0);
6225        }
6226
6227        return false;
6228    }
6229
6230    /* package */ void replaceTextfieldText(int oldStart, int oldEnd,
6231            String replace, int newStart, int newEnd) {
6232        WebViewCore.ReplaceTextData arg = new WebViewCore.ReplaceTextData();
6233        arg.mReplace = replace;
6234        arg.mNewStart = newStart;
6235        arg.mNewEnd = newEnd;
6236        mTextGeneration++;
6237        arg.mTextGeneration = mTextGeneration;
6238        mWebViewCore.sendMessage(EventHub.REPLACE_TEXT, oldStart, oldEnd, arg);
6239    }
6240
6241    /* package */ void passToJavaScript(String currentText, KeyEvent event) {
6242        WebViewCore.JSKeyData arg = new WebViewCore.JSKeyData();
6243        arg.mEvent = event;
6244        arg.mCurrentText = currentText;
6245        // Increase our text generation number, and pass it to webcore thread
6246        mTextGeneration++;
6247        mWebViewCore.sendMessage(EventHub.PASS_TO_JS, mTextGeneration, 0, arg);
6248        // WebKit's document state is not saved until about to leave the page.
6249        // To make sure the host application, like Browser, has the up to date
6250        // document state when it goes to background, we force to save the
6251        // document state.
6252        mWebViewCore.removeMessages(EventHub.SAVE_DOCUMENT_STATE);
6253        mWebViewCore.sendMessageDelayed(EventHub.SAVE_DOCUMENT_STATE,
6254                cursorData(), 1000);
6255    }
6256
6257    /* package */ synchronized WebViewCore getWebViewCore() {
6258        return mWebViewCore;
6259    }
6260
6261    //-------------------------------------------------------------------------
6262    // Methods can be called from a separate thread, like WebViewCore
6263    // If it needs to call the View system, it has to send message.
6264    //-------------------------------------------------------------------------
6265
6266    /**
6267     * General handler to receive message coming from webkit thread
6268     */
6269    class PrivateHandler extends Handler {
6270        @Override
6271        public void handleMessage(Message msg) {
6272            // exclude INVAL_RECT_MSG_ID since it is frequently output
6273            if (DebugFlags.WEB_VIEW && msg.what != INVAL_RECT_MSG_ID) {
6274                if (msg.what >= FIRST_PRIVATE_MSG_ID
6275                        && msg.what <= LAST_PRIVATE_MSG_ID) {
6276                    Log.v(LOGTAG, HandlerPrivateDebugString[msg.what
6277                            - FIRST_PRIVATE_MSG_ID]);
6278                } else if (msg.what >= FIRST_PACKAGE_MSG_ID
6279                        && msg.what <= LAST_PACKAGE_MSG_ID) {
6280                    Log.v(LOGTAG, HandlerPackageDebugString[msg.what
6281                            - FIRST_PACKAGE_MSG_ID]);
6282                } else {
6283                    Log.v(LOGTAG, Integer.toString(msg.what));
6284                }
6285            }
6286            if (mWebViewCore == null) {
6287                // after WebView's destroy() is called, skip handling messages.
6288                return;
6289            }
6290            switch (msg.what) {
6291                case REMEMBER_PASSWORD: {
6292                    mDatabase.setUsernamePassword(
6293                            msg.getData().getString("host"),
6294                            msg.getData().getString("username"),
6295                            msg.getData().getString("password"));
6296                    ((Message) msg.obj).sendToTarget();
6297                    break;
6298                }
6299                case NEVER_REMEMBER_PASSWORD: {
6300                    mDatabase.setUsernamePassword(
6301                            msg.getData().getString("host"), null, null);
6302                    ((Message) msg.obj).sendToTarget();
6303                    break;
6304                }
6305                case PREVENT_DEFAULT_TIMEOUT: {
6306                    // if timeout happens, cancel it so that it won't block UI
6307                    // to continue handling touch events
6308                    if ((msg.arg1 == MotionEvent.ACTION_DOWN
6309                            && mPreventDefault == PREVENT_DEFAULT_MAYBE_YES)
6310                            || (msg.arg1 == MotionEvent.ACTION_MOVE
6311                            && mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN)) {
6312                        cancelWebCoreTouchEvent(
6313                                viewToContentX((int) mLastTouchX + mScrollX),
6314                                viewToContentY((int) mLastTouchY + mScrollY),
6315                                true);
6316                    }
6317                    break;
6318                }
6319                case SWITCH_TO_SHORTPRESS: {
6320                    if (mTouchMode == TOUCH_INIT_MODE) {
6321                        if (!getSettings().supportTouchOnly()
6322                                && mPreventDefault != PREVENT_DEFAULT_YES) {
6323                            mTouchMode = TOUCH_SHORTPRESS_START_MODE;
6324                            updateSelection();
6325                        } else {
6326                            // set to TOUCH_SHORTPRESS_MODE so that it won't
6327                            // trigger double tap any more
6328                            mTouchMode = TOUCH_SHORTPRESS_MODE;
6329                        }
6330                    } else if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) {
6331                        mTouchMode = TOUCH_DONE_MODE;
6332                    }
6333                    break;
6334                }
6335                case SWITCH_TO_LONGPRESS: {
6336                    if (getSettings().supportTouchOnly()) {
6337                        removeTouchHighlight(false);
6338                    }
6339                    if (inFullScreenMode() || mDeferTouchProcess) {
6340                        TouchEventData ted = new TouchEventData();
6341                        ted.mAction = WebViewCore.ACTION_LONGPRESS;
6342                        ted.mX = viewToContentX((int) mLastTouchX + mScrollX);
6343                        ted.mY = viewToContentY((int) mLastTouchY + mScrollY);
6344                        // metaState for long press is tricky. Should it be the
6345                        // state when the press started or when the press was
6346                        // released? Or some intermediary key state? For
6347                        // simplicity for now, we don't set it.
6348                        ted.mMetaState = 0;
6349                        ted.mReprocess = mDeferTouchProcess;
6350                        mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted);
6351                    } else if (mPreventDefault != PREVENT_DEFAULT_YES) {
6352                        mTouchMode = TOUCH_DONE_MODE;
6353                        performLongClick();
6354                    }
6355                    break;
6356                }
6357                case RELEASE_SINGLE_TAP: {
6358                    doShortPress();
6359                    break;
6360                }
6361                case SCROLL_BY_MSG_ID:
6362                    setContentScrollBy(msg.arg1, msg.arg2, (Boolean) msg.obj);
6363                    break;
6364                case SYNC_SCROLL_TO_MSG_ID:
6365                    if (mUserScroll) {
6366                        // if user has scrolled explicitly, don't sync the
6367                        // scroll position any more
6368                        mUserScroll = false;
6369                        break;
6370                    }
6371                    // fall through
6372                case SCROLL_TO_MSG_ID:
6373                    if (setContentScrollTo(msg.arg1, msg.arg2)) {
6374                        // if we can't scroll to the exact position due to pin,
6375                        // send a message to WebCore to re-scroll when we get a
6376                        // new picture
6377                        mUserScroll = false;
6378                        mWebViewCore.sendMessage(EventHub.SYNC_SCROLL,
6379                                msg.arg1, msg.arg2);
6380                    }
6381                    break;
6382                case SPAWN_SCROLL_TO_MSG_ID:
6383                    spawnContentScrollTo(msg.arg1, msg.arg2);
6384                    break;
6385                case UPDATE_ZOOM_RANGE: {
6386                    WebViewCore.ViewState viewState = (WebViewCore.ViewState) msg.obj;
6387                    // mScrollX contains the new minPrefWidth
6388                    mZoomManager.updateZoomRange(viewState, getViewWidth(), viewState.mScrollX);
6389                    break;
6390                }
6391                case REPLACE_BASE_CONTENT: {
6392                    nativeReplaceBaseContent(msg.arg1);
6393                    break;
6394                }
6395                case NEW_PICTURE_MSG_ID: {
6396                    // called for new content
6397                    final WebViewCore.DrawData draw = (WebViewCore.DrawData) msg.obj;
6398                    nativeSetBaseLayer(draw.mBaseLayer);
6399                    final Point viewSize = draw.mViewPoint;
6400                    WebViewCore.ViewState viewState = draw.mViewState;
6401                    boolean isPictureAfterFirstLayout = viewState != null;
6402                    if (isPictureAfterFirstLayout) {
6403                        // Reset the last sent data here since dealing with new page.
6404                        mLastWidthSent = 0;
6405                        mZoomManager.onFirstLayout(draw);
6406                        if (!mDrawHistory) {
6407                            setContentScrollTo(viewState.mScrollX, viewState.mScrollY);
6408                            // As we are on a new page, remove the WebTextView. This
6409                            // is necessary for page loads driven by webkit, and in
6410                            // particular when the user was on a password field, so
6411                            // the WebTextView was visible.
6412                            clearTextEntry();
6413                        }
6414                    }
6415
6416                    // We update the layout (i.e. request a layout from the
6417                    // view system) if the last view size that we sent to
6418                    // WebCore matches the view size of the picture we just
6419                    // received in the fixed dimension.
6420                    final boolean updateLayout = viewSize.x == mLastWidthSent
6421                            && viewSize.y == mLastHeightSent;
6422                    recordNewContentSize(draw.mWidthHeight.x,
6423                            draw.mWidthHeight.y, updateLayout);
6424                    if (DebugFlags.WEB_VIEW) {
6425                        Rect b = draw.mInvalRegion.getBounds();
6426                        Log.v(LOGTAG, "NEW_PICTURE_MSG_ID {" +
6427                                b.left+","+b.top+","+b.right+","+b.bottom+"}");
6428                    }
6429                    invalidateContentRect(draw.mInvalRegion.getBounds());
6430
6431                    if (mPictureListener != null) {
6432                        mPictureListener.onNewPicture(WebView.this, capturePicture());
6433                    }
6434
6435                    // update the zoom information based on the new picture
6436                    mZoomManager.onNewPicture(draw);
6437
6438                    if (draw.mFocusSizeChanged && inEditingMode()) {
6439                        mFocusSizeChanged = true;
6440                    }
6441                    if (isPictureAfterFirstLayout) {
6442                        mViewManager.postReadyToDrawAll();
6443                    }
6444                    break;
6445                }
6446                case WEBCORE_INITIALIZED_MSG_ID:
6447                    // nativeCreate sets mNativeClass to a non-zero value
6448                    nativeCreate(msg.arg1);
6449                    break;
6450                case UPDATE_TEXTFIELD_TEXT_MSG_ID:
6451                    // Make sure that the textfield is currently focused
6452                    // and representing the same node as the pointer.
6453                    if (inEditingMode() &&
6454                            mWebTextView.isSameTextField(msg.arg1)) {
6455                        if (msg.getData().getBoolean("password")) {
6456                            Spannable text = (Spannable) mWebTextView.getText();
6457                            int start = Selection.getSelectionStart(text);
6458                            int end = Selection.getSelectionEnd(text);
6459                            mWebTextView.setInPassword(true);
6460                            // Restore the selection, which may have been
6461                            // ruined by setInPassword.
6462                            Spannable pword =
6463                                    (Spannable) mWebTextView.getText();
6464                            Selection.setSelection(pword, start, end);
6465                        // If the text entry has created more events, ignore
6466                        // this one.
6467                        } else if (msg.arg2 == mTextGeneration) {
6468                            mWebTextView.setTextAndKeepSelection(
6469                                    (String) msg.obj);
6470                        }
6471                    }
6472                    break;
6473                case REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID:
6474                    displaySoftKeyboard(true);
6475                    // fall through to UPDATE_TEXT_SELECTION_MSG_ID
6476                case UPDATE_TEXT_SELECTION_MSG_ID:
6477                    updateTextSelectionFromMessage(msg.arg1, msg.arg2,
6478                            (WebViewCore.TextSelectionData) msg.obj);
6479                    break;
6480                case RETURN_LABEL:
6481                    if (inEditingMode()
6482                            && mWebTextView.isSameTextField(msg.arg1)) {
6483                        mWebTextView.setHint((String) msg.obj);
6484                        InputMethodManager imm
6485                                = InputMethodManager.peekInstance();
6486                        // The hint is propagated to the IME in
6487                        // onCreateInputConnection.  If the IME is already
6488                        // active, restart it so that its hint text is updated.
6489                        if (imm != null && imm.isActive(mWebTextView)) {
6490                            imm.restartInput(mWebTextView);
6491                        }
6492                    }
6493                    break;
6494                case UNHANDLED_NAV_KEY:
6495                    navHandledKey(msg.arg1, 1, false, 0);
6496                    break;
6497                case UPDATE_TEXT_ENTRY_MSG_ID:
6498                    // this is sent after finishing resize in WebViewCore. Make
6499                    // sure the text edit box is still on the  screen.
6500                    if (inEditingMode() && nativeCursorIsTextInput()) {
6501                        mWebTextView.bringIntoView();
6502                        rebuildWebTextView();
6503                    }
6504                    break;
6505                case CLEAR_TEXT_ENTRY:
6506                    clearTextEntry();
6507                    break;
6508                case INVAL_RECT_MSG_ID: {
6509                    Rect r = (Rect)msg.obj;
6510                    if (r == null) {
6511                        invalidate();
6512                    } else {
6513                        // we need to scale r from content into view coords,
6514                        // which viewInvalidate() does for us
6515                        viewInvalidate(r.left, r.top, r.right, r.bottom);
6516                    }
6517                    break;
6518                }
6519                case REQUEST_FORM_DATA:
6520                    AutoCompleteAdapter adapter = (AutoCompleteAdapter) msg.obj;
6521                    if (mWebTextView.isSameTextField(msg.arg1)) {
6522                        mWebTextView.setAdapterCustom(adapter);
6523                    }
6524                    break;
6525                case RESUME_WEBCORE_PRIORITY:
6526                    WebViewCore.resumePriority();
6527                    WebViewCore.resumeUpdatePicture(mWebViewCore);
6528                    break;
6529
6530                case LONG_PRESS_CENTER:
6531                    // as this is shared by keydown and trackballdown, reset all
6532                    // the states
6533                    mGotCenterDown = false;
6534                    mTrackballDown = false;
6535                    performLongClick();
6536                    break;
6537
6538                case WEBCORE_NEED_TOUCH_EVENTS:
6539                    mForwardTouchEvents = (msg.arg1 != 0);
6540                    break;
6541
6542                case PREVENT_TOUCH_ID:
6543                    if (inFullScreenMode()) {
6544                        break;
6545                    }
6546                    if (msg.obj == null) {
6547                        if (msg.arg1 == MotionEvent.ACTION_DOWN
6548                                && mPreventDefault == PREVENT_DEFAULT_MAYBE_YES) {
6549                            // if prevent default is called from WebCore, UI
6550                            // will not handle the rest of the touch events any
6551                            // more.
6552                            mPreventDefault = msg.arg2 == 1 ? PREVENT_DEFAULT_YES
6553                                    : PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN;
6554                        } else if (msg.arg1 == MotionEvent.ACTION_MOVE
6555                                && mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN) {
6556                            // the return for the first ACTION_MOVE will decide
6557                            // whether UI will handle touch or not. Currently no
6558                            // support for alternating prevent default
6559                            mPreventDefault = msg.arg2 == 1 ? PREVENT_DEFAULT_YES
6560                                    : PREVENT_DEFAULT_NO;
6561                        }
6562                        if (mPreventDefault == PREVENT_DEFAULT_YES) {
6563                            mTouchHighlightRegion.setEmpty();
6564                        }
6565                    } else if (msg.arg2 == 0) {
6566                        // prevent default is not called in WebCore, so the
6567                        // message needs to be reprocessed in UI
6568                        TouchEventData ted = (TouchEventData) msg.obj;
6569                        switch (ted.mAction) {
6570                            case MotionEvent.ACTION_DOWN:
6571                                mLastDeferTouchX = contentToViewX(ted.mX)
6572                                        - mScrollX;
6573                                mLastDeferTouchY = contentToViewY(ted.mY)
6574                                        - mScrollY;
6575                                mDeferTouchMode = TOUCH_INIT_MODE;
6576                                break;
6577                            case MotionEvent.ACTION_MOVE: {
6578                                // no snapping in defer process
6579                                int x = contentToViewX(ted.mX) - mScrollX;
6580                                int y = contentToViewY(ted.mY) - mScrollY;
6581                                if (mDeferTouchMode != TOUCH_DRAG_MODE) {
6582                                    mDeferTouchMode = TOUCH_DRAG_MODE;
6583                                    mLastDeferTouchX = x;
6584                                    mLastDeferTouchY = y;
6585                                    startDrag();
6586                                }
6587                                int deltaX = pinLocX((int) (mScrollX
6588                                        + mLastDeferTouchX - x))
6589                                        - mScrollX;
6590                                int deltaY = pinLocY((int) (mScrollY
6591                                        + mLastDeferTouchY - y))
6592                                        - mScrollY;
6593                                doDrag(deltaX, deltaY);
6594                                if (deltaX != 0) mLastDeferTouchX = x;
6595                                if (deltaY != 0) mLastDeferTouchY = y;
6596                                break;
6597                            }
6598                            case MotionEvent.ACTION_UP:
6599                            case MotionEvent.ACTION_CANCEL:
6600                                if (mDeferTouchMode == TOUCH_DRAG_MODE) {
6601                                    // no fling in defer process
6602                                    WebViewCore.resumePriority();
6603                                    WebViewCore.resumeUpdatePicture(mWebViewCore);
6604                                }
6605                                mDeferTouchMode = TOUCH_DONE_MODE;
6606                                break;
6607                            case WebViewCore.ACTION_DOUBLETAP:
6608                                // doDoubleTap() needs mLastTouchX/Y as anchor
6609                                mLastTouchX = contentToViewX(ted.mX) - mScrollX;
6610                                mLastTouchY = contentToViewY(ted.mY) - mScrollY;
6611                                mZoomManager.handleDoubleTap(mLastTouchX, mLastTouchY);
6612                                mDeferTouchMode = TOUCH_DONE_MODE;
6613                                break;
6614                            case WebViewCore.ACTION_LONGPRESS:
6615                                HitTestResult hitTest = getHitTestResult();
6616                                if (hitTest != null && hitTest.mType
6617                                        != HitTestResult.UNKNOWN_TYPE) {
6618                                    performLongClick();
6619                                }
6620                                mDeferTouchMode = TOUCH_DONE_MODE;
6621                                break;
6622                        }
6623                    }
6624                    break;
6625
6626                case REQUEST_KEYBOARD:
6627                    if (msg.arg1 == 0) {
6628                        hideSoftKeyboard();
6629                    } else {
6630                        displaySoftKeyboard(false);
6631                    }
6632                    break;
6633
6634                case FIND_AGAIN:
6635                    // Ignore if find has been dismissed.
6636                    if (mFindIsUp && mFindCallback != null) {
6637                        mFindCallback.findAll();
6638                    }
6639                    break;
6640
6641                case DRAG_HELD_MOTIONLESS:
6642                    mHeldMotionless = MOTIONLESS_TRUE;
6643                    invalidate();
6644                    // fall through to keep scrollbars awake
6645
6646                case AWAKEN_SCROLL_BARS:
6647                    if (mTouchMode == TOUCH_DRAG_MODE
6648                            && mHeldMotionless == MOTIONLESS_TRUE) {
6649                        awakenScrollBars(ViewConfiguration
6650                                .getScrollDefaultDelay(), false);
6651                        mPrivateHandler.sendMessageDelayed(mPrivateHandler
6652                                .obtainMessage(AWAKEN_SCROLL_BARS),
6653                                ViewConfiguration.getScrollDefaultDelay());
6654                    }
6655                    break;
6656
6657                case DO_MOTION_UP:
6658                    doMotionUp(msg.arg1, msg.arg2);
6659                    break;
6660
6661                case SHOW_FULLSCREEN: {
6662                    View view = (View) msg.obj;
6663                    int npp = msg.arg1;
6664
6665                    if (mFullScreenHolder != null) {
6666                        Log.w(LOGTAG, "Should not have another full screen.");
6667                        mFullScreenHolder.dismiss();
6668                    }
6669                    mFullScreenHolder = new PluginFullScreenHolder(WebView.this, npp);
6670                    mFullScreenHolder.setContentView(view);
6671                    mFullScreenHolder.setCancelable(false);
6672                    mFullScreenHolder.setCanceledOnTouchOutside(false);
6673                    mFullScreenHolder.show();
6674
6675                    break;
6676                }
6677                case HIDE_FULLSCREEN:
6678                    if (inFullScreenMode()) {
6679                        mFullScreenHolder.dismiss();
6680                        mFullScreenHolder = null;
6681                    }
6682                    break;
6683
6684                case DOM_FOCUS_CHANGED:
6685                    if (inEditingMode()) {
6686                        nativeClearCursor();
6687                        rebuildWebTextView();
6688                    }
6689                    break;
6690
6691                case SHOW_RECT_MSG_ID: {
6692                    WebViewCore.ShowRectData data = (WebViewCore.ShowRectData) msg.obj;
6693                    int x = mScrollX;
6694                    int left = contentToViewX(data.mLeft);
6695                    int width = contentToViewDimension(data.mWidth);
6696                    int maxWidth = contentToViewDimension(data.mContentWidth);
6697                    int viewWidth = getViewWidth();
6698                    if (width < viewWidth) {
6699                        // center align
6700                        x += left + width / 2 - mScrollX - viewWidth / 2;
6701                    } else {
6702                        x += (int) (left + data.mXPercentInDoc * width
6703                                - mScrollX - data.mXPercentInView * viewWidth);
6704                    }
6705                    if (DebugFlags.WEB_VIEW) {
6706                        Log.v(LOGTAG, "showRectMsg=(left=" + left + ",width=" +
6707                              width + ",maxWidth=" + maxWidth +
6708                              ",viewWidth=" + viewWidth + ",x="
6709                              + x + ",xPercentInDoc=" + data.mXPercentInDoc +
6710                              ",xPercentInView=" + data.mXPercentInView+ ")");
6711                    }
6712                    // use the passing content width to cap x as the current
6713                    // mContentWidth may not be updated yet
6714                    x = Math.max(0,
6715                            (Math.min(maxWidth, x + viewWidth)) - viewWidth);
6716                    int top = contentToViewY(data.mTop);
6717                    int height = contentToViewDimension(data.mHeight);
6718                    int maxHeight = contentToViewDimension(data.mContentHeight);
6719                    int viewHeight = getViewHeight();
6720                    int y = (int) (top + data.mYPercentInDoc * height -
6721                                   data.mYPercentInView * viewHeight);
6722                    if (DebugFlags.WEB_VIEW) {
6723                        Log.v(LOGTAG, "showRectMsg=(top=" + top + ",height=" +
6724                              height + ",maxHeight=" + maxHeight +
6725                              ",viewHeight=" + viewHeight + ",y="
6726                              + y + ",yPercentInDoc=" + data.mYPercentInDoc +
6727                              ",yPercentInView=" + data.mYPercentInView+ ")");
6728                    }
6729                    // use the passing content height to cap y as the current
6730                    // mContentHeight may not be updated yet
6731                    y = Math.max(0,
6732                            (Math.min(maxHeight, y + viewHeight) - viewHeight));
6733                    // We need to take into account the visible title height
6734                    // when scrolling since y is an absolute view position.
6735                    y = Math.max(0, y - getVisibleTitleHeight());
6736                    scrollTo(x, y);
6737                    }
6738                    break;
6739
6740                case CENTER_FIT_RECT:
6741                    Rect r = (Rect)msg.obj;
6742                    centerFitRect(r.left, r.top, r.width(), r.height());
6743                    break;
6744
6745                case SET_SCROLLBAR_MODES:
6746                    mHorizontalScrollBarMode = msg.arg1;
6747                    mVerticalScrollBarMode = msg.arg2;
6748                    break;
6749
6750                case SELECTION_STRING_CHANGED:
6751                    if (mAccessibilityInjector != null) {
6752                        String selectionString = (String) msg.obj;
6753                        mAccessibilityInjector.onSelectionStringChange(selectionString);
6754                    }
6755                    break;
6756
6757                case SET_TOUCH_HIGHLIGHT_RECTS:
6758                    invalidate(mTouchHighlightRegion.getBounds());
6759                    mTouchHighlightRegion.setEmpty();
6760                    if (msg.obj != null) {
6761                        ArrayList<Rect> rects = (ArrayList<Rect>) msg.obj;
6762                        for (Rect rect : rects) {
6763                            Rect viewRect = contentToViewRect(rect);
6764                            // some sites, like stories in nytimes.com, set
6765                            // mouse event handler in the top div. It is not
6766                            // user friendly to highlight the div if it covers
6767                            // more than half of the screen.
6768                            if (viewRect.width() < getWidth() >> 1
6769                                    || viewRect.height() < getHeight() >> 1) {
6770                                mTouchHighlightRegion.union(viewRect);
6771                                invalidate(viewRect);
6772                            } else {
6773                                Log.w(LOGTAG, "Skip the huge selection rect:"
6774                                        + viewRect);
6775                            }
6776                        }
6777                    }
6778                    break;
6779
6780                case SAVE_WEBARCHIVE_FINISHED:
6781                    SaveWebArchiveMessage saveMessage = (SaveWebArchiveMessage)msg.obj;
6782                    if (saveMessage.mCallback != null) {
6783                        saveMessage.mCallback.onReceiveValue(saveMessage.mResultFile);
6784                    }
6785                    break;
6786
6787                default:
6788                    super.handleMessage(msg);
6789                    break;
6790            }
6791        }
6792    }
6793
6794    /**
6795     * Used when receiving messages for REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID
6796     * and UPDATE_TEXT_SELECTION_MSG_ID.  Update the selection of WebTextView.
6797     */
6798    private void updateTextSelectionFromMessage(int nodePointer,
6799            int textGeneration, WebViewCore.TextSelectionData data) {
6800        if (inEditingMode()
6801                && mWebTextView.isSameTextField(nodePointer)
6802                && textGeneration == mTextGeneration) {
6803            mWebTextView.setSelectionFromWebKit(data.mStart, data.mEnd);
6804        }
6805    }
6806
6807    // Class used to use a dropdown for a <select> element
6808    private class InvokeListBox implements Runnable {
6809        // Whether the listbox allows multiple selection.
6810        private boolean     mMultiple;
6811        // Passed in to a list with multiple selection to tell
6812        // which items are selected.
6813        private int[]       mSelectedArray;
6814        // Passed in to a list with single selection to tell
6815        // where the initial selection is.
6816        private int         mSelection;
6817
6818        private Container[] mContainers;
6819
6820        // Need these to provide stable ids to my ArrayAdapter,
6821        // which normally does not have stable ids. (Bug 1250098)
6822        private class Container extends Object {
6823            /**
6824             * Possible values for mEnabled.  Keep in sync with OptionStatus in
6825             * WebViewCore.cpp
6826             */
6827            final static int OPTGROUP = -1;
6828            final static int OPTION_DISABLED = 0;
6829            final static int OPTION_ENABLED = 1;
6830
6831            String  mString;
6832            int     mEnabled;
6833            int     mId;
6834
6835            public String toString() {
6836                return mString;
6837            }
6838        }
6839
6840        /**
6841         *  Subclass ArrayAdapter so we can disable OptionGroupLabels,
6842         *  and allow filtering.
6843         */
6844        private class MyArrayListAdapter extends ArrayAdapter<Container> {
6845            public MyArrayListAdapter(Context context, Container[] objects, boolean multiple) {
6846                super(context,
6847                            multiple ? com.android.internal.R.layout.select_dialog_multichoice :
6848                            com.android.internal.R.layout.select_dialog_singlechoice,
6849                            objects);
6850            }
6851
6852            @Override
6853            public View getView(int position, View convertView,
6854                    ViewGroup parent) {
6855                // Always pass in null so that we will get a new CheckedTextView
6856                // Otherwise, an item which was previously used as an <optgroup>
6857                // element (i.e. has no check), could get used as an <option>
6858                // element, which needs a checkbox/radio, but it would not have
6859                // one.
6860                convertView = super.getView(position, null, parent);
6861                Container c = item(position);
6862                if (c != null && Container.OPTION_ENABLED != c.mEnabled) {
6863                    // ListView does not draw dividers between disabled and
6864                    // enabled elements.  Use a LinearLayout to provide dividers
6865                    LinearLayout layout = new LinearLayout(mContext);
6866                    layout.setOrientation(LinearLayout.VERTICAL);
6867                    if (position > 0) {
6868                        View dividerTop = new View(mContext);
6869                        dividerTop.setBackgroundResource(
6870                                android.R.drawable.divider_horizontal_bright);
6871                        layout.addView(dividerTop);
6872                    }
6873
6874                    if (Container.OPTGROUP == c.mEnabled) {
6875                        // Currently select_dialog_multichoice and
6876                        // select_dialog_singlechoice are CheckedTextViews.  If
6877                        // that changes, the class cast will no longer be valid.
6878                        Assert.assertTrue(
6879                                convertView instanceof CheckedTextView);
6880                        ((CheckedTextView) convertView).setCheckMarkDrawable(
6881                                null);
6882                    } else {
6883                        // c.mEnabled == Container.OPTION_DISABLED
6884                        // Draw the disabled element in a disabled state.
6885                        convertView.setEnabled(false);
6886                    }
6887
6888                    layout.addView(convertView);
6889                    if (position < getCount() - 1) {
6890                        View dividerBottom = new View(mContext);
6891                        dividerBottom.setBackgroundResource(
6892                                android.R.drawable.divider_horizontal_bright);
6893                        layout.addView(dividerBottom);
6894                    }
6895                    return layout;
6896                }
6897                return convertView;
6898            }
6899
6900            @Override
6901            public boolean hasStableIds() {
6902                // AdapterView's onChanged method uses this to determine whether
6903                // to restore the old state.  Return false so that the old (out
6904                // of date) state does not replace the new, valid state.
6905                return false;
6906            }
6907
6908            private Container item(int position) {
6909                if (position < 0 || position >= getCount()) {
6910                    return null;
6911                }
6912                return (Container) getItem(position);
6913            }
6914
6915            @Override
6916            public long getItemId(int position) {
6917                Container item = item(position);
6918                if (item == null) {
6919                    return -1;
6920                }
6921                return item.mId;
6922            }
6923
6924            @Override
6925            public boolean areAllItemsEnabled() {
6926                return false;
6927            }
6928
6929            @Override
6930            public boolean isEnabled(int position) {
6931                Container item = item(position);
6932                if (item == null) {
6933                    return false;
6934                }
6935                return Container.OPTION_ENABLED == item.mEnabled;
6936            }
6937        }
6938
6939        private InvokeListBox(String[] array, int[] enabled, int[] selected) {
6940            mMultiple = true;
6941            mSelectedArray = selected;
6942
6943            int length = array.length;
6944            mContainers = new Container[length];
6945            for (int i = 0; i < length; i++) {
6946                mContainers[i] = new Container();
6947                mContainers[i].mString = array[i];
6948                mContainers[i].mEnabled = enabled[i];
6949                mContainers[i].mId = i;
6950            }
6951        }
6952
6953        private InvokeListBox(String[] array, int[] enabled, int selection) {
6954            mSelection = selection;
6955            mMultiple = false;
6956
6957            int length = array.length;
6958            mContainers = new Container[length];
6959            for (int i = 0; i < length; i++) {
6960                mContainers[i] = new Container();
6961                mContainers[i].mString = array[i];
6962                mContainers[i].mEnabled = enabled[i];
6963                mContainers[i].mId = i;
6964            }
6965        }
6966
6967        /*
6968         * Whenever the data set changes due to filtering, this class ensures
6969         * that the checked item remains checked.
6970         */
6971        private class SingleDataSetObserver extends DataSetObserver {
6972            private long        mCheckedId;
6973            private ListView    mListView;
6974            private Adapter     mAdapter;
6975
6976            /*
6977             * Create a new observer.
6978             * @param id The ID of the item to keep checked.
6979             * @param l ListView for getting and clearing the checked states
6980             * @param a Adapter for getting the IDs
6981             */
6982            public SingleDataSetObserver(long id, ListView l, Adapter a) {
6983                mCheckedId = id;
6984                mListView = l;
6985                mAdapter = a;
6986            }
6987
6988            public void onChanged() {
6989                // The filter may have changed which item is checked.  Find the
6990                // item that the ListView thinks is checked.
6991                int position = mListView.getCheckedItemPosition();
6992                long id = mAdapter.getItemId(position);
6993                if (mCheckedId != id) {
6994                    // Clear the ListView's idea of the checked item, since
6995                    // it is incorrect
6996                    mListView.clearChoices();
6997                    // Search for mCheckedId.  If it is in the filtered list,
6998                    // mark it as checked
6999                    int count = mAdapter.getCount();
7000                    for (int i = 0; i < count; i++) {
7001                        if (mAdapter.getItemId(i) == mCheckedId) {
7002                            mListView.setItemChecked(i, true);
7003                            break;
7004                        }
7005                    }
7006                }
7007            }
7008
7009            public void onInvalidate() {}
7010        }
7011
7012        public void run() {
7013            final ListView listView = (ListView) LayoutInflater.from(mContext)
7014                    .inflate(com.android.internal.R.layout.select_dialog, null);
7015            final MyArrayListAdapter adapter = new
7016                    MyArrayListAdapter(mContext, mContainers, mMultiple);
7017            AlertDialog.Builder b = new AlertDialog.Builder(mContext)
7018                    .setView(listView).setCancelable(true)
7019                    .setInverseBackgroundForced(true);
7020
7021            if (mMultiple) {
7022                b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
7023                    public void onClick(DialogInterface dialog, int which) {
7024                        mWebViewCore.sendMessage(
7025                                EventHub.LISTBOX_CHOICES,
7026                                adapter.getCount(), 0,
7027                                listView.getCheckedItemPositions());
7028                    }});
7029                b.setNegativeButton(android.R.string.cancel,
7030                        new DialogInterface.OnClickListener() {
7031                    public void onClick(DialogInterface dialog, int which) {
7032                        mWebViewCore.sendMessage(
7033                                EventHub.SINGLE_LISTBOX_CHOICE, -2, 0);
7034                }});
7035            }
7036            final AlertDialog dialog = b.create();
7037            listView.setAdapter(adapter);
7038            listView.setFocusableInTouchMode(true);
7039            // There is a bug (1250103) where the checks in a ListView with
7040            // multiple items selected are associated with the positions, not
7041            // the ids, so the items do not properly retain their checks when
7042            // filtered.  Do not allow filtering on multiple lists until
7043            // that bug is fixed.
7044
7045            listView.setTextFilterEnabled(!mMultiple);
7046            if (mMultiple) {
7047                listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
7048                int length = mSelectedArray.length;
7049                for (int i = 0; i < length; i++) {
7050                    listView.setItemChecked(mSelectedArray[i], true);
7051                }
7052            } else {
7053                listView.setOnItemClickListener(new OnItemClickListener() {
7054                    public void onItemClick(AdapterView parent, View v,
7055                            int position, long id) {
7056                        mWebViewCore.sendMessage(
7057                                EventHub.SINGLE_LISTBOX_CHOICE, (int)id, 0);
7058                        dialog.dismiss();
7059                    }
7060                });
7061                if (mSelection != -1) {
7062                    listView.setSelection(mSelection);
7063                    listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
7064                    listView.setItemChecked(mSelection, true);
7065                    DataSetObserver observer = new SingleDataSetObserver(
7066                            adapter.getItemId(mSelection), listView, adapter);
7067                    adapter.registerDataSetObserver(observer);
7068                }
7069            }
7070            dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
7071                public void onCancel(DialogInterface dialog) {
7072                    mWebViewCore.sendMessage(
7073                                EventHub.SINGLE_LISTBOX_CHOICE, -2, 0);
7074                }
7075            });
7076            dialog.show();
7077        }
7078    }
7079
7080    /*
7081     * Request a dropdown menu for a listbox with multiple selection.
7082     *
7083     * @param array Labels for the listbox.
7084     * @param enabledArray  State for each element in the list.  See static
7085     *      integers in Container class.
7086     * @param selectedArray Which positions are initally selected.
7087     */
7088    void requestListBox(String[] array, int[] enabledArray, int[]
7089            selectedArray) {
7090        mPrivateHandler.post(
7091                new InvokeListBox(array, enabledArray, selectedArray));
7092    }
7093
7094    /*
7095     * Request a dropdown menu for a listbox with single selection or a single
7096     * <select> element.
7097     *
7098     * @param array Labels for the listbox.
7099     * @param enabledArray  State for each element in the list.  See static
7100     *      integers in Container class.
7101     * @param selection Which position is initally selected.
7102     */
7103    void requestListBox(String[] array, int[] enabledArray, int selection) {
7104        mPrivateHandler.post(
7105                new InvokeListBox(array, enabledArray, selection));
7106    }
7107
7108    // called by JNI
7109    private void sendMoveFocus(int frame, int node) {
7110        mWebViewCore.sendMessage(EventHub.SET_MOVE_FOCUS,
7111                new WebViewCore.CursorData(frame, node, 0, 0));
7112    }
7113
7114    // called by JNI
7115    private void sendMoveMouse(int frame, int node, int x, int y) {
7116        mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE,
7117                new WebViewCore.CursorData(frame, node, x, y));
7118    }
7119
7120    /*
7121     * Send a mouse move event to the webcore thread.
7122     *
7123     * @param removeFocus Pass true if the "mouse" cursor is now over a node
7124     *                    which wants key events, but it is not the focus. This
7125     *                    will make the visual appear as though nothing is in
7126     *                    focus.  Remove the WebTextView, if present, and stop
7127     *                    drawing the blinking caret.
7128     * called by JNI
7129     */
7130    private void sendMoveMouseIfLatest(boolean removeFocus) {
7131        if (removeFocus) {
7132            clearTextEntry();
7133        }
7134        mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE_IF_LATEST,
7135                cursorData());
7136    }
7137
7138    // called by JNI
7139    private void sendMotionUp(int touchGeneration,
7140            int frame, int node, int x, int y) {
7141        WebViewCore.TouchUpData touchUpData = new WebViewCore.TouchUpData();
7142        touchUpData.mMoveGeneration = touchGeneration;
7143        touchUpData.mFrame = frame;
7144        touchUpData.mNode = node;
7145        touchUpData.mX = x;
7146        touchUpData.mY = y;
7147        mWebViewCore.sendMessage(EventHub.TOUCH_UP, touchUpData);
7148    }
7149
7150
7151    private int getScaledMaxXScroll() {
7152        int width;
7153        if (mHeightCanMeasure == false) {
7154            width = getViewWidth() / 4;
7155        } else {
7156            Rect visRect = new Rect();
7157            calcOurVisibleRect(visRect);
7158            width = visRect.width() / 2;
7159        }
7160        // FIXME the divisor should be retrieved from somewhere
7161        return viewToContentX(width);
7162    }
7163
7164    private int getScaledMaxYScroll() {
7165        int height;
7166        if (mHeightCanMeasure == false) {
7167            height = getViewHeight() / 4;
7168        } else {
7169            Rect visRect = new Rect();
7170            calcOurVisibleRect(visRect);
7171            height = visRect.height() / 2;
7172        }
7173        // FIXME the divisor should be retrieved from somewhere
7174        // the closest thing today is hard-coded into ScrollView.java
7175        // (from ScrollView.java, line 363)   int maxJump = height/2;
7176        return Math.round(height * mZoomManager.getInvScale());
7177    }
7178
7179    /**
7180     * Called by JNI to invalidate view
7181     */
7182    private void viewInvalidate() {
7183        invalidate();
7184    }
7185
7186    /**
7187     * Pass the key directly to the page.  This assumes that
7188     * nativePageShouldHandleShiftAndArrows() returned true.
7189     */
7190    private void letPageHandleNavKey(int keyCode, long time, boolean down) {
7191        int keyEventAction;
7192        int eventHubAction;
7193        if (down) {
7194            keyEventAction = KeyEvent.ACTION_DOWN;
7195            eventHubAction = EventHub.KEY_DOWN;
7196            playSoundEffect(keyCodeToSoundsEffect(keyCode));
7197        } else {
7198            keyEventAction = KeyEvent.ACTION_UP;
7199            eventHubAction = EventHub.KEY_UP;
7200        }
7201        KeyEvent event = new KeyEvent(time, time, keyEventAction, keyCode,
7202                1, (mShiftIsPressed ? KeyEvent.META_SHIFT_ON : 0)
7203                | (false ? KeyEvent.META_ALT_ON : 0) // FIXME
7204                | (false ? KeyEvent.META_SYM_ON : 0) // FIXME
7205                , 0, 0, 0);
7206        mWebViewCore.sendMessage(eventHubAction, event);
7207    }
7208
7209    // return true if the key was handled
7210    private boolean navHandledKey(int keyCode, int count, boolean noScroll,
7211            long time) {
7212        if (mNativeClass == 0) {
7213            return false;
7214        }
7215        mLastCursorTime = time;
7216        mLastCursorBounds = nativeGetCursorRingBounds();
7217        boolean keyHandled
7218                = nativeMoveCursor(keyCode, count, noScroll) == false;
7219        if (DebugFlags.WEB_VIEW) {
7220            Log.v(LOGTAG, "navHandledKey mLastCursorBounds=" + mLastCursorBounds
7221                    + " mLastCursorTime=" + mLastCursorTime
7222                    + " handled=" + keyHandled);
7223        }
7224        if (keyHandled == false || mHeightCanMeasure == false) {
7225            return keyHandled;
7226        }
7227        Rect contentCursorRingBounds = nativeGetCursorRingBounds();
7228        if (contentCursorRingBounds.isEmpty()) return keyHandled;
7229        Rect viewCursorRingBounds = contentToViewRect(contentCursorRingBounds);
7230        Rect visRect = new Rect();
7231        calcOurVisibleRect(visRect);
7232        Rect outset = new Rect(visRect);
7233        int maxXScroll = visRect.width() / 2;
7234        int maxYScroll = visRect.height() / 2;
7235        outset.inset(-maxXScroll, -maxYScroll);
7236        if (Rect.intersects(outset, viewCursorRingBounds) == false) {
7237            return keyHandled;
7238        }
7239        // FIXME: Necessary because ScrollView/ListView do not scroll left/right
7240        int maxH = Math.min(viewCursorRingBounds.right - visRect.right,
7241                maxXScroll);
7242        if (maxH > 0) {
7243            pinScrollBy(maxH, 0, true, 0);
7244        } else {
7245            maxH = Math.max(viewCursorRingBounds.left - visRect.left,
7246                    -maxXScroll);
7247            if (maxH < 0) {
7248                pinScrollBy(maxH, 0, true, 0);
7249            }
7250        }
7251        if (mLastCursorBounds.isEmpty()) return keyHandled;
7252        if (mLastCursorBounds.equals(contentCursorRingBounds)) {
7253            return keyHandled;
7254        }
7255        if (DebugFlags.WEB_VIEW) {
7256            Log.v(LOGTAG, "navHandledKey contentCursorRingBounds="
7257                    + contentCursorRingBounds);
7258        }
7259        requestRectangleOnScreen(viewCursorRingBounds);
7260        mUserScroll = true;
7261        return keyHandled;
7262    }
7263
7264    /**
7265     * Set the background color. It's white by default. Pass
7266     * zero to make the view transparent.
7267     * @param color   the ARGB color described by Color.java
7268     */
7269    public void setBackgroundColor(int color) {
7270        mBackgroundColor = color;
7271        mWebViewCore.sendMessage(EventHub.SET_BACKGROUND_COLOR, color);
7272    }
7273
7274    public void debugDump() {
7275        nativeDebugDump();
7276        mWebViewCore.sendMessage(EventHub.DUMP_NAVTREE);
7277    }
7278
7279    /**
7280     * Draw the HTML page into the specified canvas. This call ignores any
7281     * view-specific zoom, scroll offset, or other changes. It does not draw
7282     * any view-specific chrome, such as progress or URL bars.
7283     *
7284     * @hide only needs to be accessible to Browser and testing
7285     */
7286    public void drawPage(Canvas canvas) {
7287        nativeDraw(canvas, 0, 0, false);
7288    }
7289
7290    /**
7291     * Set the time to wait between passing touches to WebCore. See also the
7292     * TOUCH_SENT_INTERVAL member for further discussion.
7293     *
7294     * @hide This is only used by the DRT test application.
7295     */
7296    public void setTouchInterval(int interval) {
7297        mCurrentTouchInterval = interval;
7298    }
7299
7300    /**
7301     *  Update our cache with updatedText.
7302     *  @param updatedText  The new text to put in our cache.
7303     */
7304    /* package */ void updateCachedTextfield(String updatedText) {
7305        // Also place our generation number so that when we look at the cache
7306        // we recognize that it is up to date.
7307        nativeUpdateCachedTextfield(updatedText, mTextGeneration);
7308    }
7309
7310    private native int nativeCacheHitFramePointer();
7311    private native Rect nativeCacheHitNodeBounds();
7312    private native int nativeCacheHitNodePointer();
7313    /* package */ native void nativeClearCursor();
7314    private native void     nativeCreate(int ptr);
7315    private native int      nativeCursorFramePointer();
7316    private native Rect     nativeCursorNodeBounds();
7317    private native int nativeCursorNodePointer();
7318    /* package */ native boolean nativeCursorMatchesFocus();
7319    private native boolean  nativeCursorIntersects(Rect visibleRect);
7320    private native boolean  nativeCursorIsAnchor();
7321    private native boolean  nativeCursorIsTextInput();
7322    private native Point    nativeCursorPosition();
7323    private native String   nativeCursorText();
7324    /**
7325     * Returns true if the native cursor node says it wants to handle key events
7326     * (ala plugins). This can only be called if mNativeClass is non-zero!
7327     */
7328    private native boolean  nativeCursorWantsKeyEvents();
7329    private native void     nativeDebugDump();
7330    private native void     nativeDestroy();
7331
7332    /**
7333     * Draw the picture set with a background color and extra. If
7334     * "splitIfNeeded" is true and the return value is not 0, the return value
7335     * MUST be passed to WebViewCore with SPLIT_PICTURE_SET message so that the
7336     * native allocation can be freed.
7337     */
7338    private native int nativeDraw(Canvas canvas, int color, int extra,
7339            boolean splitIfNeeded);
7340    private native void     nativeDumpDisplayTree(String urlOrNull);
7341    private native boolean  nativeEvaluateLayersAnimations();
7342    private native void     nativeExtendSelection(int x, int y);
7343    private native int      nativeFindAll(String findLower, String findUpper);
7344    private native void     nativeFindNext(boolean forward);
7345    /* package */ native int      nativeFocusCandidateFramePointer();
7346    /* package */ native boolean  nativeFocusCandidateHasNextTextfield();
7347    /* package */ native boolean  nativeFocusCandidateIsPassword();
7348    private native boolean  nativeFocusCandidateIsRtlText();
7349    private native boolean  nativeFocusCandidateIsTextInput();
7350    /* package */ native int      nativeFocusCandidateMaxLength();
7351    /* package */ native String   nativeFocusCandidateName();
7352    private native Rect     nativeFocusCandidateNodeBounds();
7353    /* package */ native int      nativeFocusCandidatePointer();
7354    private native String   nativeFocusCandidateText();
7355    private native int      nativeFocusCandidateTextSize();
7356    /**
7357     * Returns an integer corresponding to WebView.cpp::type.
7358     * See WebTextView.setType()
7359     */
7360    private native int      nativeFocusCandidateType();
7361    private native boolean  nativeFocusIsPlugin();
7362    private native Rect     nativeFocusNodeBounds();
7363    /* package */ native int nativeFocusNodePointer();
7364    private native Rect     nativeGetCursorRingBounds();
7365    private native String   nativeGetSelection();
7366    private native boolean  nativeHasCursorNode();
7367    private native boolean  nativeHasFocusNode();
7368    private native void     nativeHideCursor();
7369    private native boolean  nativeHitSelection(int x, int y);
7370    private native String   nativeImageURI(int x, int y);
7371    private native void     nativeInstrumentReport();
7372    /* package */ native boolean nativeMoveCursorToNextTextInput();
7373    // return true if the page has been scrolled
7374    private native boolean  nativeMotionUp(int x, int y, int slop);
7375    // returns false if it handled the key
7376    private native boolean  nativeMoveCursor(int keyCode, int count,
7377            boolean noScroll);
7378    private native int      nativeMoveGeneration();
7379    private native void     nativeMoveSelection(int x, int y);
7380    /**
7381     * @return true if the page should get the shift and arrow keys, rather
7382     * than select text/navigation.
7383     *
7384     * If the focus is a plugin, or if the focus and cursor match and are
7385     * a contentEditable element, then the page should handle these keys.
7386     */
7387    private native boolean  nativePageShouldHandleShiftAndArrows();
7388    private native boolean  nativePointInNavCache(int x, int y, int slop);
7389    // Like many other of our native methods, you must make sure that
7390    // mNativeClass is not null before calling this method.
7391    private native void     nativeRecordButtons(boolean focused,
7392            boolean pressed, boolean invalidate);
7393    private native void     nativeResetSelection();
7394    private native void     nativeSelectAll();
7395    private native void     nativeSelectBestAt(Rect rect);
7396    private native int      nativeSelectionX();
7397    private native int      nativeSelectionY();
7398    private native int      nativeFindIndex();
7399    private native void     nativeSetExtendSelection();
7400    private native void     nativeSetFindIsEmpty();
7401    private native void     nativeSetFindIsUp(boolean isUp);
7402    private native void     nativeSetHeightCanMeasure(boolean measure);
7403    private native void     nativeSetBaseLayer(int layer);
7404    private native void     nativeShowCursorTimed();
7405    private native void     nativeReplaceBaseContent(int content);
7406    private native void     nativeCopyBaseContentToPicture(Picture pict);
7407    private native boolean  nativeHasContent();
7408    private native void     nativeSetSelectionPointer(boolean set,
7409            float scale, int x, int y);
7410    private native boolean  nativeStartSelection(int x, int y);
7411    private native Rect     nativeSubtractLayers(Rect content);
7412    private native int      nativeTextGeneration();
7413    // Never call this version except by updateCachedTextfield(String) -
7414    // we always want to pass in our generation number.
7415    private native void     nativeUpdateCachedTextfield(String updatedText,
7416            int generation);
7417    private native boolean  nativeWordSelection(int x, int y);
7418    // return NO_LEFTEDGE means failure.
7419    static final int NO_LEFTEDGE = -1;
7420    native int nativeGetBlockLeftEdge(int x, int y, float scale);
7421
7422    // Returns a pointer to the scrollable LayerAndroid at the given point.
7423    private native int      nativeScrollableLayer(int x, int y);
7424    private native boolean  nativeScrollLayer(int layer, int dx, int dy);
7425}
7426