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