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