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