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