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