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