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