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