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