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