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