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