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