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