WebView.java revision d7bd2eb0321936e377592be9039de957b8794ab1
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 com.android.internal.R; 20 21import android.annotation.Widget; 22import android.app.AlertDialog; 23import android.content.Context; 24import android.content.DialogInterface; 25import android.content.DialogInterface.OnCancelListener; 26import android.content.Intent; 27import android.content.pm.PackageManager; 28import android.content.res.Resources; 29import android.database.DataSetObserver; 30import android.graphics.Bitmap; 31import android.graphics.BitmapFactory; 32import android.graphics.BitmapShader; 33import android.graphics.Canvas; 34import android.graphics.Color; 35import android.graphics.Interpolator; 36import android.graphics.Paint; 37import android.graphics.Picture; 38import android.graphics.Point; 39import android.graphics.Rect; 40import android.graphics.RectF; 41import android.graphics.Region; 42import android.graphics.Shader; 43import android.graphics.drawable.Drawable; 44import android.net.Uri; 45import android.net.http.SslCertificate; 46import android.os.Bundle; 47import android.os.Handler; 48import android.os.Message; 49import android.os.ServiceManager; 50import android.os.SystemClock; 51import android.text.IClipboard; 52import android.text.Selection; 53import android.text.Spannable; 54import android.util.AttributeSet; 55import android.util.EventLog; 56import android.util.Log; 57import android.util.TypedValue; 58import android.view.Gravity; 59import android.view.KeyEvent; 60import android.view.LayoutInflater; 61import android.view.MotionEvent; 62import android.view.ScaleGestureDetector; 63import android.view.SoundEffectConstants; 64import android.view.VelocityTracker; 65import android.view.View; 66import android.view.ViewConfiguration; 67import android.view.ViewGroup; 68import android.view.ViewTreeObserver; 69import android.view.animation.AlphaAnimation; 70import android.view.inputmethod.EditorInfo; 71import android.view.inputmethod.InputConnection; 72import android.view.inputmethod.InputMethodManager; 73import android.webkit.WebTextView.AutoCompleteAdapter; 74import android.webkit.WebViewCore.EventHub; 75import android.webkit.WebViewCore.TouchEventData; 76import android.widget.AbsoluteLayout; 77import android.widget.Adapter; 78import android.widget.AdapterView; 79import android.widget.AdapterView.OnItemClickListener; 80import android.widget.ArrayAdapter; 81import android.widget.CheckedTextView; 82import android.widget.EdgeGlow; 83import android.widget.FrameLayout; 84import android.widget.LinearLayout; 85import android.widget.ListView; 86import android.widget.OverScroller; 87import android.widget.Toast; 88import android.widget.ZoomButtonsController; 89import android.widget.ZoomControls; 90 91import java.io.File; 92import java.io.FileInputStream; 93import java.io.FileNotFoundException; 94import java.io.FileOutputStream; 95import java.net.URLDecoder; 96import java.util.ArrayList; 97import java.util.HashMap; 98import java.util.List; 99import java.util.Map; 100import java.util.Set; 101 102import junit.framework.Assert; 103 104/** 105 * <p>A View that displays web pages. This class is the basis upon which you 106 * can roll your own web browser or simply display some online content within your Activity. 107 * It uses the WebKit rendering engine to display 108 * web pages and includes methods to navigate forward and backward 109 * through a history, zoom in and out, perform text searches and more.</p> 110 * <p>To enable the built-in zoom, set 111 * {@link #getSettings() WebSettings}.{@link WebSettings#setBuiltInZoomControls(boolean)} 112 * (introduced in API version 3). 113 * <p>Note that, in order for your Activity to access the Internet and load web pages 114 * in a WebView, you must add the {@code INTERNET} permissions to your 115 * Android Manifest file:</p> 116 * <pre><uses-permission android:name="android.permission.INTERNET" /></pre> 117 * 118 * <p>This must be a child of the <a 119 * href="{@docRoot}guide/topics/manifest/manifest-element.html">{@code <manifest>}</a> 120 * element.</p> 121 * 122 * <p>See the <a href="{@docRoot}resources/tutorials/views/hello-webview.html">Web View 123 * tutorial</a>.</p> 124 * 125 * <h3>Basic usage</h3> 126 * 127 * <p>By default, a WebView provides no browser-like widgets, does not 128 * enable JavaScript and web page errors are ignored. If your goal is only 129 * to display some HTML as a part of your UI, this is probably fine; 130 * the user won't need to interact with the web page beyond reading 131 * it, and the web page won't need to interact with the user. If you 132 * actually want a full-blown web browser, then you probably want to 133 * invoke the Browser application with a URL Intent rather than show it 134 * with a WebView. For example: 135 * <pre> 136 * Uri uri = Uri.parse("http://www.example.com"); 137 * Intent intent = new Intent(Intent.ACTION_VIEW, uri); 138 * startActivity(intent); 139 * </pre> 140 * <p>See {@link android.content.Intent} for more information.</p> 141 * 142 * <p>To provide a WebView in your own Activity, include a {@code <WebView>} in your layout, 143 * or set the entire Activity window as a WebView during {@link 144 * android.app.Activity#onCreate(Bundle) onCreate()}:</p> 145 * <pre class="prettyprint"> 146 * WebView webview = new WebView(this); 147 * setContentView(webview); 148 * </pre> 149 * 150 * <p>Then load the desired web page:</p> 151 * <pre> 152 * // Simplest usage: note that an exception will NOT be thrown 153 * // if there is an error loading this page (see below). 154 * webview.loadUrl("http://slashdot.org/"); 155 * 156 * // OR, you can also load from an HTML string: 157 * String summary = "<html><body>You scored <b>192</b> points.</body></html>"; 158 * webview.loadData(summary, "text/html", "utf-8"); 159 * // ... although note that there are restrictions on what this HTML can do. 160 * // See the JavaDocs for {@link #loadData(String,String,String) loadData()} and {@link 161 * #loadDataWithBaseURL(String,String,String,String,String) loadDataWithBaseURL()} for more info. 162 * </pre> 163 * 164 * <p>A WebView has several customization points where you can add your 165 * own behavior. These are:</p> 166 * 167 * <ul> 168 * <li>Creating and setting a {@link android.webkit.WebChromeClient} subclass. 169 * This class is called when something that might impact a 170 * browser UI happens, for instance, progress updates and 171 * JavaScript alerts are sent here (see <a 172 * href="{@docRoot}guide/developing/debug-tasks.html#DebuggingWebPages">Debugging Tasks</a>). 173 * </li> 174 * <li>Creating and setting a {@link android.webkit.WebViewClient} subclass. 175 * It will be called when things happen that impact the 176 * rendering of the content, eg, errors or form submissions. You 177 * can also intercept URL loading here (via {@link 178 * android.webkit.WebViewClient#shouldOverrideUrlLoading(WebView,String) 179 * shouldOverrideUrlLoading()}).</li> 180 * <li>Modifying the {@link android.webkit.WebSettings}, such as 181 * enabling JavaScript with {@link android.webkit.WebSettings#setJavaScriptEnabled(boolean) 182 * setJavaScriptEnabled()}. </li> 183 * <li>Adding JavaScript-to-Java interfaces with the {@link 184 * android.webkit.WebView#addJavascriptInterface} method. 185 * This lets you bind Java objects into the WebView so they can be 186 * controlled from the web pages JavaScript.</li> 187 * </ul> 188 * 189 * <p>Here's a more complicated example, showing error handling, 190 * settings, and progress notification:</p> 191 * 192 * <pre class="prettyprint"> 193 * // Let's display the progress in the activity title bar, like the 194 * // browser app does. 195 * getWindow().requestFeature(Window.FEATURE_PROGRESS); 196 * 197 * webview.getSettings().setJavaScriptEnabled(true); 198 * 199 * final Activity activity = this; 200 * webview.setWebChromeClient(new WebChromeClient() { 201 * public void onProgressChanged(WebView view, int progress) { 202 * // Activities and WebViews measure progress with different scales. 203 * // The progress meter will automatically disappear when we reach 100% 204 * activity.setProgress(progress * 1000); 205 * } 206 * }); 207 * webview.setWebViewClient(new WebViewClient() { 208 * public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { 209 * Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show(); 210 * } 211 * }); 212 * 213 * webview.loadUrl("http://slashdot.org/"); 214 * </pre> 215 * 216 * <h3>Cookie and window management</h3> 217 * 218 * <p>For obvious security reasons, your application has its own 219 * cache, cookie store etc.—it does not share the Browser 220 * application's data. Cookies are managed on a separate thread, so 221 * operations like index building don't block the UI 222 * thread. Follow the instructions in {@link android.webkit.CookieSyncManager} 223 * if you want to use cookies in your application. 224 * </p> 225 * 226 * <p>By default, requests by the HTML to open new windows are 227 * ignored. This is true whether they be opened by JavaScript or by 228 * the target attribute on a link. You can customize your 229 * {@link WebChromeClient} to provide your own behaviour for opening multiple windows, 230 * and render them in whatever manner you want.</p> 231 * 232 * <p>The standard behavior for an Activity is to be destroyed and 233 * recreated when the device orientation or any other configuration changes. This will cause 234 * the WebView to reload the current page. If you don't want that, you 235 * can set your Activity to handle the {@code orientation} and {@code keyboardHidden} 236 * changes, and then just leave the WebView alone. It'll automatically 237 * re-orient itself as appropriate. Read <a 238 * href="{@docRoot}guide/topics/resources/runtime-changes.html">Handling Runtime Changes</a> for 239 * more information about how to handle configuration changes during runtime.</p> 240 * 241 * 242 * <h3>Building web pages to support different screen densities</h3> 243 * 244 * <p>The screen density of a device is based on the screen resolution. A screen with low density 245 * has fewer available pixels per inch, where a screen with high density 246 * has more — sometimes significantly more — pixels per inch. The density of a 247 * screen is important because, other things being equal, a UI element (such as a button) whose 248 * height and width are defined in terms of screen pixels will appear larger on the lower density 249 * screen and smaller on the higher density screen. 250 * For simplicity, Android collapses all actual screen densities into three generalized densities: 251 * high, medium, and low.</p> 252 * <p>By default, WebView scales a web page so that it is drawn at a size that matches the default 253 * appearance on a medium density screen. So, it applies 1.5x scaling on a high density screen 254 * (because its pixels are smaller) and 0.75x scaling on a low density screen (because its pixels 255 * are bigger). 256 * Starting with API Level 5 (Android 2.0), WebView supports DOM, CSS, and meta tag features to help 257 * you (as a web developer) target screens with different screen densities.</p> 258 * <p>Here's a summary of the features you can use to handle different screen densities:</p> 259 * <ul> 260 * <li>The {@code window.devicePixelRatio} DOM property. The value of this property specifies the 261 * default scaling factor used for the current device. For example, if the value of {@code 262 * window.devicePixelRatio} is "1.0", then the device is considered a medium density (mdpi) device 263 * and default scaling is not applied to the web page; if the value is "1.5", then the device is 264 * considered a high density device (hdpi) and the page content is scaled 1.5x; if the 265 * value is "0.75", then the device is considered a low density device (ldpi) and the content is 266 * scaled 0.75x. However, if you specify the {@code "target-densitydpi"} meta property 267 * (discussed below), then you can stop this default scaling behavior.</li> 268 * <li>The {@code -webkit-device-pixel-ratio} CSS media query. Use this to specify the screen 269 * densities for which this style sheet is to be used. The corresponding value should be either 270 * "0.75", "1", or "1.5", to indicate that the styles are for devices with low density, medium 271 * density, or high density screens, respectively. For example: 272 * <pre> 273 * <link rel="stylesheet" media="screen and (-webkit-device-pixel-ratio:1.5)" href="hdpi.css" /></pre> 274 * <p>The {@code hdpi.css} stylesheet is only used for devices with a screen pixel ration of 1.5, 275 * which is the high density pixel ratio.</p> 276 * </li> 277 * <li>The {@code target-densitydpi} property for the {@code viewport} meta tag. You can use 278 * this to specify the target density for which the web page is designed, using the following 279 * values: 280 * <ul> 281 * <li>{@code device-dpi} - Use the device's native dpi as the target dpi. Default scaling never 282 * occurs.</li> 283 * <li>{@code high-dpi} - Use hdpi as the target dpi. Medium and low density screens scale down 284 * as appropriate.</li> 285 * <li>{@code medium-dpi} - Use mdpi as the target dpi. High density screens scale up and 286 * low density screens scale down. This is also the default behavior.</li> 287 * <li>{@code low-dpi} - Use ldpi as the target dpi. Medium and high density screens scale up 288 * as appropriate.</li> 289 * <li><em>{@code <value>}</em> - Specify a dpi value to use as the target dpi (accepted 290 * values are 70-400).</li> 291 * </ul> 292 * <p>Here's an example meta tag to specify the target density:</p> 293 * <pre><meta name="viewport" content="target-densitydpi=device-dpi" /></pre></li> 294 * </ul> 295 * <p>If you want to modify your web page for different densities, by using the {@code 296 * -webkit-device-pixel-ratio} CSS media query and/or the {@code 297 * window.devicePixelRatio} DOM property, then you should set the {@code target-densitydpi} meta 298 * property to {@code device-dpi}. This stops Android from performing scaling in your web page and 299 * allows you to make the necessary adjustments for each density via CSS and JavaScript.</p> 300 * 301 * 302 */ 303@Widget 304public class WebView extends AbsoluteLayout 305 implements ViewTreeObserver.OnGlobalFocusChangeListener, 306 ViewGroup.OnHierarchyChangeListener { 307 308 // enable debug output for drag trackers 309 private static final boolean DEBUG_DRAG_TRACKER = false; 310 // if AUTO_REDRAW_HACK is true, then the CALL key will toggle redrawing 311 // the screen all-the-time. Good for profiling our drawing code 312 static private final boolean AUTO_REDRAW_HACK = false; 313 // true means redraw the screen all-the-time. Only with AUTO_REDRAW_HACK 314 private boolean mAutoRedraw; 315 316 static final String LOGTAG = "webview"; 317 318 private static class ExtendedZoomControls extends FrameLayout { 319 public ExtendedZoomControls(Context context, AttributeSet attrs) { 320 super(context, attrs); 321 LayoutInflater inflater = (LayoutInflater) 322 context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 323 inflater.inflate(com.android.internal.R.layout.zoom_magnify, this, true); 324 mPlusMinusZoomControls = (ZoomControls) findViewById( 325 com.android.internal.R.id.zoomControls); 326 findViewById(com.android.internal.R.id.zoomMagnify).setVisibility( 327 View.GONE); 328 } 329 330 public void show(boolean showZoom, boolean canZoomOut) { 331 mPlusMinusZoomControls.setVisibility( 332 showZoom ? View.VISIBLE : View.GONE); 333 fade(View.VISIBLE, 0.0f, 1.0f); 334 } 335 336 public void hide() { 337 fade(View.GONE, 1.0f, 0.0f); 338 } 339 340 private void fade(int visibility, float startAlpha, float endAlpha) { 341 AlphaAnimation anim = new AlphaAnimation(startAlpha, endAlpha); 342 anim.setDuration(500); 343 startAnimation(anim); 344 setVisibility(visibility); 345 } 346 347 public boolean hasFocus() { 348 return mPlusMinusZoomControls.hasFocus(); 349 } 350 351 public void setOnZoomInClickListener(OnClickListener listener) { 352 mPlusMinusZoomControls.setOnZoomInClickListener(listener); 353 } 354 355 public void setOnZoomOutClickListener(OnClickListener listener) { 356 mPlusMinusZoomControls.setOnZoomOutClickListener(listener); 357 } 358 359 ZoomControls mPlusMinusZoomControls; 360 } 361 362 /** 363 * Transportation object for returning WebView across thread boundaries. 364 */ 365 public class WebViewTransport { 366 private WebView mWebview; 367 368 /** 369 * Set the WebView to the transportation object. 370 * @param webview The WebView to transport. 371 */ 372 public synchronized void setWebView(WebView webview) { 373 mWebview = webview; 374 } 375 376 /** 377 * Return the WebView object. 378 * @return WebView The transported WebView object. 379 */ 380 public synchronized WebView getWebView() { 381 return mWebview; 382 } 383 } 384 385 // A final CallbackProxy shared by WebViewCore and BrowserFrame. 386 private final CallbackProxy mCallbackProxy; 387 388 private final WebViewDatabase mDatabase; 389 390 // SSL certificate for the main top-level page (if secure) 391 private SslCertificate mCertificate; 392 393 // Native WebView pointer that is 0 until the native object has been 394 // created. 395 private int mNativeClass; 396 // This would be final but it needs to be set to null when the WebView is 397 // destroyed. 398 private WebViewCore mWebViewCore; 399 // Handler for dispatching UI messages. 400 /* package */ final Handler mPrivateHandler = new PrivateHandler(); 401 private WebTextView mWebTextView; 402 // Used to ignore changes to webkit text that arrives to the UI side after 403 // more key events. 404 private int mTextGeneration; 405 406 // Used by WebViewCore to create child views. 407 /* package */ final ViewManager mViewManager; 408 409 // Used to display in full screen mode 410 PluginFullScreenHolder mFullScreenHolder; 411 412 /** 413 * Position of the last touch event. 414 */ 415 private float mLastTouchX; 416 private float mLastTouchY; 417 418 /** 419 * Time of the last touch event. 420 */ 421 private long mLastTouchTime; 422 423 /** 424 * Time of the last time sending touch event to WebViewCore 425 */ 426 private long mLastSentTouchTime; 427 428 /** 429 * The minimum elapsed time before sending another ACTION_MOVE event to 430 * WebViewCore. This really should be tuned for each type of the devices. 431 * For example in Google Map api test case, it takes Dream device at least 432 * 150ms to do a full cycle in the WebViewCore by processing a touch event, 433 * triggering the layout and drawing the picture. While the same process 434 * takes 60+ms on the current high speed device. If we make 435 * TOUCH_SENT_INTERVAL too small, there will be multiple touch events sent 436 * to WebViewCore queue and the real layout and draw events will be pushed 437 * to further, which slows down the refresh rate. Choose 50 to favor the 438 * current high speed devices. For Dream like devices, 100 is a better 439 * choice. Maybe make this in the buildspec later. 440 */ 441 private static final int TOUCH_SENT_INTERVAL = 50; 442 private int mCurrentTouchInterval = TOUCH_SENT_INTERVAL; 443 444 /** 445 * Helper class to get velocity for fling 446 */ 447 VelocityTracker mVelocityTracker; 448 private int mMaximumFling; 449 private float mLastVelocity; 450 private float mLastVelX; 451 private float mLastVelY; 452 453 /** 454 * Touch mode 455 */ 456 private int mTouchMode = TOUCH_DONE_MODE; 457 private static final int TOUCH_INIT_MODE = 1; 458 private static final int TOUCH_DRAG_START_MODE = 2; 459 private static final int TOUCH_DRAG_MODE = 3; 460 private static final int TOUCH_SHORTPRESS_START_MODE = 4; 461 private static final int TOUCH_SHORTPRESS_MODE = 5; 462 private static final int TOUCH_DOUBLE_TAP_MODE = 6; 463 private static final int TOUCH_DONE_MODE = 7; 464 private static final int TOUCH_PINCH_DRAG = 8; 465 466 /** 467 * True if we have a touch panel capable of detecting smooth pan/scale at the same time 468 */ 469 private boolean mAllowPanAndScale; 470 471 // Whether to forward the touch events to WebCore 472 private boolean mForwardTouchEvents = false; 473 474 // Whether to prevent default during touch. The initial value depends on 475 // mForwardTouchEvents. If WebCore wants all the touch events, it says yes 476 // for touch down. Otherwise UI will wait for the answer of the first 477 // confirmed move before taking over the control. 478 private static final int PREVENT_DEFAULT_NO = 0; 479 private static final int PREVENT_DEFAULT_MAYBE_YES = 1; 480 private static final int PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN = 2; 481 private static final int PREVENT_DEFAULT_YES = 3; 482 private static final int PREVENT_DEFAULT_IGNORE = 4; 483 private int mPreventDefault = PREVENT_DEFAULT_IGNORE; 484 485 // true when the touch movement exceeds the slop 486 private boolean mConfirmMove; 487 488 // if true, touch events will be first processed by WebCore, if prevent 489 // default is not set, the UI will continue handle them. 490 private boolean mDeferTouchProcess; 491 492 // to avoid interfering with the current touch events, track them 493 // separately. Currently no snapping or fling in the deferred process mode 494 private int mDeferTouchMode = TOUCH_DONE_MODE; 495 private float mLastDeferTouchX; 496 private float mLastDeferTouchY; 497 498 // To keep track of whether the current drag was initiated by a WebTextView, 499 // so that we know not to hide the cursor 500 boolean mDragFromTextInput; 501 502 // Whether or not to draw the cursor ring. 503 private boolean mDrawCursorRing = true; 504 505 // true if onPause has been called (and not onResume) 506 private boolean mIsPaused; 507 508 // true if, during a transition to a new page, we're delaying 509 // deleting a root layer until there's something to draw of the new page. 510 private boolean mDelayedDeleteRootLayer; 511 512 /** 513 * Customizable constant 514 */ 515 // pre-computed square of ViewConfiguration.getScaledTouchSlop() 516 private int mTouchSlopSquare; 517 // pre-computed square of ViewConfiguration.getScaledDoubleTapSlop() 518 private int mDoubleTapSlopSquare; 519 // pre-computed density adjusted navigation slop 520 private int mNavSlop; 521 // This should be ViewConfiguration.getTapTimeout() 522 // But system time out is 100ms, which is too short for the browser. 523 // In the browser, if it switches out of tap too soon, jump tap won't work. 524 private static final int TAP_TIMEOUT = 200; 525 // This should be ViewConfiguration.getLongPressTimeout() 526 // But system time out is 500ms, which is too short for the browser. 527 // With a short timeout, it's difficult to treat trigger a short press. 528 private static final int LONG_PRESS_TIMEOUT = 1000; 529 // needed to avoid flinging after a pause of no movement 530 private static final int MIN_FLING_TIME = 250; 531 // draw unfiltered after drag is held without movement 532 private static final int MOTIONLESS_TIME = 100; 533 // The time that the Zoom Controls are visible before fading away 534 private static final long ZOOM_CONTROLS_TIMEOUT = 535 ViewConfiguration.getZoomControlsTimeout(); 536 // The amount of content to overlap between two screens when going through 537 // pages with the space bar, in pixels. 538 private static final int PAGE_SCROLL_OVERLAP = 24; 539 540 /** 541 * These prevent calling requestLayout if either dimension is fixed. This 542 * depends on the layout parameters and the measure specs. 543 */ 544 boolean mWidthCanMeasure; 545 boolean mHeightCanMeasure; 546 547 // Remember the last dimensions we sent to the native side so we can avoid 548 // sending the same dimensions more than once. 549 int mLastWidthSent; 550 int mLastHeightSent; 551 552 private int mContentWidth; // cache of value from WebViewCore 553 private int mContentHeight; // cache of value from WebViewCore 554 555 // Need to have the separate control for horizontal and vertical scrollbar 556 // style than the View's single scrollbar style 557 private boolean mOverlayHorizontalScrollbar = true; 558 private boolean mOverlayVerticalScrollbar = false; 559 560 // our standard speed. this way small distances will be traversed in less 561 // time than large distances, but we cap the duration, so that very large 562 // distances won't take too long to get there. 563 private static final int STD_SPEED = 480; // pixels per second 564 // time for the longest scroll animation 565 private static final int MAX_DURATION = 750; // milliseconds 566 private static final int SLIDE_TITLE_DURATION = 500; // milliseconds 567 private OverScroller mScroller; 568 private boolean mInOverScrollMode = false; 569 private static Paint mOverScrollBackground; 570 private static Paint mOverScrollBorder; 571 572 private boolean mWrapContent; 573 private static final int MOTIONLESS_FALSE = 0; 574 private static final int MOTIONLESS_PENDING = 1; 575 private static final int MOTIONLESS_TRUE = 2; 576 private static final int MOTIONLESS_IGNORE = 3; 577 private int mHeldMotionless; 578 579 // whether support multi-touch 580 private boolean mSupportMultiTouch; 581 // use the framework's ScaleGestureDetector to handle multi-touch 582 private ScaleGestureDetector mScaleDetector; 583 584 // the anchor point in the document space where VIEW_SIZE_CHANGED should 585 // apply to 586 private int mAnchorX; 587 private int mAnchorY; 588 589 /* 590 * Private message ids 591 */ 592 private static final int REMEMBER_PASSWORD = 1; 593 private static final int NEVER_REMEMBER_PASSWORD = 2; 594 private static final int SWITCH_TO_SHORTPRESS = 3; 595 private static final int SWITCH_TO_LONGPRESS = 4; 596 private static final int RELEASE_SINGLE_TAP = 5; 597 private static final int REQUEST_FORM_DATA = 6; 598 private static final int RESUME_WEBCORE_PRIORITY = 7; 599 private static final int DRAG_HELD_MOTIONLESS = 8; 600 private static final int AWAKEN_SCROLL_BARS = 9; 601 private static final int PREVENT_DEFAULT_TIMEOUT = 10; 602 603 private static final int FIRST_PRIVATE_MSG_ID = REMEMBER_PASSWORD; 604 private static final int LAST_PRIVATE_MSG_ID = PREVENT_DEFAULT_TIMEOUT; 605 606 /* 607 * Package message ids 608 */ 609 //! arg1=x, arg2=y 610 static final int SCROLL_TO_MSG_ID = 101; 611 static final int SCROLL_BY_MSG_ID = 102; 612 //! arg1=x, arg2=y 613 static final int SPAWN_SCROLL_TO_MSG_ID = 103; 614 //! arg1=x, arg2=y 615 static final int SYNC_SCROLL_TO_MSG_ID = 104; 616 static final int NEW_PICTURE_MSG_ID = 105; 617 static final int UPDATE_TEXT_ENTRY_MSG_ID = 106; 618 static final int WEBCORE_INITIALIZED_MSG_ID = 107; 619 static final int UPDATE_TEXTFIELD_TEXT_MSG_ID = 108; 620 static final int UPDATE_ZOOM_RANGE = 109; 621 static final int MOVE_OUT_OF_PLUGIN = 110; 622 static final int CLEAR_TEXT_ENTRY = 111; 623 static final int UPDATE_TEXT_SELECTION_MSG_ID = 112; 624 static final int SHOW_RECT_MSG_ID = 113; 625 static final int LONG_PRESS_CENTER = 114; 626 static final int PREVENT_TOUCH_ID = 115; 627 static final int WEBCORE_NEED_TOUCH_EVENTS = 116; 628 // obj=Rect in doc coordinates 629 static final int INVAL_RECT_MSG_ID = 117; 630 static final int REQUEST_KEYBOARD = 118; 631 static final int DO_MOTION_UP = 119; 632 static final int SHOW_FULLSCREEN = 120; 633 static final int HIDE_FULLSCREEN = 121; 634 static final int DOM_FOCUS_CHANGED = 122; 635 static final int IMMEDIATE_REPAINT_MSG_ID = 123; 636 static final int SET_ROOT_LAYER_MSG_ID = 124; 637 static final int RETURN_LABEL = 125; 638 static final int FIND_AGAIN = 126; 639 static final int CENTER_FIT_RECT = 127; 640 static final int REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID = 128; 641 static final int SET_SCROLLBAR_MODES = 129; 642 643 private static final int FIRST_PACKAGE_MSG_ID = SCROLL_TO_MSG_ID; 644 private static final int LAST_PACKAGE_MSG_ID = SET_SCROLLBAR_MODES; 645 646 static final String[] HandlerPrivateDebugString = { 647 "REMEMBER_PASSWORD", // = 1; 648 "NEVER_REMEMBER_PASSWORD", // = 2; 649 "SWITCH_TO_SHORTPRESS", // = 3; 650 "SWITCH_TO_LONGPRESS", // = 4; 651 "RELEASE_SINGLE_TAP", // = 5; 652 "REQUEST_FORM_DATA", // = 6; 653 "RESUME_WEBCORE_PRIORITY", // = 7; 654 "DRAG_HELD_MOTIONLESS", // = 8; 655 "AWAKEN_SCROLL_BARS", // = 9; 656 "PREVENT_DEFAULT_TIMEOUT" // = 10; 657 }; 658 659 static final String[] HandlerPackageDebugString = { 660 "SCROLL_TO_MSG_ID", // = 101; 661 "SCROLL_BY_MSG_ID", // = 102; 662 "SPAWN_SCROLL_TO_MSG_ID", // = 103; 663 "SYNC_SCROLL_TO_MSG_ID", // = 104; 664 "NEW_PICTURE_MSG_ID", // = 105; 665 "UPDATE_TEXT_ENTRY_MSG_ID", // = 106; 666 "WEBCORE_INITIALIZED_MSG_ID", // = 107; 667 "UPDATE_TEXTFIELD_TEXT_MSG_ID", // = 108; 668 "UPDATE_ZOOM_RANGE", // = 109; 669 "MOVE_OUT_OF_PLUGIN", // = 110; 670 "CLEAR_TEXT_ENTRY", // = 111; 671 "UPDATE_TEXT_SELECTION_MSG_ID", // = 112; 672 "SHOW_RECT_MSG_ID", // = 113; 673 "LONG_PRESS_CENTER", // = 114; 674 "PREVENT_TOUCH_ID", // = 115; 675 "WEBCORE_NEED_TOUCH_EVENTS", // = 116; 676 "INVAL_RECT_MSG_ID", // = 117; 677 "REQUEST_KEYBOARD", // = 118; 678 "DO_MOTION_UP", // = 119; 679 "SHOW_FULLSCREEN", // = 120; 680 "HIDE_FULLSCREEN", // = 121; 681 "DOM_FOCUS_CHANGED", // = 122; 682 "IMMEDIATE_REPAINT_MSG_ID", // = 123; 683 "SET_ROOT_LAYER_MSG_ID", // = 124; 684 "RETURN_LABEL", // = 125; 685 "FIND_AGAIN", // = 126; 686 "CENTER_FIT_RECT", // = 127; 687 "REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID", // = 128; 688 "SET_SCROLLBAR_MODES" // = 129; 689 }; 690 691 // If the site doesn't use the viewport meta tag to specify the viewport, 692 // use DEFAULT_VIEWPORT_WIDTH as the default viewport width 693 static final int DEFAULT_VIEWPORT_WIDTH = 800; 694 695 // normally we try to fit the content to the minimum preferred width 696 // calculated by the Webkit. To avoid the bad behavior when some site's 697 // minimum preferred width keeps growing when changing the viewport width or 698 // the minimum preferred width is huge, an upper limit is needed. 699 static int sMaxViewportWidth = DEFAULT_VIEWPORT_WIDTH; 700 701 // default scale limit. Depending on the display density 702 private static float DEFAULT_MAX_ZOOM_SCALE; 703 private static float DEFAULT_MIN_ZOOM_SCALE; 704 // scale limit, which can be set through viewport meta tag in the web page 705 private float mMaxZoomScale; 706 private float mMinZoomScale; 707 private boolean mMinZoomScaleFixed = true; 708 709 // initial scale in percent. 0 means using default. 710 private int mInitialScaleInPercent = 0; 711 712 // while in the zoom overview mode, the page's width is fully fit to the 713 // current window. The page is alive, in another words, you can click to 714 // follow the links. Double tap will toggle between zoom overview mode and 715 // the last zoom scale. 716 boolean mInZoomOverview = false; 717 718 // ideally mZoomOverviewWidth should be mContentWidth. But sites like espn, 719 // engadget always have wider mContentWidth no matter what viewport size is. 720 int mZoomOverviewWidth = DEFAULT_VIEWPORT_WIDTH; 721 float mTextWrapScale; 722 723 // default scale. Depending on the display density. 724 static int DEFAULT_SCALE_PERCENT; 725 private float mDefaultScale; 726 727 private static float MINIMUM_SCALE_INCREMENT = 0.01f; 728 729 // set to true temporarily during ScaleGesture triggered zoom 730 private boolean mPreviewZoomOnly = false; 731 732 // computed scale and inverse, from mZoomWidth. 733 private float mActualScale; 734 private float mInvActualScale; 735 // if this is non-zero, it is used on drawing rather than mActualScale 736 private float mZoomScale; 737 private float mInvInitialZoomScale; 738 private float mInvFinalZoomScale; 739 private int mInitialScrollX; 740 private int mInitialScrollY; 741 private long mZoomStart; 742 private static final int ZOOM_ANIMATION_LENGTH = 500; 743 744 private boolean mUserScroll = false; 745 746 private int mSnapScrollMode = SNAP_NONE; 747 private static final int SNAP_NONE = 0; 748 private static final int SNAP_LOCK = 1; // not a separate state 749 private static final int SNAP_X = 2; // may be combined with SNAP_LOCK 750 private static final int SNAP_Y = 4; // may be combined with SNAP_LOCK 751 private boolean mSnapPositive; 752 753 // keep these in sync with their counterparts in WebView.cpp 754 private static final int DRAW_EXTRAS_NONE = 0; 755 private static final int DRAW_EXTRAS_FIND = 1; 756 private static final int DRAW_EXTRAS_SELECTION = 2; 757 private static final int DRAW_EXTRAS_CURSOR_RING = 3; 758 759 // keep this in sync with WebCore:ScrollbarMode in WebKit 760 private static final int SCROLLBAR_AUTO = 0; 761 private static final int SCROLLBAR_ALWAYSOFF = 1; 762 // as we auto fade scrollbar, this is ignored. 763 private static final int SCROLLBAR_ALWAYSON = 2; 764 private int mHorizontalScrollBarMode = SCROLLBAR_AUTO; 765 private int mVerticalScrollBarMode = SCROLLBAR_AUTO; 766 767 /** 768 * Max distance to overscroll by in pixels. 769 * This how far content can be pulled beyond its normal bounds by the user. 770 */ 771 private int mOverscrollDistance; 772 773 /** 774 * Max distance to overfling by in pixels. 775 * This is how far flinged content can move beyond the end of its normal bounds. 776 */ 777 private int mOverflingDistance; 778 779 /* 780 * These manage the edge glow effect when flung or pulled beyond the edges. 781 * If one is not null, all are not null. Checking one for null is as good as checking each. 782 */ 783 private EdgeGlow mEdgeGlowTop; 784 private EdgeGlow mEdgeGlowBottom; 785 private EdgeGlow mEdgeGlowLeft; 786 private EdgeGlow mEdgeGlowRight; 787 788 // Used to match key downs and key ups 789 private boolean mGotKeyDown; 790 791 /* package */ static boolean mLogEvent = true; 792 793 // for event log 794 private long mLastTouchUpTime = 0; 795 796 /** 797 * URI scheme for telephone number 798 */ 799 public static final String SCHEME_TEL = "tel:"; 800 /** 801 * URI scheme for email address 802 */ 803 public static final String SCHEME_MAILTO = "mailto:"; 804 /** 805 * URI scheme for map address 806 */ 807 public static final String SCHEME_GEO = "geo:0,0?q="; 808 809 private int mBackgroundColor = Color.WHITE; 810 811 // Used to notify listeners of a new picture. 812 private PictureListener mPictureListener; 813 /** 814 * Interface to listen for new pictures as they change. 815 */ 816 public interface PictureListener { 817 /** 818 * Notify the listener that the picture has changed. 819 * @param view The WebView that owns the picture. 820 * @param picture The new picture. 821 */ 822 public void onNewPicture(WebView view, Picture picture); 823 } 824 825 // FIXME: Want to make this public, but need to change the API file. 826 public /*static*/ class HitTestResult { 827 /** 828 * Default HitTestResult, where the target is unknown 829 */ 830 public static final int UNKNOWN_TYPE = 0; 831 /** 832 * HitTestResult for hitting a HTML::a tag 833 */ 834 public static final int ANCHOR_TYPE = 1; 835 /** 836 * HitTestResult for hitting a phone number 837 */ 838 public static final int PHONE_TYPE = 2; 839 /** 840 * HitTestResult for hitting a map address 841 */ 842 public static final int GEO_TYPE = 3; 843 /** 844 * HitTestResult for hitting an email address 845 */ 846 public static final int EMAIL_TYPE = 4; 847 /** 848 * HitTestResult for hitting an HTML::img tag 849 */ 850 public static final int IMAGE_TYPE = 5; 851 /** 852 * HitTestResult for hitting a HTML::a tag which contains HTML::img 853 */ 854 public static final int IMAGE_ANCHOR_TYPE = 6; 855 /** 856 * HitTestResult for hitting a HTML::a tag with src=http 857 */ 858 public static final int SRC_ANCHOR_TYPE = 7; 859 /** 860 * HitTestResult for hitting a HTML::a tag with src=http + HTML::img 861 */ 862 public static final int SRC_IMAGE_ANCHOR_TYPE = 8; 863 /** 864 * HitTestResult for hitting an edit text area 865 */ 866 public static final int EDIT_TEXT_TYPE = 9; 867 868 private int mType; 869 private String mExtra; 870 871 HitTestResult() { 872 mType = UNKNOWN_TYPE; 873 } 874 875 private void setType(int type) { 876 mType = type; 877 } 878 879 private void setExtra(String extra) { 880 mExtra = extra; 881 } 882 883 public int getType() { 884 return mType; 885 } 886 887 public String getExtra() { 888 return mExtra; 889 } 890 } 891 892 // The View containing the zoom controls 893 private ExtendedZoomControls mZoomControls; 894 private Runnable mZoomControlRunnable; 895 896 // mZoomButtonsController will be lazy initialized in 897 // getZoomButtonsController() to get better performance. 898 private ZoomButtonsController mZoomButtonsController; 899 900 // These keep track of the center point of the zoom. They are used to 901 // determine the point around which we should zoom. 902 private float mZoomCenterX; 903 private float mZoomCenterY; 904 905 private ZoomButtonsController.OnZoomListener mZoomListener = 906 new ZoomButtonsController.OnZoomListener() { 907 908 public void onVisibilityChanged(boolean visible) { 909 if (visible) { 910 switchOutDrawHistory(); 911 // Bring back the hidden zoom controls. 912 mZoomButtonsController.getZoomControls().setVisibility( 913 View.VISIBLE); 914 updateZoomButtonsEnabled(); 915 } 916 } 917 918 public void onZoom(boolean zoomIn) { 919 if (zoomIn) { 920 zoomIn(); 921 } else { 922 zoomOut(); 923 } 924 925 updateZoomButtonsEnabled(); 926 } 927 }; 928 929 /** 930 * Construct a new WebView with a Context object. 931 * @param context A Context object used to access application assets. 932 */ 933 public WebView(Context context) { 934 this(context, null); 935 } 936 937 /** 938 * Construct a new WebView with layout parameters. 939 * @param context A Context object used to access application assets. 940 * @param attrs An AttributeSet passed to our parent. 941 */ 942 public WebView(Context context, AttributeSet attrs) { 943 this(context, attrs, com.android.internal.R.attr.webViewStyle); 944 } 945 946 /** 947 * Construct a new WebView with layout parameters and a default style. 948 * @param context A Context object used to access application assets. 949 * @param attrs An AttributeSet passed to our parent. 950 * @param defStyle The default style resource ID. 951 */ 952 public WebView(Context context, AttributeSet attrs, int defStyle) { 953 this(context, attrs, defStyle, null); 954 } 955 956 /** 957 * Construct a new WebView with layout parameters, a default style and a set 958 * of custom Javscript interfaces to be added to the WebView at initialization 959 * time. This guarantees that these interfaces will be available when the JS 960 * context is initialized. 961 * @param context A Context object used to access application assets. 962 * @param attrs An AttributeSet passed to our parent. 963 * @param defStyle The default style resource ID. 964 * @param javascriptInterfaces is a Map of intareface names, as keys, and 965 * object implementing those interfaces, as values. 966 * @hide pending API council approval. 967 */ 968 protected WebView(Context context, AttributeSet attrs, int defStyle, 969 Map<String, Object> javascriptInterfaces) { 970 super(context, attrs, defStyle); 971 init(); 972 973 mCallbackProxy = new CallbackProxy(context, this); 974 mViewManager = new ViewManager(this); 975 mWebViewCore = new WebViewCore(context, this, mCallbackProxy, javascriptInterfaces); 976 mDatabase = WebViewDatabase.getInstance(context); 977 mScroller = new OverScroller(context); 978 979 updateMultiTouchSupport(context); 980 } 981 982 void updateMultiTouchSupport(Context context) { 983 WebSettings settings = getSettings(); 984 final PackageManager pm = context.getPackageManager(); 985 mSupportMultiTouch = pm.hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH) 986 && settings.supportZoom() && settings.getBuiltInZoomControls(); 987 mAllowPanAndScale = pm.hasSystemFeature( 988 PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT); 989 if (mSupportMultiTouch && (mScaleDetector == null)) { 990 mScaleDetector = new ScaleGestureDetector(context, 991 new ScaleDetectorListener()); 992 } else if (!mSupportMultiTouch && (mScaleDetector != null)) { 993 mScaleDetector = null; 994 } 995 } 996 997 private void updateZoomButtonsEnabled() { 998 if (mZoomButtonsController == null) return; 999 boolean canZoomIn = mActualScale < mMaxZoomScale; 1000 boolean canZoomOut = mActualScale > mMinZoomScale && !mInZoomOverview; 1001 if (!canZoomIn && !canZoomOut) { 1002 // Hide the zoom in and out buttons, as well as the fit to page 1003 // button, if the page cannot zoom 1004 mZoomButtonsController.getZoomControls().setVisibility(View.GONE); 1005 } else { 1006 // Set each one individually, as a page may be able to zoom in 1007 // or out. 1008 mZoomButtonsController.setZoomInEnabled(canZoomIn); 1009 mZoomButtonsController.setZoomOutEnabled(canZoomOut); 1010 } 1011 } 1012 1013 private void init() { 1014 setWillNotDraw(false); 1015 setFocusable(true); 1016 setFocusableInTouchMode(true); 1017 setClickable(true); 1018 setLongClickable(true); 1019 1020 final ViewConfiguration configuration = ViewConfiguration.get(getContext()); 1021 int slop = configuration.getScaledTouchSlop(); 1022 mTouchSlopSquare = slop * slop; 1023 mMinLockSnapReverseDistance = slop; 1024 slop = configuration.getScaledDoubleTapSlop(); 1025 mDoubleTapSlopSquare = slop * slop; 1026 final float density = getContext().getResources().getDisplayMetrics().density; 1027 // use one line height, 16 based on our current default font, for how 1028 // far we allow a touch be away from the edge of a link 1029 mNavSlop = (int) (16 * density); 1030 // density adjusted scale factors 1031 DEFAULT_SCALE_PERCENT = (int) (100 * density); 1032 mDefaultScale = density; 1033 mActualScale = density; 1034 mInvActualScale = 1 / density; 1035 mTextWrapScale = density; 1036 DEFAULT_MAX_ZOOM_SCALE = 4.0f * density; 1037 DEFAULT_MIN_ZOOM_SCALE = 0.25f * density; 1038 mMaxZoomScale = DEFAULT_MAX_ZOOM_SCALE; 1039 mMinZoomScale = DEFAULT_MIN_ZOOM_SCALE; 1040 mMaximumFling = configuration.getScaledMaximumFlingVelocity(); 1041 mOverscrollDistance = configuration.getScaledOverscrollDistance(); 1042 mOverflingDistance = configuration.getScaledOverflingDistance(); 1043 } 1044 1045 @Override 1046 public void setOverScrollMode(int mode) { 1047 super.setOverScrollMode(mode); 1048 if (mode != OVER_SCROLL_NEVER) { 1049 if (mEdgeGlowTop == null) { 1050 final Resources res = getContext().getResources(); 1051 final Drawable edge = res.getDrawable(R.drawable.overscroll_edge); 1052 final Drawable glow = res.getDrawable(R.drawable.overscroll_glow); 1053 mEdgeGlowTop = new EdgeGlow(edge, glow); 1054 mEdgeGlowBottom = new EdgeGlow(edge, glow); 1055 mEdgeGlowLeft = new EdgeGlow(edge, glow); 1056 mEdgeGlowRight = new EdgeGlow(edge, glow); 1057 } 1058 } else { 1059 mEdgeGlowTop = null; 1060 mEdgeGlowBottom = null; 1061 mEdgeGlowLeft = null; 1062 mEdgeGlowRight = null; 1063 } 1064 } 1065 1066 /* package */void updateDefaultZoomDensity(int zoomDensity) { 1067 final float density = getContext().getResources().getDisplayMetrics().density 1068 * 100 / zoomDensity; 1069 if (Math.abs(density - mDefaultScale) > 0.01) { 1070 float scaleFactor = density / mDefaultScale; 1071 // adjust the limits 1072 mNavSlop = (int) (16 * density); 1073 DEFAULT_SCALE_PERCENT = (int) (100 * density); 1074 DEFAULT_MAX_ZOOM_SCALE = 4.0f * density; 1075 DEFAULT_MIN_ZOOM_SCALE = 0.25f * density; 1076 mDefaultScale = density; 1077 mMaxZoomScale *= scaleFactor; 1078 mMinZoomScale *= scaleFactor; 1079 setNewZoomScale(mActualScale * scaleFactor, true, false); 1080 } 1081 } 1082 1083 /* package */ boolean onSavePassword(String schemePlusHost, String username, 1084 String password, final Message resumeMsg) { 1085 boolean rVal = false; 1086 if (resumeMsg == null) { 1087 // null resumeMsg implies saving password silently 1088 mDatabase.setUsernamePassword(schemePlusHost, username, password); 1089 } else { 1090 final Message remember = mPrivateHandler.obtainMessage( 1091 REMEMBER_PASSWORD); 1092 remember.getData().putString("host", schemePlusHost); 1093 remember.getData().putString("username", username); 1094 remember.getData().putString("password", password); 1095 remember.obj = resumeMsg; 1096 1097 final Message neverRemember = mPrivateHandler.obtainMessage( 1098 NEVER_REMEMBER_PASSWORD); 1099 neverRemember.getData().putString("host", schemePlusHost); 1100 neverRemember.getData().putString("username", username); 1101 neverRemember.getData().putString("password", password); 1102 neverRemember.obj = resumeMsg; 1103 1104 new AlertDialog.Builder(getContext()) 1105 .setTitle(com.android.internal.R.string.save_password_label) 1106 .setMessage(com.android.internal.R.string.save_password_message) 1107 .setPositiveButton(com.android.internal.R.string.save_password_notnow, 1108 new DialogInterface.OnClickListener() { 1109 public void onClick(DialogInterface dialog, int which) { 1110 resumeMsg.sendToTarget(); 1111 } 1112 }) 1113 .setNeutralButton(com.android.internal.R.string.save_password_remember, 1114 new DialogInterface.OnClickListener() { 1115 public void onClick(DialogInterface dialog, int which) { 1116 remember.sendToTarget(); 1117 } 1118 }) 1119 .setNegativeButton(com.android.internal.R.string.save_password_never, 1120 new DialogInterface.OnClickListener() { 1121 public void onClick(DialogInterface dialog, int which) { 1122 neverRemember.sendToTarget(); 1123 } 1124 }) 1125 .setOnCancelListener(new OnCancelListener() { 1126 public void onCancel(DialogInterface dialog) { 1127 resumeMsg.sendToTarget(); 1128 } 1129 }).show(); 1130 // Return true so that WebViewCore will pause while the dialog is 1131 // up. 1132 rVal = true; 1133 } 1134 return rVal; 1135 } 1136 1137 @Override 1138 public void setScrollBarStyle(int style) { 1139 if (style == View.SCROLLBARS_INSIDE_INSET 1140 || style == View.SCROLLBARS_OUTSIDE_INSET) { 1141 mOverlayHorizontalScrollbar = mOverlayVerticalScrollbar = false; 1142 } else { 1143 mOverlayHorizontalScrollbar = mOverlayVerticalScrollbar = true; 1144 } 1145 super.setScrollBarStyle(style); 1146 } 1147 1148 /** 1149 * Specify whether the horizontal scrollbar has overlay style. 1150 * @param overlay TRUE if horizontal scrollbar should have overlay style. 1151 */ 1152 public void setHorizontalScrollbarOverlay(boolean overlay) { 1153 mOverlayHorizontalScrollbar = overlay; 1154 } 1155 1156 /** 1157 * Specify whether the vertical scrollbar has overlay style. 1158 * @param overlay TRUE if vertical scrollbar should have overlay style. 1159 */ 1160 public void setVerticalScrollbarOverlay(boolean overlay) { 1161 mOverlayVerticalScrollbar = overlay; 1162 } 1163 1164 /** 1165 * Return whether horizontal scrollbar has overlay style 1166 * @return TRUE if horizontal scrollbar has overlay style. 1167 */ 1168 public boolean overlayHorizontalScrollbar() { 1169 return mOverlayHorizontalScrollbar; 1170 } 1171 1172 /** 1173 * Return whether vertical scrollbar has overlay style 1174 * @return TRUE if vertical scrollbar has overlay style. 1175 */ 1176 public boolean overlayVerticalScrollbar() { 1177 return mOverlayVerticalScrollbar; 1178 } 1179 1180 /* 1181 * Return the width of the view where the content of WebView should render 1182 * to. 1183 * Note: this can be called from WebCoreThread. 1184 */ 1185 /* package */ int getViewWidth() { 1186 if (!isVerticalScrollBarEnabled() || mOverlayVerticalScrollbar) { 1187 return getWidth(); 1188 } else { 1189 return getWidth() - getVerticalScrollbarWidth(); 1190 } 1191 } 1192 1193 /* 1194 * returns the height of the titlebarview (if any). Does not care about 1195 * scrolling 1196 */ 1197 private int getTitleHeight() { 1198 return mTitleBar != null ? mTitleBar.getHeight() : 0; 1199 } 1200 1201 /* 1202 * Return the amount of the titlebarview (if any) that is visible 1203 */ 1204 private int getVisibleTitleHeight() { 1205 // need to restrict mScrollY due to over scroll 1206 return Math.max(getTitleHeight() - Math.max(0, mScrollY), 0); 1207 } 1208 1209 /* 1210 * Return the height of the view where the content of WebView should render 1211 * to. Note that this excludes mTitleBar, if there is one. 1212 * Note: this can be called from WebCoreThread. 1213 */ 1214 /* package */ int getViewHeight() { 1215 return getViewHeightWithTitle() - getVisibleTitleHeight(); 1216 } 1217 1218 private int getViewHeightWithTitle() { 1219 int height = getHeight(); 1220 if (isHorizontalScrollBarEnabled() && !mOverlayHorizontalScrollbar) { 1221 height -= getHorizontalScrollbarHeight(); 1222 } 1223 return height; 1224 } 1225 1226 /** 1227 * @return The SSL certificate for the main top-level page or null if 1228 * there is no certificate (the site is not secure). 1229 */ 1230 public SslCertificate getCertificate() { 1231 return mCertificate; 1232 } 1233 1234 /** 1235 * Sets the SSL certificate for the main top-level page. 1236 */ 1237 public void setCertificate(SslCertificate certificate) { 1238 if (DebugFlags.WEB_VIEW) { 1239 Log.v(LOGTAG, "setCertificate=" + certificate); 1240 } 1241 // here, the certificate can be null (if the site is not secure) 1242 mCertificate = certificate; 1243 } 1244 1245 //------------------------------------------------------------------------- 1246 // Methods called by activity 1247 //------------------------------------------------------------------------- 1248 1249 /** 1250 * Save the username and password for a particular host in the WebView's 1251 * internal database. 1252 * @param host The host that required the credentials. 1253 * @param username The username for the given host. 1254 * @param password The password for the given host. 1255 */ 1256 public void savePassword(String host, String username, String password) { 1257 mDatabase.setUsernamePassword(host, username, password); 1258 } 1259 1260 /** 1261 * Set the HTTP authentication credentials for a given host and realm. 1262 * 1263 * @param host The host for the credentials. 1264 * @param realm The realm for the credentials. 1265 * @param username The username for the password. If it is null, it means 1266 * password can't be saved. 1267 * @param password The password 1268 */ 1269 public void setHttpAuthUsernamePassword(String host, String realm, 1270 String username, String password) { 1271 mDatabase.setHttpAuthUsernamePassword(host, realm, username, password); 1272 } 1273 1274 /** 1275 * Retrieve the HTTP authentication username and password for a given 1276 * host & realm pair 1277 * 1278 * @param host The host for which the credentials apply. 1279 * @param realm The realm for which the credentials apply. 1280 * @return String[] if found, String[0] is username, which can be null and 1281 * String[1] is password. Return null if it can't find anything. 1282 */ 1283 public String[] getHttpAuthUsernamePassword(String host, String realm) { 1284 return mDatabase.getHttpAuthUsernamePassword(host, realm); 1285 } 1286 1287 private void clearHelpers() { 1288 clearTextEntry(false); 1289 selectionDone(); 1290 } 1291 1292 /** 1293 * Destroy the internal state of the WebView. This method should be called 1294 * after the WebView has been removed from the view system. No other 1295 * methods may be called on a WebView after destroy. 1296 */ 1297 public void destroy() { 1298 clearHelpers(); 1299 if (mWebViewCore != null) { 1300 // Set the handlers to null before destroying WebViewCore so no 1301 // more messages will be posted. 1302 mCallbackProxy.setWebViewClient(null); 1303 mCallbackProxy.setWebChromeClient(null); 1304 // Tell WebViewCore to destroy itself 1305 synchronized (this) { 1306 WebViewCore webViewCore = mWebViewCore; 1307 mWebViewCore = null; // prevent using partial webViewCore 1308 webViewCore.destroy(); 1309 } 1310 // Remove any pending messages that might not be serviced yet. 1311 mPrivateHandler.removeCallbacksAndMessages(null); 1312 mCallbackProxy.removeCallbacksAndMessages(null); 1313 // Wake up the WebCore thread just in case it is waiting for a 1314 // javascript dialog. 1315 synchronized (mCallbackProxy) { 1316 mCallbackProxy.notify(); 1317 } 1318 } 1319 if (mNativeClass != 0) { 1320 nativeDestroy(); 1321 mNativeClass = 0; 1322 } 1323 } 1324 1325 /** 1326 * Enables platform notifications of data state and proxy changes. 1327 */ 1328 public static void enablePlatformNotifications() { 1329 Network.enablePlatformNotifications(); 1330 } 1331 1332 /** 1333 * If platform notifications are enabled, this should be called 1334 * from the Activity's onPause() or onStop(). 1335 */ 1336 public static void disablePlatformNotifications() { 1337 Network.disablePlatformNotifications(); 1338 } 1339 1340 /** 1341 * Sets JavaScript engine flags. 1342 * 1343 * @param flags JS engine flags in a String 1344 * 1345 * @hide pending API solidification 1346 */ 1347 public void setJsFlags(String flags) { 1348 mWebViewCore.sendMessage(EventHub.SET_JS_FLAGS, flags); 1349 } 1350 1351 /** 1352 * Inform WebView of the network state. This is used to set 1353 * the javascript property window.navigator.isOnline and 1354 * generates the online/offline event as specified in HTML5, sec. 5.7.7 1355 * @param networkUp boolean indicating if network is available 1356 */ 1357 public void setNetworkAvailable(boolean networkUp) { 1358 mWebViewCore.sendMessage(EventHub.SET_NETWORK_STATE, 1359 networkUp ? 1 : 0, 0); 1360 } 1361 1362 /** 1363 * Inform WebView about the current network type. 1364 * {@hide} 1365 */ 1366 public void setNetworkType(String type, String subtype) { 1367 Map<String, String> map = new HashMap<String, String>(); 1368 map.put("type", type); 1369 map.put("subtype", subtype); 1370 mWebViewCore.sendMessage(EventHub.SET_NETWORK_TYPE, map); 1371 } 1372 /** 1373 * Save the state of this WebView used in 1374 * {@link android.app.Activity#onSaveInstanceState}. Please note that this 1375 * method no longer stores the display data for this WebView. The previous 1376 * behavior could potentially leak files if {@link #restoreState} was never 1377 * called. See {@link #savePicture} and {@link #restorePicture} for saving 1378 * and restoring the display data. 1379 * @param outState The Bundle to store the WebView state. 1380 * @return The same copy of the back/forward list used to save the state. If 1381 * saveState fails, the returned list will be null. 1382 * @see #savePicture 1383 * @see #restorePicture 1384 */ 1385 public WebBackForwardList saveState(Bundle outState) { 1386 if (outState == null) { 1387 return null; 1388 } 1389 // We grab a copy of the back/forward list because a client of WebView 1390 // may have invalidated the history list by calling clearHistory. 1391 WebBackForwardList list = copyBackForwardList(); 1392 final int currentIndex = list.getCurrentIndex(); 1393 final int size = list.getSize(); 1394 // We should fail saving the state if the list is empty or the index is 1395 // not in a valid range. 1396 if (currentIndex < 0 || currentIndex >= size || size == 0) { 1397 return null; 1398 } 1399 outState.putInt("index", currentIndex); 1400 // FIXME: This should just be a byte[][] instead of ArrayList but 1401 // Parcel.java does not have the code to handle multi-dimensional 1402 // arrays. 1403 ArrayList<byte[]> history = new ArrayList<byte[]>(size); 1404 for (int i = 0; i < size; i++) { 1405 WebHistoryItem item = list.getItemAtIndex(i); 1406 if (null == item) { 1407 // FIXME: this shouldn't happen 1408 // need to determine how item got set to null 1409 Log.w(LOGTAG, "saveState: Unexpected null history item."); 1410 return null; 1411 } 1412 byte[] data = item.getFlattenedData(); 1413 if (data == null) { 1414 // It would be very odd to not have any data for a given history 1415 // item. And we will fail to rebuild the history list without 1416 // flattened data. 1417 return null; 1418 } 1419 history.add(data); 1420 } 1421 outState.putSerializable("history", history); 1422 if (mCertificate != null) { 1423 outState.putBundle("certificate", 1424 SslCertificate.saveState(mCertificate)); 1425 } 1426 return list; 1427 } 1428 1429 /** 1430 * Save the current display data to the Bundle given. Used in conjunction 1431 * with {@link #saveState}. 1432 * @param b A Bundle to store the display data. 1433 * @param dest The file to store the serialized picture data. Will be 1434 * overwritten with this WebView's picture data. 1435 * @return True if the picture was successfully saved. 1436 */ 1437 public boolean savePicture(Bundle b, final File dest) { 1438 if (dest == null || b == null) { 1439 return false; 1440 } 1441 final Picture p = capturePicture(); 1442 // Use a temporary file while writing to ensure the destination file 1443 // contains valid data. 1444 final File temp = new File(dest.getPath() + ".writing"); 1445 new Thread(new Runnable() { 1446 public void run() { 1447 FileOutputStream out = null; 1448 try { 1449 out = new FileOutputStream(temp); 1450 p.writeToStream(out); 1451 // Writing the picture succeeded, rename the temporary file 1452 // to the destination. 1453 temp.renameTo(dest); 1454 } catch (Exception e) { 1455 // too late to do anything about it. 1456 } finally { 1457 if (out != null) { 1458 try { 1459 out.close(); 1460 } catch (Exception e) { 1461 // Can't do anything about that 1462 } 1463 } 1464 temp.delete(); 1465 } 1466 } 1467 }).start(); 1468 // now update the bundle 1469 b.putInt("scrollX", mScrollX); 1470 b.putInt("scrollY", mScrollY); 1471 b.putFloat("scale", mActualScale); 1472 b.putFloat("textwrapScale", mTextWrapScale); 1473 b.putBoolean("overview", mInZoomOverview); 1474 return true; 1475 } 1476 1477 private void restoreHistoryPictureFields(Picture p, Bundle b) { 1478 int sx = b.getInt("scrollX", 0); 1479 int sy = b.getInt("scrollY", 0); 1480 float scale = b.getFloat("scale", 1.0f); 1481 mDrawHistory = true; 1482 mHistoryPicture = p; 1483 mScrollX = sx; 1484 mScrollY = sy; 1485 mHistoryWidth = Math.round(p.getWidth() * scale); 1486 mHistoryHeight = Math.round(p.getHeight() * scale); 1487 // as getWidth() / getHeight() of the view are not available yet, set up 1488 // mActualScale, so that when onSizeChanged() is called, the rest will 1489 // be set correctly 1490 mActualScale = scale; 1491 mInvActualScale = 1 / scale; 1492 mTextWrapScale = b.getFloat("textwrapScale", scale); 1493 mInZoomOverview = b.getBoolean("overview"); 1494 invalidate(); 1495 } 1496 1497 /** 1498 * Restore the display data that was save in {@link #savePicture}. Used in 1499 * conjunction with {@link #restoreState}. 1500 * @param b A Bundle containing the saved display data. 1501 * @param src The file where the picture data was stored. 1502 * @return True if the picture was successfully restored. 1503 */ 1504 public boolean restorePicture(Bundle b, File src) { 1505 if (src == null || b == null) { 1506 return false; 1507 } 1508 if (!src.exists()) { 1509 return false; 1510 } 1511 try { 1512 final FileInputStream in = new FileInputStream(src); 1513 final Bundle copy = new Bundle(b); 1514 new Thread(new Runnable() { 1515 public void run() { 1516 try { 1517 final Picture p = Picture.createFromStream(in); 1518 if (p != null) { 1519 // Post a runnable on the main thread to update the 1520 // history picture fields. 1521 mPrivateHandler.post(new Runnable() { 1522 public void run() { 1523 restoreHistoryPictureFields(p, copy); 1524 } 1525 }); 1526 } 1527 } finally { 1528 try { 1529 in.close(); 1530 } catch (Exception e) { 1531 // Nothing we can do now. 1532 } 1533 } 1534 } 1535 }).start(); 1536 } catch (FileNotFoundException e){ 1537 e.printStackTrace(); 1538 } 1539 return true; 1540 } 1541 1542 /** 1543 * Restore the state of this WebView from the given map used in 1544 * {@link android.app.Activity#onRestoreInstanceState}. This method should 1545 * be called to restore the state of the WebView before using the object. If 1546 * it is called after the WebView has had a chance to build state (load 1547 * pages, create a back/forward list, etc.) there may be undesirable 1548 * side-effects. Please note that this method no longer restores the 1549 * display data for this WebView. See {@link #savePicture} and {@link 1550 * #restorePicture} for saving and restoring the display data. 1551 * @param inState The incoming Bundle of state. 1552 * @return The restored back/forward list or null if restoreState failed. 1553 * @see #savePicture 1554 * @see #restorePicture 1555 */ 1556 public WebBackForwardList restoreState(Bundle inState) { 1557 WebBackForwardList returnList = null; 1558 if (inState == null) { 1559 return returnList; 1560 } 1561 if (inState.containsKey("index") && inState.containsKey("history")) { 1562 mCertificate = SslCertificate.restoreState( 1563 inState.getBundle("certificate")); 1564 1565 final WebBackForwardList list = mCallbackProxy.getBackForwardList(); 1566 final int index = inState.getInt("index"); 1567 // We can't use a clone of the list because we need to modify the 1568 // shared copy, so synchronize instead to prevent concurrent 1569 // modifications. 1570 synchronized (list) { 1571 final List<byte[]> history = 1572 (List<byte[]>) inState.getSerializable("history"); 1573 final int size = history.size(); 1574 // Check the index bounds so we don't crash in native code while 1575 // restoring the history index. 1576 if (index < 0 || index >= size) { 1577 return null; 1578 } 1579 for (int i = 0; i < size; i++) { 1580 byte[] data = history.remove(0); 1581 if (data == null) { 1582 // If we somehow have null data, we cannot reconstruct 1583 // the item and thus our history list cannot be rebuilt. 1584 return null; 1585 } 1586 WebHistoryItem item = new WebHistoryItem(data); 1587 list.addHistoryItem(item); 1588 } 1589 // Grab the most recent copy to return to the caller. 1590 returnList = copyBackForwardList(); 1591 // Update the copy to have the correct index. 1592 returnList.setCurrentIndex(index); 1593 } 1594 // Remove all pending messages because we are restoring previous 1595 // state. 1596 mWebViewCore.removeMessages(); 1597 // Send a restore state message. 1598 mWebViewCore.sendMessage(EventHub.RESTORE_STATE, index); 1599 } 1600 return returnList; 1601 } 1602 1603 /** 1604 * Load the given url with the extra headers. 1605 * @param url The url of the resource to load. 1606 * @param extraHeaders The extra headers sent with this url. This should not 1607 * include the common headers like "user-agent". If it does, it 1608 * will be replaced by the intrinsic value of the WebView. 1609 */ 1610 public void loadUrl(String url, Map<String, String> extraHeaders) { 1611 switchOutDrawHistory(); 1612 WebViewCore.GetUrlData arg = new WebViewCore.GetUrlData(); 1613 arg.mUrl = url; 1614 arg.mExtraHeaders = extraHeaders; 1615 mWebViewCore.sendMessage(EventHub.LOAD_URL, arg); 1616 clearHelpers(); 1617 } 1618 1619 /** 1620 * Load the given url. 1621 * @param url The url of the resource to load. 1622 */ 1623 public void loadUrl(String url) { 1624 if (url == null) { 1625 return; 1626 } 1627 loadUrl(url, null); 1628 } 1629 1630 /** 1631 * Load the url with postData using "POST" method into the WebView. If url 1632 * is not a network url, it will be loaded with {link 1633 * {@link #loadUrl(String)} instead. 1634 * 1635 * @param url The url of the resource to load. 1636 * @param postData The data will be passed to "POST" request. 1637 */ 1638 public void postUrl(String url, byte[] postData) { 1639 if (URLUtil.isNetworkUrl(url)) { 1640 switchOutDrawHistory(); 1641 WebViewCore.PostUrlData arg = new WebViewCore.PostUrlData(); 1642 arg.mUrl = url; 1643 arg.mPostData = postData; 1644 mWebViewCore.sendMessage(EventHub.POST_URL, arg); 1645 clearHelpers(); 1646 } else { 1647 loadUrl(url); 1648 } 1649 } 1650 1651 /** 1652 * Load the given data into the WebView. This will load the data into 1653 * WebView using the data: scheme. Content loaded through this mechanism 1654 * does not have the ability to load content from the network. 1655 * @param data A String of data in the given encoding. The date must 1656 * be URI-escaped -- '#', '%', '\', '?' should be replaced by %23, %25, 1657 * %27, %3f respectively. 1658 * @param mimeType The MIMEType of the data. i.e. text/html, image/jpeg 1659 * @param encoding The encoding of the data. i.e. utf-8, base64 1660 */ 1661 public void loadData(String data, String mimeType, String encoding) { 1662 loadUrl("data:" + mimeType + ";" + encoding + "," + data); 1663 } 1664 1665 /** 1666 * Load the given data into the WebView, use the provided URL as the base 1667 * URL for the content. The base URL is the URL that represents the page 1668 * that is loaded through this interface. As such, it is used to resolve any 1669 * relative URLs. The historyUrl is used for the history entry. 1670 * <p> 1671 * Note for post 1.0. Due to the change in the WebKit, the access to asset 1672 * files through "file:///android_asset/" for the sub resources is more 1673 * restricted. If you provide null or empty string as baseUrl, you won't be 1674 * able to access asset files. If the baseUrl is anything other than 1675 * http(s)/ftp(s)/about/javascript as scheme, you can access asset files for 1676 * sub resources. 1677 * 1678 * @param baseUrl Url to resolve relative paths with, if null defaults to 1679 * "about:blank" 1680 * @param data A String of data in the given encoding. 1681 * @param mimeType The MIMEType of the data. i.e. text/html. If null, 1682 * defaults to "text/html" 1683 * @param encoding The encoding of the data. i.e. utf-8, us-ascii 1684 * @param historyUrl URL to use as the history entry. Can be null. 1685 */ 1686 public void loadDataWithBaseURL(String baseUrl, String data, 1687 String mimeType, String encoding, String historyUrl) { 1688 1689 if (baseUrl != null && baseUrl.toLowerCase().startsWith("data:")) { 1690 loadData(data, mimeType, encoding); 1691 return; 1692 } 1693 switchOutDrawHistory(); 1694 WebViewCore.BaseUrlData arg = new WebViewCore.BaseUrlData(); 1695 arg.mBaseUrl = baseUrl; 1696 arg.mData = data; 1697 arg.mMimeType = mimeType; 1698 arg.mEncoding = encoding; 1699 arg.mHistoryUrl = historyUrl; 1700 mWebViewCore.sendMessage(EventHub.LOAD_DATA, arg); 1701 clearHelpers(); 1702 } 1703 1704 /** 1705 * Stop the current load. 1706 */ 1707 public void stopLoading() { 1708 // TODO: should we clear all the messages in the queue before sending 1709 // STOP_LOADING? 1710 switchOutDrawHistory(); 1711 mWebViewCore.sendMessage(EventHub.STOP_LOADING); 1712 } 1713 1714 /** 1715 * Reload the current url. 1716 */ 1717 public void reload() { 1718 clearHelpers(); 1719 switchOutDrawHistory(); 1720 mWebViewCore.sendMessage(EventHub.RELOAD); 1721 } 1722 1723 /** 1724 * Return true if this WebView has a back history item. 1725 * @return True iff this WebView has a back history item. 1726 */ 1727 public boolean canGoBack() { 1728 WebBackForwardList l = mCallbackProxy.getBackForwardList(); 1729 synchronized (l) { 1730 if (l.getClearPending()) { 1731 return false; 1732 } else { 1733 return l.getCurrentIndex() > 0; 1734 } 1735 } 1736 } 1737 1738 /** 1739 * Go back in the history of this WebView. 1740 */ 1741 public void goBack() { 1742 goBackOrForward(-1); 1743 } 1744 1745 /** 1746 * Return true if this WebView has a forward history item. 1747 * @return True iff this Webview has a forward history item. 1748 */ 1749 public boolean canGoForward() { 1750 WebBackForwardList l = mCallbackProxy.getBackForwardList(); 1751 synchronized (l) { 1752 if (l.getClearPending()) { 1753 return false; 1754 } else { 1755 return l.getCurrentIndex() < l.getSize() - 1; 1756 } 1757 } 1758 } 1759 1760 /** 1761 * Go forward in the history of this WebView. 1762 */ 1763 public void goForward() { 1764 goBackOrForward(1); 1765 } 1766 1767 /** 1768 * Return true if the page can go back or forward the given 1769 * number of steps. 1770 * @param steps The negative or positive number of steps to move the 1771 * history. 1772 */ 1773 public boolean canGoBackOrForward(int steps) { 1774 WebBackForwardList l = mCallbackProxy.getBackForwardList(); 1775 synchronized (l) { 1776 if (l.getClearPending()) { 1777 return false; 1778 } else { 1779 int newIndex = l.getCurrentIndex() + steps; 1780 return newIndex >= 0 && newIndex < l.getSize(); 1781 } 1782 } 1783 } 1784 1785 /** 1786 * Go to the history item that is the number of steps away from 1787 * the current item. Steps is negative if backward and positive 1788 * if forward. 1789 * @param steps The number of steps to take back or forward in the back 1790 * forward list. 1791 */ 1792 public void goBackOrForward(int steps) { 1793 goBackOrForward(steps, false); 1794 } 1795 1796 private void goBackOrForward(int steps, boolean ignoreSnapshot) { 1797 if (steps != 0) { 1798 clearHelpers(); 1799 mWebViewCore.sendMessage(EventHub.GO_BACK_FORWARD, steps, 1800 ignoreSnapshot ? 1 : 0); 1801 } 1802 } 1803 1804 private boolean extendScroll(int y) { 1805 int finalY = mScroller.getFinalY(); 1806 int newY = pinLocY(finalY + y); 1807 if (newY == finalY) return false; 1808 mScroller.setFinalY(newY); 1809 mScroller.extendDuration(computeDuration(0, y)); 1810 return true; 1811 } 1812 1813 /** 1814 * Scroll the contents of the view up by half the view size 1815 * @param top true to jump to the top of the page 1816 * @return true if the page was scrolled 1817 */ 1818 public boolean pageUp(boolean top) { 1819 if (mNativeClass == 0) { 1820 return false; 1821 } 1822 nativeClearCursor(); // start next trackball movement from page edge 1823 if (top) { 1824 // go to the top of the document 1825 return pinScrollTo(mScrollX, 0, true, 0); 1826 } 1827 // Page up 1828 int h = getHeight(); 1829 int y; 1830 if (h > 2 * PAGE_SCROLL_OVERLAP) { 1831 y = -h + PAGE_SCROLL_OVERLAP; 1832 } else { 1833 y = -h / 2; 1834 } 1835 mUserScroll = true; 1836 return mScroller.isFinished() ? pinScrollBy(0, y, true, 0) 1837 : extendScroll(y); 1838 } 1839 1840 /** 1841 * Scroll the contents of the view down by half the page size 1842 * @param bottom true to jump to bottom of page 1843 * @return true if the page was scrolled 1844 */ 1845 public boolean pageDown(boolean bottom) { 1846 if (mNativeClass == 0) { 1847 return false; 1848 } 1849 nativeClearCursor(); // start next trackball movement from page edge 1850 if (bottom) { 1851 return pinScrollTo(mScrollX, computeRealVerticalScrollRange(), true, 0); 1852 } 1853 // Page down. 1854 int h = getHeight(); 1855 int y; 1856 if (h > 2 * PAGE_SCROLL_OVERLAP) { 1857 y = h - PAGE_SCROLL_OVERLAP; 1858 } else { 1859 y = h / 2; 1860 } 1861 mUserScroll = true; 1862 return mScroller.isFinished() ? pinScrollBy(0, y, true, 0) 1863 : extendScroll(y); 1864 } 1865 1866 /** 1867 * Clear the view so that onDraw() will draw nothing but white background, 1868 * and onMeasure() will return 0 if MeasureSpec is not MeasureSpec.EXACTLY 1869 */ 1870 public void clearView() { 1871 mContentWidth = 0; 1872 mContentHeight = 0; 1873 mWebViewCore.sendMessage(EventHub.CLEAR_CONTENT); 1874 } 1875 1876 /** 1877 * Return a new picture that captures the current display of the webview. 1878 * This is a copy of the display, and will be unaffected if the webview 1879 * later loads a different URL. 1880 * 1881 * @return a picture containing the current contents of the view. Note this 1882 * picture is of the entire document, and is not restricted to the 1883 * bounds of the view. 1884 */ 1885 public Picture capturePicture() { 1886 if (null == mWebViewCore) return null; // check for out of memory tab 1887 return mWebViewCore.copyContentPicture(); 1888 } 1889 1890 /** 1891 * Return true if the browser is displaying a TextView for text input. 1892 */ 1893 private boolean inEditingMode() { 1894 return mWebTextView != null && mWebTextView.getParent() != null; 1895 } 1896 1897 /** 1898 * Remove the WebTextView. 1899 * @param disableFocusController If true, send a message to webkit 1900 * disabling the focus controller, so the caret stops blinking. 1901 */ 1902 private void clearTextEntry(boolean disableFocusController) { 1903 if (inEditingMode()) { 1904 mWebTextView.remove(); 1905 if (disableFocusController) { 1906 setFocusControllerInactive(); 1907 } 1908 } 1909 } 1910 1911 /** 1912 * Return the current scale of the WebView 1913 * @return The current scale. 1914 */ 1915 public float getScale() { 1916 return mActualScale; 1917 } 1918 1919 /** 1920 * Set the initial scale for the WebView. 0 means default. If 1921 * {@link WebSettings#getUseWideViewPort()} is true, it zooms out all the 1922 * way. Otherwise it starts with 100%. If initial scale is greater than 0, 1923 * WebView starts will this value as initial scale. 1924 * 1925 * @param scaleInPercent The initial scale in percent. 1926 */ 1927 public void setInitialScale(int scaleInPercent) { 1928 mInitialScaleInPercent = scaleInPercent; 1929 } 1930 1931 /** 1932 * Invoke the graphical zoom picker widget for this WebView. This will 1933 * result in the zoom widget appearing on the screen to control the zoom 1934 * level of this WebView. 1935 */ 1936 public void invokeZoomPicker() { 1937 if (!getSettings().supportZoom()) { 1938 Log.w(LOGTAG, "This WebView doesn't support zoom."); 1939 return; 1940 } 1941 clearTextEntry(false); 1942 if (getSettings().getBuiltInZoomControls()) { 1943 getZoomButtonsController().setVisible(true); 1944 } else { 1945 mPrivateHandler.removeCallbacks(mZoomControlRunnable); 1946 mPrivateHandler.postDelayed(mZoomControlRunnable, 1947 ZOOM_CONTROLS_TIMEOUT); 1948 } 1949 } 1950 1951 /** 1952 * Return a HitTestResult based on the current cursor node. If a HTML::a tag 1953 * is found and the anchor has a non-javascript url, the HitTestResult type 1954 * is set to SRC_ANCHOR_TYPE and the url is set in the "extra" field. If the 1955 * anchor does not have a url or if it is a javascript url, the type will 1956 * be UNKNOWN_TYPE and the url has to be retrieved through 1957 * {@link #requestFocusNodeHref} asynchronously. If a HTML::img tag is 1958 * found, the HitTestResult type is set to IMAGE_TYPE and the url is set in 1959 * the "extra" field. A type of 1960 * SRC_IMAGE_ANCHOR_TYPE indicates an anchor with a url that has an image as 1961 * a child node. If a phone number is found, the HitTestResult type is set 1962 * to PHONE_TYPE and the phone number is set in the "extra" field of 1963 * HitTestResult. If a map address is found, the HitTestResult type is set 1964 * to GEO_TYPE and the address is set in the "extra" field of HitTestResult. 1965 * If an email address is found, the HitTestResult type is set to EMAIL_TYPE 1966 * and the email is set in the "extra" field of HitTestResult. Otherwise, 1967 * HitTestResult type is set to UNKNOWN_TYPE. 1968 */ 1969 public HitTestResult getHitTestResult() { 1970 if (mNativeClass == 0) { 1971 return null; 1972 } 1973 1974 HitTestResult result = new HitTestResult(); 1975 if (nativeHasCursorNode()) { 1976 if (nativeCursorIsTextInput()) { 1977 result.setType(HitTestResult.EDIT_TEXT_TYPE); 1978 } else { 1979 String text = nativeCursorText(); 1980 if (text != null) { 1981 if (text.startsWith(SCHEME_TEL)) { 1982 result.setType(HitTestResult.PHONE_TYPE); 1983 result.setExtra(text.substring(SCHEME_TEL.length())); 1984 } else if (text.startsWith(SCHEME_MAILTO)) { 1985 result.setType(HitTestResult.EMAIL_TYPE); 1986 result.setExtra(text.substring(SCHEME_MAILTO.length())); 1987 } else if (text.startsWith(SCHEME_GEO)) { 1988 result.setType(HitTestResult.GEO_TYPE); 1989 result.setExtra(URLDecoder.decode(text 1990 .substring(SCHEME_GEO.length()))); 1991 } else if (nativeCursorIsAnchor()) { 1992 result.setType(HitTestResult.SRC_ANCHOR_TYPE); 1993 result.setExtra(text); 1994 } 1995 } 1996 } 1997 } 1998 int type = result.getType(); 1999 if (type == HitTestResult.UNKNOWN_TYPE 2000 || type == HitTestResult.SRC_ANCHOR_TYPE) { 2001 // Now check to see if it is an image. 2002 int contentX = viewToContentX((int) mLastTouchX + mScrollX); 2003 int contentY = viewToContentY((int) mLastTouchY + mScrollY); 2004 String text = nativeImageURI(contentX, contentY); 2005 if (text != null) { 2006 result.setType(type == HitTestResult.UNKNOWN_TYPE ? 2007 HitTestResult.IMAGE_TYPE : 2008 HitTestResult.SRC_IMAGE_ANCHOR_TYPE); 2009 result.setExtra(text); 2010 } 2011 } 2012 return result; 2013 } 2014 2015 // Called by JNI when the DOM has changed the focus. Clear the focus so 2016 // that new keys will go to the newly focused field 2017 private void domChangedFocus() { 2018 if (inEditingMode()) { 2019 mPrivateHandler.obtainMessage(DOM_FOCUS_CHANGED).sendToTarget(); 2020 } 2021 } 2022 /** 2023 * Request the href of an anchor element due to getFocusNodePath returning 2024 * "href." If hrefMsg is null, this method returns immediately and does not 2025 * dispatch hrefMsg to its target. 2026 * 2027 * @param hrefMsg This message will be dispatched with the result of the 2028 * request as the data member with "url" as key. The result can 2029 * be null. 2030 */ 2031 // FIXME: API change required to change the name of this function. We now 2032 // look at the cursor node, and not the focus node. Also, what is 2033 // getFocusNodePath? 2034 public void requestFocusNodeHref(Message hrefMsg) { 2035 if (hrefMsg == null || mNativeClass == 0) { 2036 return; 2037 } 2038 if (nativeCursorIsAnchor()) { 2039 mWebViewCore.sendMessage(EventHub.REQUEST_CURSOR_HREF, 2040 nativeCursorFramePointer(), nativeCursorNodePointer(), 2041 hrefMsg); 2042 } 2043 } 2044 2045 /** 2046 * Request the url of the image last touched by the user. msg will be sent 2047 * to its target with a String representing the url as its object. 2048 * 2049 * @param msg This message will be dispatched with the result of the request 2050 * as the data member with "url" as key. The result can be null. 2051 */ 2052 public void requestImageRef(Message msg) { 2053 if (0 == mNativeClass) return; // client isn't initialized 2054 int contentX = viewToContentX((int) mLastTouchX + mScrollX); 2055 int contentY = viewToContentY((int) mLastTouchY + mScrollY); 2056 String ref = nativeImageURI(contentX, contentY); 2057 Bundle data = msg.getData(); 2058 data.putString("url", ref); 2059 msg.setData(data); 2060 msg.sendToTarget(); 2061 } 2062 2063 private static int pinLoc(int x, int viewMax, int docMax) { 2064// Log.d(LOGTAG, "-- pinLoc " + x + " " + viewMax + " " + docMax); 2065 if (docMax < viewMax) { // the doc has room on the sides for "blank" 2066 // pin the short document to the top/left of the screen 2067 x = 0; 2068// Log.d(LOGTAG, "--- center " + x); 2069 } else if (x < 0) { 2070 x = 0; 2071// Log.d(LOGTAG, "--- zero"); 2072 } else if (x + viewMax > docMax) { 2073 x = docMax - viewMax; 2074// Log.d(LOGTAG, "--- pin " + x); 2075 } 2076 return x; 2077 } 2078 2079 // Expects x in view coordinates 2080 private int pinLocX(int x) { 2081 if (mInOverScrollMode) return x; 2082 return pinLoc(x, getViewWidth(), computeRealHorizontalScrollRange()); 2083 } 2084 2085 // Expects y in view coordinates 2086 private int pinLocY(int y) { 2087 if (mInOverScrollMode) return y; 2088 return pinLoc(y, getViewHeightWithTitle(), 2089 computeRealVerticalScrollRange() + getTitleHeight()); 2090 } 2091 2092 /** 2093 * A title bar which is embedded in this WebView, and scrolls along with it 2094 * vertically, but not horizontally. 2095 */ 2096 private View mTitleBar; 2097 2098 /** 2099 * Since we draw the title bar ourselves, we removed the shadow from the 2100 * browser's activity. We do want a shadow at the bottom of the title bar, 2101 * or at the top of the screen if the title bar is not visible. This 2102 * drawable serves that purpose. 2103 */ 2104 private Drawable mTitleShadow; 2105 2106 /** 2107 * Add or remove a title bar to be embedded into the WebView, and scroll 2108 * along with it vertically, while remaining in view horizontally. Pass 2109 * null to remove the title bar from the WebView, and return to drawing 2110 * the WebView normally without translating to account for the title bar. 2111 * @hide 2112 */ 2113 public void setEmbeddedTitleBar(View v) { 2114 if (mTitleBar == v) return; 2115 if (mTitleBar != null) { 2116 removeView(mTitleBar); 2117 } 2118 if (null != v) { 2119 addView(v, new AbsoluteLayout.LayoutParams( 2120 ViewGroup.LayoutParams.MATCH_PARENT, 2121 ViewGroup.LayoutParams.WRAP_CONTENT, 0, 0)); 2122 if (mTitleShadow == null) { 2123 mTitleShadow = (Drawable) mContext.getResources().getDrawable( 2124 com.android.internal.R.drawable.title_bar_shadow); 2125 } 2126 } 2127 mTitleBar = v; 2128 } 2129 2130 /** 2131 * Given a distance in view space, convert it to content space. Note: this 2132 * does not reflect translation, just scaling, so this should not be called 2133 * with coordinates, but should be called for dimensions like width or 2134 * height. 2135 */ 2136 private int viewToContentDimension(int d) { 2137 return Math.round(d * mInvActualScale); 2138 } 2139 2140 /** 2141 * Given an x coordinate in view space, convert it to content space. Also 2142 * may be used for absolute heights (such as for the WebTextView's 2143 * textSize, which is unaffected by the height of the title bar). 2144 */ 2145 /*package*/ int viewToContentX(int x) { 2146 return viewToContentDimension(x); 2147 } 2148 2149 /** 2150 * Given a y coordinate in view space, convert it to content space. 2151 * Takes into account the height of the title bar if there is one 2152 * embedded into the WebView. 2153 */ 2154 /*package*/ int viewToContentY(int y) { 2155 return viewToContentDimension(y - getTitleHeight()); 2156 } 2157 2158 /** 2159 * Given a x coordinate in view space, convert it to content space. 2160 * Returns the result as a float. 2161 */ 2162 private float viewToContentXf(int x) { 2163 return x * mInvActualScale; 2164 } 2165 2166 /** 2167 * Given a y coordinate in view space, convert it to content space. 2168 * Takes into account the height of the title bar if there is one 2169 * embedded into the WebView. Returns the result as a float. 2170 */ 2171 private float viewToContentYf(int y) { 2172 return (y - getTitleHeight()) * mInvActualScale; 2173 } 2174 2175 /** 2176 * Given a distance in content space, convert it to view space. Note: this 2177 * does not reflect translation, just scaling, so this should not be called 2178 * with coordinates, but should be called for dimensions like width or 2179 * height. 2180 */ 2181 /*package*/ int contentToViewDimension(int d) { 2182 return Math.round(d * mActualScale); 2183 } 2184 2185 /** 2186 * Given an x coordinate in content space, convert it to view 2187 * space. 2188 */ 2189 /*package*/ int contentToViewX(int x) { 2190 return contentToViewDimension(x); 2191 } 2192 2193 /** 2194 * Given a y coordinate in content space, convert it to view 2195 * space. Takes into account the height of the title bar. 2196 */ 2197 /*package*/ int contentToViewY(int y) { 2198 return contentToViewDimension(y) + getTitleHeight(); 2199 } 2200 2201 private Rect contentToViewRect(Rect x) { 2202 return new Rect(contentToViewX(x.left), contentToViewY(x.top), 2203 contentToViewX(x.right), contentToViewY(x.bottom)); 2204 } 2205 2206 /* To invalidate a rectangle in content coordinates, we need to transform 2207 the rect into view coordinates, so we can then call invalidate(...). 2208 2209 Normally, we would just call contentToView[XY](...), which eventually 2210 calls Math.round(coordinate * mActualScale). However, for invalidates, 2211 we need to account for the slop that occurs with antialiasing. To 2212 address that, we are a little more liberal in the size of the rect that 2213 we invalidate. 2214 2215 This liberal calculation calls floor() for the top/left, and ceil() for 2216 the bottom/right coordinates. This catches the possible extra pixels of 2217 antialiasing that we might have missed with just round(). 2218 */ 2219 2220 // Called by JNI to invalidate the View, given rectangle coordinates in 2221 // content space 2222 private void viewInvalidate(int l, int t, int r, int b) { 2223 final float scale = mActualScale; 2224 final int dy = getTitleHeight(); 2225 invalidate((int)Math.floor(l * scale), 2226 (int)Math.floor(t * scale) + dy, 2227 (int)Math.ceil(r * scale), 2228 (int)Math.ceil(b * scale) + dy); 2229 } 2230 2231 // Called by JNI to invalidate the View after a delay, given rectangle 2232 // coordinates in content space 2233 private void viewInvalidateDelayed(long delay, int l, int t, int r, int b) { 2234 final float scale = mActualScale; 2235 final int dy = getTitleHeight(); 2236 postInvalidateDelayed(delay, 2237 (int)Math.floor(l * scale), 2238 (int)Math.floor(t * scale) + dy, 2239 (int)Math.ceil(r * scale), 2240 (int)Math.ceil(b * scale) + dy); 2241 } 2242 2243 private void invalidateContentRect(Rect r) { 2244 viewInvalidate(r.left, r.top, r.right, r.bottom); 2245 } 2246 2247 // stop the scroll animation, and don't let a subsequent fling add 2248 // to the existing velocity 2249 private void abortAnimation() { 2250 mScroller.abortAnimation(); 2251 mLastVelocity = 0; 2252 } 2253 2254 /* call from webcoreview.draw(), so we're still executing in the UI thread 2255 */ 2256 private void recordNewContentSize(int w, int h, boolean updateLayout) { 2257 2258 // premature data from webkit, ignore 2259 if ((w | h) == 0) { 2260 return; 2261 } 2262 2263 // don't abort a scroll animation if we didn't change anything 2264 if (mContentWidth != w || mContentHeight != h) { 2265 // record new dimensions 2266 mContentWidth = w; 2267 mContentHeight = h; 2268 // If history Picture is drawn, don't update scroll. They will be 2269 // updated when we get out of that mode. 2270 if (!mDrawHistory) { 2271 // repin our scroll, taking into account the new content size 2272 int oldX = mScrollX; 2273 int oldY = mScrollY; 2274 mScrollX = pinLocX(mScrollX); 2275 mScrollY = pinLocY(mScrollY); 2276 if (oldX != mScrollX || oldY != mScrollY) { 2277 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 2278 } 2279 if (!mScroller.isFinished()) { 2280 // We are in the middle of a scroll. Repin the final scroll 2281 // position. 2282 mScroller.setFinalX(pinLocX(mScroller.getFinalX())); 2283 mScroller.setFinalY(pinLocY(mScroller.getFinalY())); 2284 } 2285 } 2286 } 2287 contentSizeChanged(updateLayout); 2288 } 2289 2290 private void setNewZoomScale(float scale, boolean updateTextWrapScale, 2291 boolean force) { 2292 if (scale < mMinZoomScale) { 2293 scale = mMinZoomScale; 2294 // set mInZoomOverview for non mobile sites 2295 if (scale < mDefaultScale) mInZoomOverview = true; 2296 } else if (scale > mMaxZoomScale) { 2297 scale = mMaxZoomScale; 2298 } 2299 if (updateTextWrapScale) { 2300 mTextWrapScale = scale; 2301 // reset mLastHeightSent to force VIEW_SIZE_CHANGED sent to WebKit 2302 mLastHeightSent = 0; 2303 } 2304 if (scale != mActualScale || force) { 2305 if (mDrawHistory) { 2306 // If history Picture is drawn, don't update scroll. They will 2307 // be updated when we get out of that mode. 2308 if (scale != mActualScale && !mPreviewZoomOnly) { 2309 mCallbackProxy.onScaleChanged(mActualScale, scale); 2310 } 2311 mActualScale = scale; 2312 mInvActualScale = 1 / scale; 2313 sendViewSizeZoom(); 2314 } else { 2315 // update our scroll so we don't appear to jump 2316 // i.e. keep the center of the doc in the center of the view 2317 2318 int oldX = mScrollX; 2319 int oldY = mScrollY; 2320 float ratio = scale * mInvActualScale; // old inverse 2321 float sx = ratio * oldX + (ratio - 1) * mZoomCenterX; 2322 float sy = ratio * oldY + (ratio - 1) 2323 * (mZoomCenterY - getTitleHeight()); 2324 2325 // now update our new scale and inverse 2326 if (scale != mActualScale && !mPreviewZoomOnly) { 2327 mCallbackProxy.onScaleChanged(mActualScale, scale); 2328 } 2329 mActualScale = scale; 2330 mInvActualScale = 1 / scale; 2331 2332 // Scale all the child views 2333 mViewManager.scaleAll(); 2334 2335 // as we don't have animation for scaling, don't do animation 2336 // for scrolling, as it causes weird intermediate state 2337 // pinScrollTo(Math.round(sx), Math.round(sy)); 2338 mScrollX = pinLocX(Math.round(sx)); 2339 mScrollY = pinLocY(Math.round(sy)); 2340 2341 // update webkit 2342 if (oldX != mScrollX || oldY != mScrollY) { 2343 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 2344 } else { 2345 // the scroll position is adjusted at the beginning of the 2346 // zoom animation. But we want to update the WebKit at the 2347 // end of the zoom animation. See comments in onScaleEnd(). 2348 sendOurVisibleRect(); 2349 } 2350 sendViewSizeZoom(); 2351 } 2352 } 2353 } 2354 2355 // Used to avoid sending many visible rect messages. 2356 private Rect mLastVisibleRectSent; 2357 private Rect mLastGlobalRect; 2358 2359 private Rect sendOurVisibleRect() { 2360 if (mPreviewZoomOnly) return mLastVisibleRectSent; 2361 2362 Rect rect = new Rect(); 2363 calcOurContentVisibleRect(rect); 2364 // Rect.equals() checks for null input. 2365 if (!rect.equals(mLastVisibleRectSent)) { 2366 Point pos = new Point(rect.left, rect.top); 2367 mWebViewCore.sendMessage(EventHub.SET_SCROLL_OFFSET, 2368 nativeMoveGeneration(), 0, pos); 2369 mLastVisibleRectSent = rect; 2370 } 2371 Rect globalRect = new Rect(); 2372 if (getGlobalVisibleRect(globalRect) 2373 && !globalRect.equals(mLastGlobalRect)) { 2374 if (DebugFlags.WEB_VIEW) { 2375 Log.v(LOGTAG, "sendOurVisibleRect=(" + globalRect.left + "," 2376 + globalRect.top + ",r=" + globalRect.right + ",b=" 2377 + globalRect.bottom); 2378 } 2379 // TODO: the global offset is only used by windowRect() 2380 // in ChromeClientAndroid ; other clients such as touch 2381 // and mouse events could return view + screen relative points. 2382 mWebViewCore.sendMessage(EventHub.SET_GLOBAL_BOUNDS, globalRect); 2383 mLastGlobalRect = globalRect; 2384 } 2385 return rect; 2386 } 2387 2388 // Sets r to be the visible rectangle of our webview in view coordinates 2389 private void calcOurVisibleRect(Rect r) { 2390 Point p = new Point(); 2391 getGlobalVisibleRect(r, p); 2392 r.offset(-p.x, -p.y); 2393 if (mFindIsUp) { 2394 r.bottom -= mFindHeight; 2395 } 2396 } 2397 2398 // Sets r to be our visible rectangle in content coordinates 2399 private void calcOurContentVisibleRect(Rect r) { 2400 calcOurVisibleRect(r); 2401 // since we might overscroll, pin the rect to the bounds of the content 2402 r.left = Math.max(viewToContentX(r.left), 0); 2403 // viewToContentY will remove the total height of the title bar. Add 2404 // the visible height back in to account for the fact that if the title 2405 // bar is partially visible, the part of the visible rect which is 2406 // displaying our content is displaced by that amount. 2407 r.top = Math.max(viewToContentY(r.top + getVisibleTitleHeight()), 0); 2408 r.right = Math.min(viewToContentX(r.right), mContentWidth); 2409 r.bottom = Math.min(viewToContentY(r.bottom), mContentHeight); 2410 } 2411 2412 // Sets r to be our visible rectangle in content coordinates. We use this 2413 // method on the native side to compute the position of the fixed layers. 2414 // Uses floating coordinates (necessary to correctly place elements when 2415 // the scale factor is not 1) 2416 private void calcOurContentVisibleRectF(RectF r) { 2417 Rect ri = new Rect(0,0,0,0); 2418 calcOurVisibleRect(ri); 2419 // pin the rect to the bounds of the content 2420 r.left = Math.max(viewToContentXf(ri.left), 0.0f); 2421 // viewToContentY will remove the total height of the title bar. Add 2422 // the visible height back in to account for the fact that if the title 2423 // bar is partially visible, the part of the visible rect which is 2424 // displaying our content is displaced by that amount. 2425 r.top = Math.max(viewToContentYf(ri.top + getVisibleTitleHeight()), 0.0f); 2426 r.right = Math.min(viewToContentXf(ri.right), (float)mContentWidth); 2427 r.bottom = Math.min(viewToContentYf(ri.bottom), (float)mContentHeight); 2428 } 2429 2430 static class ViewSizeData { 2431 int mWidth; 2432 int mHeight; 2433 int mTextWrapWidth; 2434 int mAnchorX; 2435 int mAnchorY; 2436 float mScale; 2437 boolean mIgnoreHeight; 2438 } 2439 2440 /** 2441 * Compute unzoomed width and height, and if they differ from the last 2442 * values we sent, send them to webkit (to be used has new viewport) 2443 * 2444 * @return true if new values were sent 2445 */ 2446 private boolean sendViewSizeZoom() { 2447 if (mPreviewZoomOnly) return false; 2448 2449 int viewWidth = getViewWidth(); 2450 int newWidth = Math.round(viewWidth * mInvActualScale); 2451 int newHeight = Math.round(getViewHeight() * mInvActualScale); 2452 /* 2453 * Because the native side may have already done a layout before the 2454 * View system was able to measure us, we have to send a height of 0 to 2455 * remove excess whitespace when we grow our width. This will trigger a 2456 * layout and a change in content size. This content size change will 2457 * mean that contentSizeChanged will either call this method directly or 2458 * indirectly from onSizeChanged. 2459 */ 2460 if (newWidth > mLastWidthSent && mWrapContent) { 2461 newHeight = 0; 2462 } 2463 // Avoid sending another message if the dimensions have not changed. 2464 if (newWidth != mLastWidthSent || newHeight != mLastHeightSent) { 2465 ViewSizeData data = new ViewSizeData(); 2466 data.mWidth = newWidth; 2467 data.mHeight = newHeight; 2468 data.mTextWrapWidth = Math.round(viewWidth / mTextWrapScale);; 2469 data.mScale = mActualScale; 2470 data.mIgnoreHeight = mZoomScale != 0 && !mHeightCanMeasure; 2471 data.mAnchorX = mAnchorX; 2472 data.mAnchorY = mAnchorY; 2473 mWebViewCore.sendMessage(EventHub.VIEW_SIZE_CHANGED, data); 2474 mLastWidthSent = newWidth; 2475 mLastHeightSent = newHeight; 2476 mAnchorX = mAnchorY = 0; 2477 return true; 2478 } 2479 return false; 2480 } 2481 2482 private int computeRealHorizontalScrollRange() { 2483 if (mDrawHistory) { 2484 return mHistoryWidth; 2485 } else if (mHorizontalScrollBarMode == SCROLLBAR_ALWAYSOFF 2486 && (mActualScale - mMinZoomScale <= MINIMUM_SCALE_INCREMENT)) { 2487 // only honor the scrollbar mode when it is at minimum zoom level 2488 return computeHorizontalScrollExtent(); 2489 } else { 2490 // to avoid rounding error caused unnecessary scrollbar, use floor 2491 return (int) Math.floor(mContentWidth * mActualScale); 2492 } 2493 } 2494 2495 @Override 2496 protected int computeHorizontalScrollRange() { 2497 int range = computeRealHorizontalScrollRange(); 2498 2499 // Adjust reported range if overscrolled to compress the scroll bars 2500 final int scrollX = mScrollX; 2501 final int overscrollRight = computeMaxScrollX(); 2502 if (scrollX < 0) { 2503 range -= scrollX; 2504 } else if (scrollX > overscrollRight) { 2505 range += scrollX - overscrollRight; 2506 } 2507 2508 return range; 2509 } 2510 2511 @Override 2512 protected int computeHorizontalScrollOffset() { 2513 return Math.max(mScrollX, 0); 2514 } 2515 2516 private int computeRealVerticalScrollRange() { 2517 if (mDrawHistory) { 2518 return mHistoryHeight; 2519 } else if (mVerticalScrollBarMode == SCROLLBAR_ALWAYSOFF 2520 && (mActualScale - mMinZoomScale <= MINIMUM_SCALE_INCREMENT)) { 2521 // only honor the scrollbar mode when it is at minimum zoom level 2522 return computeVerticalScrollExtent(); 2523 } else { 2524 // to avoid rounding error caused unnecessary scrollbar, use floor 2525 return (int) Math.floor(mContentHeight * mActualScale); 2526 } 2527 } 2528 2529 @Override 2530 protected int computeVerticalScrollRange() { 2531 int range = computeRealVerticalScrollRange(); 2532 2533 // Adjust reported range if overscrolled to compress the scroll bars 2534 final int scrollY = mScrollY; 2535 final int overscrollBottom = computeMaxScrollY(); 2536 if (scrollY < 0) { 2537 range -= scrollY; 2538 } else if (scrollY > overscrollBottom) { 2539 range += scrollY - overscrollBottom; 2540 } 2541 2542 return range; 2543 } 2544 2545 @Override 2546 protected int computeVerticalScrollOffset() { 2547 return Math.max(mScrollY - getTitleHeight(), 0); 2548 } 2549 2550 @Override 2551 protected int computeVerticalScrollExtent() { 2552 return getViewHeight(); 2553 } 2554 2555 /** @hide */ 2556 @Override 2557 protected void onDrawVerticalScrollBar(Canvas canvas, 2558 Drawable scrollBar, 2559 int l, int t, int r, int b) { 2560 if (mScrollY < 0) { 2561 t -= mScrollY; 2562 } 2563 scrollBar.setBounds(l, t + getVisibleTitleHeight(), r, b); 2564 scrollBar.draw(canvas); 2565 } 2566 2567 @Override 2568 protected void onOverScrolled(int scrollX, int scrollY, boolean clampedX, 2569 boolean clampedY) { 2570 mInOverScrollMode = false; 2571 int maxX = computeMaxScrollX(); 2572 if (maxX == 0) { 2573 // do not over scroll x if the page just fits the screen 2574 scrollX = pinLocX(scrollX); 2575 } else if (scrollX < 0 || scrollX > maxX) { 2576 mInOverScrollMode = true; 2577 } 2578 if (scrollY < 0 || scrollY > computeMaxScrollY()) { 2579 mInOverScrollMode = true; 2580 } 2581 2582 super.scrollTo(scrollX, scrollY); 2583 } 2584 2585 /** 2586 * Get the url for the current page. This is not always the same as the url 2587 * passed to WebViewClient.onPageStarted because although the load for 2588 * that url has begun, the current page may not have changed. 2589 * @return The url for the current page. 2590 */ 2591 public String getUrl() { 2592 WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem(); 2593 return h != null ? h.getUrl() : null; 2594 } 2595 2596 /** 2597 * Get the original url for the current page. This is not always the same 2598 * as the url passed to WebViewClient.onPageStarted because although the 2599 * load for that url has begun, the current page may not have changed. 2600 * Also, there may have been redirects resulting in a different url to that 2601 * originally requested. 2602 * @return The url that was originally requested for the current page. 2603 */ 2604 public String getOriginalUrl() { 2605 WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem(); 2606 return h != null ? h.getOriginalUrl() : null; 2607 } 2608 2609 /** 2610 * Get the title for the current page. This is the title of the current page 2611 * until WebViewClient.onReceivedTitle is called. 2612 * @return The title for the current page. 2613 */ 2614 public String getTitle() { 2615 WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem(); 2616 return h != null ? h.getTitle() : null; 2617 } 2618 2619 /** 2620 * Get the favicon for the current page. This is the favicon of the current 2621 * page until WebViewClient.onReceivedIcon is called. 2622 * @return The favicon for the current page. 2623 */ 2624 public Bitmap getFavicon() { 2625 WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem(); 2626 return h != null ? h.getFavicon() : null; 2627 } 2628 2629 /** 2630 * Get the touch icon url for the apple-touch-icon <link> element. 2631 * @hide 2632 */ 2633 public String getTouchIconUrl() { 2634 WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem(); 2635 return h != null ? h.getTouchIconUrl() : null; 2636 } 2637 2638 /** 2639 * Get the progress for the current page. 2640 * @return The progress for the current page between 0 and 100. 2641 */ 2642 public int getProgress() { 2643 return mCallbackProxy.getProgress(); 2644 } 2645 2646 /** 2647 * @return the height of the HTML content. 2648 */ 2649 public int getContentHeight() { 2650 return mContentHeight; 2651 } 2652 2653 /** 2654 * @return the width of the HTML content. 2655 * @hide 2656 */ 2657 public int getContentWidth() { 2658 return mContentWidth; 2659 } 2660 2661 /** 2662 * Pause all layout, parsing, and javascript timers for all webviews. This 2663 * is a global requests, not restricted to just this webview. This can be 2664 * useful if the application has been paused. 2665 */ 2666 public void pauseTimers() { 2667 mWebViewCore.sendMessage(EventHub.PAUSE_TIMERS); 2668 } 2669 2670 /** 2671 * Resume all layout, parsing, and javascript timers for all webviews. 2672 * This will resume dispatching all timers. 2673 */ 2674 public void resumeTimers() { 2675 mWebViewCore.sendMessage(EventHub.RESUME_TIMERS); 2676 } 2677 2678 /** 2679 * Call this to pause any extra processing associated with this view and 2680 * its associated DOM/plugins/javascript/etc. For example, if the view is 2681 * taken offscreen, this could be called to reduce unnecessary CPU and/or 2682 * network traffic. When the view is again "active", call onResume(). 2683 * 2684 * Note that this differs from pauseTimers(), which affects all views/DOMs 2685 * @hide 2686 */ 2687 public void onPause() { 2688 if (!mIsPaused) { 2689 mIsPaused = true; 2690 mWebViewCore.sendMessage(EventHub.ON_PAUSE); 2691 } 2692 } 2693 2694 /** 2695 * Call this to balanace a previous call to onPause() 2696 * @hide 2697 */ 2698 public void onResume() { 2699 if (mIsPaused) { 2700 mIsPaused = false; 2701 mWebViewCore.sendMessage(EventHub.ON_RESUME); 2702 } 2703 } 2704 2705 /** 2706 * Returns true if the view is paused, meaning onPause() was called. Calling 2707 * onResume() sets the paused state back to false. 2708 * @hide 2709 */ 2710 public boolean isPaused() { 2711 return mIsPaused; 2712 } 2713 2714 /** 2715 * Call this to inform the view that memory is low so that it can 2716 * free any available memory. 2717 */ 2718 public void freeMemory() { 2719 mWebViewCore.sendMessage(EventHub.FREE_MEMORY); 2720 } 2721 2722 /** 2723 * Clear the resource cache. Note that the cache is per-application, so 2724 * this will clear the cache for all WebViews used. 2725 * 2726 * @param includeDiskFiles If false, only the RAM cache is cleared. 2727 */ 2728 public void clearCache(boolean includeDiskFiles) { 2729 // Note: this really needs to be a static method as it clears cache for all 2730 // WebView. But we need mWebViewCore to send message to WebCore thread, so 2731 // we can't make this static. 2732 mWebViewCore.sendMessage(EventHub.CLEAR_CACHE, 2733 includeDiskFiles ? 1 : 0, 0); 2734 } 2735 2736 /** 2737 * Make sure that clearing the form data removes the adapter from the 2738 * currently focused textfield if there is one. 2739 */ 2740 public void clearFormData() { 2741 if (inEditingMode()) { 2742 AutoCompleteAdapter adapter = null; 2743 mWebTextView.setAdapterCustom(adapter); 2744 } 2745 } 2746 2747 /** 2748 * Tell the WebView to clear its internal back/forward list. 2749 */ 2750 public void clearHistory() { 2751 mCallbackProxy.getBackForwardList().setClearPending(); 2752 mWebViewCore.sendMessage(EventHub.CLEAR_HISTORY); 2753 } 2754 2755 /** 2756 * Clear the SSL preferences table stored in response to proceeding with SSL 2757 * certificate errors. 2758 */ 2759 public void clearSslPreferences() { 2760 mWebViewCore.sendMessage(EventHub.CLEAR_SSL_PREF_TABLE); 2761 } 2762 2763 /** 2764 * Return the WebBackForwardList for this WebView. This contains the 2765 * back/forward list for use in querying each item in the history stack. 2766 * This is a copy of the private WebBackForwardList so it contains only a 2767 * snapshot of the current state. Multiple calls to this method may return 2768 * different objects. The object returned from this method will not be 2769 * updated to reflect any new state. 2770 */ 2771 public WebBackForwardList copyBackForwardList() { 2772 return mCallbackProxy.getBackForwardList().clone(); 2773 } 2774 2775 /* 2776 * Highlight and scroll to the next occurance of String in findAll. 2777 * Wraps the page infinitely, and scrolls. Must be called after 2778 * calling findAll. 2779 * 2780 * @param forward Direction to search. 2781 */ 2782 public void findNext(boolean forward) { 2783 if (0 == mNativeClass) return; // client isn't initialized 2784 nativeFindNext(forward); 2785 } 2786 2787 /* 2788 * Find all instances of find on the page and highlight them. 2789 * @param find String to find. 2790 * @return int The number of occurances of the String "find" 2791 * that were found. 2792 */ 2793 public int findAll(String find) { 2794 if (0 == mNativeClass) return 0; // client isn't initialized 2795 int result = find != null ? nativeFindAll(find.toLowerCase(), 2796 find.toUpperCase()) : 0; 2797 invalidate(); 2798 mLastFind = find; 2799 return result; 2800 } 2801 2802 /** 2803 * @hide 2804 */ 2805 public void setFindIsUp(boolean isUp) { 2806 mFindIsUp = isUp; 2807 if (isUp) { 2808 recordNewContentSize(mContentWidth, mContentHeight + mFindHeight, 2809 false); 2810 } 2811 if (0 == mNativeClass) return; // client isn't initialized 2812 nativeSetFindIsUp(isUp); 2813 } 2814 2815 /** 2816 * @hide 2817 */ 2818 public int findIndex() { 2819 if (0 == mNativeClass) return -1; 2820 return nativeFindIndex(); 2821 } 2822 2823 // Used to know whether the find dialog is open. Affects whether 2824 // or not we draw the highlights for matches. 2825 private boolean mFindIsUp; 2826 2827 private int mFindHeight; 2828 // Keep track of the last string sent, so we can search again after an 2829 // orientation change or the dismissal of the soft keyboard. 2830 private String mLastFind; 2831 2832 /** 2833 * Return the first substring consisting of the address of a physical 2834 * location. Currently, only addresses in the United States are detected, 2835 * and consist of: 2836 * - a house number 2837 * - a street name 2838 * - a street type (Road, Circle, etc), either spelled out or abbreviated 2839 * - a city name 2840 * - a state or territory, either spelled out or two-letter abbr. 2841 * - an optional 5 digit or 9 digit zip code. 2842 * 2843 * All names must be correctly capitalized, and the zip code, if present, 2844 * must be valid for the state. The street type must be a standard USPS 2845 * spelling or abbreviation. The state or territory must also be spelled 2846 * or abbreviated using USPS standards. The house number may not exceed 2847 * five digits. 2848 * @param addr The string to search for addresses. 2849 * 2850 * @return the address, or if no address is found, return null. 2851 */ 2852 public static String findAddress(String addr) { 2853 return findAddress(addr, false); 2854 } 2855 2856 /** 2857 * @hide 2858 * Return the first substring consisting of the address of a physical 2859 * location. Currently, only addresses in the United States are detected, 2860 * and consist of: 2861 * - a house number 2862 * - a street name 2863 * - a street type (Road, Circle, etc), either spelled out or abbreviated 2864 * - a city name 2865 * - a state or territory, either spelled out or two-letter abbr. 2866 * - an optional 5 digit or 9 digit zip code. 2867 * 2868 * Names are optionally capitalized, and the zip code, if present, 2869 * must be valid for the state. The street type must be a standard USPS 2870 * spelling or abbreviation. The state or territory must also be spelled 2871 * or abbreviated using USPS standards. The house number may not exceed 2872 * five digits. 2873 * @param addr The string to search for addresses. 2874 * @param caseInsensitive addr Set to true to make search ignore case. 2875 * 2876 * @return the address, or if no address is found, return null. 2877 */ 2878 public static String findAddress(String addr, boolean caseInsensitive) { 2879 return WebViewCore.nativeFindAddress(addr, caseInsensitive); 2880 } 2881 2882 /* 2883 * Clear the highlighting surrounding text matches created by findAll. 2884 */ 2885 public void clearMatches() { 2886 mLastFind = ""; 2887 if (mNativeClass == 0) 2888 return; 2889 nativeSetFindIsEmpty(); 2890 invalidate(); 2891 } 2892 2893 /** 2894 * @hide 2895 */ 2896 public void notifyFindDialogDismissed() { 2897 if (mWebViewCore == null) { 2898 return; 2899 } 2900 clearMatches(); 2901 setFindIsUp(false); 2902 recordNewContentSize(mContentWidth, mContentHeight - mFindHeight, 2903 false); 2904 // Now that the dialog has been removed, ensure that we scroll to a 2905 // location that is not beyond the end of the page. 2906 pinScrollTo(mScrollX, mScrollY, false, 0); 2907 invalidate(); 2908 } 2909 2910 /** 2911 * @hide 2912 */ 2913 public void setFindDialogHeight(int height) { 2914 if (DebugFlags.WEB_VIEW) { 2915 Log.v(LOGTAG, "setFindDialogHeight height=" + height); 2916 } 2917 mFindHeight = height; 2918 } 2919 2920 /** 2921 * Query the document to see if it contains any image references. The 2922 * message object will be dispatched with arg1 being set to 1 if images 2923 * were found and 0 if the document does not reference any images. 2924 * @param response The message that will be dispatched with the result. 2925 */ 2926 public void documentHasImages(Message response) { 2927 if (response == null) { 2928 return; 2929 } 2930 mWebViewCore.sendMessage(EventHub.DOC_HAS_IMAGES, response); 2931 } 2932 2933 @Override 2934 public void computeScroll() { 2935 if (mScroller.computeScrollOffset()) { 2936 int oldX = mScrollX; 2937 int oldY = mScrollY; 2938 int x = mScroller.getCurrX(); 2939 int y = mScroller.getCurrY(); 2940 invalidate(); // So we draw again 2941 2942 if (oldX != x || oldY != y) { 2943 final int rangeX = computeMaxScrollX(); 2944 final int rangeY = computeMaxScrollY(); 2945 overScrollBy(x - oldX, y - oldY, oldX, oldY, 2946 rangeX, rangeY, 2947 mOverflingDistance, mOverflingDistance, false); 2948 2949 if (mEdgeGlowTop != null) { 2950 if (rangeY > 0 || getOverScrollMode() == OVER_SCROLL_ALWAYS) { 2951 if (y < 0 && oldY >= 0) { 2952 mEdgeGlowTop.onAbsorb((int) mScroller.getCurrVelocity()); 2953 if (!mEdgeGlowBottom.isFinished()) { 2954 mEdgeGlowBottom.onRelease(); 2955 } 2956 } else if (y > rangeY && oldY <= rangeY) { 2957 mEdgeGlowBottom.onAbsorb((int) mScroller.getCurrVelocity()); 2958 if (!mEdgeGlowTop.isFinished()) { 2959 mEdgeGlowTop.onRelease(); 2960 } 2961 } 2962 } 2963 2964 if (rangeX > 0) { 2965 if (x < 0 && oldX >= 0) { 2966 mEdgeGlowLeft.onAbsorb((int) mScroller.getCurrVelocity()); 2967 if (!mEdgeGlowRight.isFinished()) { 2968 mEdgeGlowRight.onRelease(); 2969 } 2970 } else if (x > rangeX && oldX <= rangeX) { 2971 mEdgeGlowRight.onAbsorb((int) mScroller.getCurrVelocity()); 2972 if (!mEdgeGlowLeft.isFinished()) { 2973 mEdgeGlowLeft.onRelease(); 2974 } 2975 } 2976 } 2977 } 2978 } 2979 if (mScroller.isFinished()) { 2980 mPrivateHandler.sendEmptyMessage(RESUME_WEBCORE_PRIORITY); 2981 } 2982 } else { 2983 super.computeScroll(); 2984 } 2985 } 2986 2987 private static int computeDuration(int dx, int dy) { 2988 int distance = Math.max(Math.abs(dx), Math.abs(dy)); 2989 int duration = distance * 1000 / STD_SPEED; 2990 return Math.min(duration, MAX_DURATION); 2991 } 2992 2993 // helper to pin the scrollBy parameters (already in view coordinates) 2994 // returns true if the scroll was changed 2995 private boolean pinScrollBy(int dx, int dy, boolean animate, int animationDuration) { 2996 return pinScrollTo(mScrollX + dx, mScrollY + dy, animate, animationDuration); 2997 } 2998 // helper to pin the scrollTo parameters (already in view coordinates) 2999 // returns true if the scroll was changed 3000 private boolean pinScrollTo(int x, int y, boolean animate, int animationDuration) { 3001 x = pinLocX(x); 3002 y = pinLocY(y); 3003 int dx = x - mScrollX; 3004 int dy = y - mScrollY; 3005 3006 if ((dx | dy) == 0) { 3007 return false; 3008 } 3009 if (animate) { 3010 // Log.d(LOGTAG, "startScroll: " + dx + " " + dy); 3011 mScroller.startScroll(mScrollX, mScrollY, dx, dy, 3012 animationDuration > 0 ? animationDuration : computeDuration(dx, dy)); 3013 awakenScrollBars(mScroller.getDuration()); 3014 invalidate(); 3015 } else { 3016 abortAnimation(); // just in case 3017 scrollTo(x, y); 3018 } 3019 return true; 3020 } 3021 3022 // Scale from content to view coordinates, and pin. 3023 // Also called by jni webview.cpp 3024 private boolean setContentScrollBy(int cx, int cy, boolean animate) { 3025 if (mDrawHistory) { 3026 // disallow WebView to change the scroll position as History Picture 3027 // is used in the view system. 3028 // TODO: as we switchOutDrawHistory when trackball or navigation 3029 // keys are hit, this should be safe. Right? 3030 return false; 3031 } 3032 cx = contentToViewDimension(cx); 3033 cy = contentToViewDimension(cy); 3034 if (mHeightCanMeasure) { 3035 // move our visible rect according to scroll request 3036 if (cy != 0) { 3037 Rect tempRect = new Rect(); 3038 calcOurVisibleRect(tempRect); 3039 tempRect.offset(cx, cy); 3040 requestRectangleOnScreen(tempRect); 3041 } 3042 // FIXME: We scroll horizontally no matter what because currently 3043 // ScrollView and ListView will not scroll horizontally. 3044 // FIXME: Why do we only scroll horizontally if there is no 3045 // vertical scroll? 3046// Log.d(LOGTAG, "setContentScrollBy cy=" + cy); 3047 return cy == 0 && cx != 0 && pinScrollBy(cx, 0, animate, 0); 3048 } else { 3049 return pinScrollBy(cx, cy, animate, 0); 3050 } 3051 } 3052 3053 /** 3054 * Called by CallbackProxy when the page finishes loading. 3055 * @param url The URL of the page which has finished loading. 3056 */ 3057 /* package */ void onPageFinished(String url) { 3058 if (mPageThatNeedsToSlideTitleBarOffScreen != null) { 3059 // If the user is now on a different page, or has scrolled the page 3060 // past the point where the title bar is offscreen, ignore the 3061 // scroll request. 3062 if (mPageThatNeedsToSlideTitleBarOffScreen.equals(url) 3063 && mScrollX == 0 && mScrollY == 0) { 3064 pinScrollTo(0, mYDistanceToSlideTitleOffScreen, true, 3065 SLIDE_TITLE_DURATION); 3066 } 3067 mPageThatNeedsToSlideTitleBarOffScreen = null; 3068 } 3069 } 3070 3071 /** 3072 * The URL of a page that sent a message to scroll the title bar off screen. 3073 * 3074 * Many mobile sites tell the page to scroll to (0,1) in order to scroll the 3075 * title bar off the screen. Sometimes, the scroll position is set before 3076 * the page finishes loading. Rather than scrolling while the page is still 3077 * loading, keep track of the URL and new scroll position so we can perform 3078 * the scroll once the page finishes loading. 3079 */ 3080 private String mPageThatNeedsToSlideTitleBarOffScreen; 3081 3082 /** 3083 * The destination Y scroll position to be used when the page finishes 3084 * loading. See mPageThatNeedsToSlideTitleBarOffScreen. 3085 */ 3086 private int mYDistanceToSlideTitleOffScreen; 3087 3088 // scale from content to view coordinates, and pin 3089 // return true if pin caused the final x/y different than the request cx/cy, 3090 // and a future scroll may reach the request cx/cy after our size has 3091 // changed 3092 // return false if the view scroll to the exact position as it is requested, 3093 // where negative numbers are taken to mean 0 3094 private boolean setContentScrollTo(int cx, int cy) { 3095 if (mDrawHistory) { 3096 // disallow WebView to change the scroll position as History Picture 3097 // is used in the view system. 3098 // One known case where this is called is that WebCore tries to 3099 // restore the scroll position. As history Picture already uses the 3100 // saved scroll position, it is ok to skip this. 3101 return false; 3102 } 3103 int vx; 3104 int vy; 3105 if ((cx | cy) == 0) { 3106 // If the page is being scrolled to (0,0), do not add in the title 3107 // bar's height, and simply scroll to (0,0). (The only other work 3108 // in contentToView_ is to multiply, so this would not change 0.) 3109 vx = 0; 3110 vy = 0; 3111 } else { 3112 vx = contentToViewX(cx); 3113 vy = contentToViewY(cy); 3114 } 3115// Log.d(LOGTAG, "content scrollTo [" + cx + " " + cy + "] view=[" + 3116// vx + " " + vy + "]"); 3117 // Some mobile sites attempt to scroll the title bar off the page by 3118 // scrolling to (0,1). If we are at the top left corner of the 3119 // page, assume this is an attempt to scroll off the title bar, and 3120 // animate the title bar off screen slowly enough that the user can see 3121 // it. 3122 if (cx == 0 && cy == 1 && mScrollX == 0 && mScrollY == 0 3123 && mTitleBar != null) { 3124 // FIXME: 100 should be defined somewhere as our max progress. 3125 if (getProgress() < 100) { 3126 // Wait to scroll the title bar off screen until the page has 3127 // finished loading. Keep track of the URL and the destination 3128 // Y position 3129 mPageThatNeedsToSlideTitleBarOffScreen = getUrl(); 3130 mYDistanceToSlideTitleOffScreen = vy; 3131 } else { 3132 pinScrollTo(vx, vy, true, SLIDE_TITLE_DURATION); 3133 } 3134 // Since we are animating, we have not yet reached the desired 3135 // scroll position. Do not return true to request another attempt 3136 return false; 3137 } 3138 pinScrollTo(vx, vy, false, 0); 3139 // If the request was to scroll to a negative coordinate, treat it as if 3140 // it was a request to scroll to 0 3141 if ((mScrollX != vx && cx >= 0) || (mScrollY != vy && cy >= 0)) { 3142 return true; 3143 } else { 3144 return false; 3145 } 3146 } 3147 3148 // scale from content to view coordinates, and pin 3149 private void spawnContentScrollTo(int cx, int cy) { 3150 if (mDrawHistory) { 3151 // disallow WebView to change the scroll position as History Picture 3152 // is used in the view system. 3153 return; 3154 } 3155 int vx = contentToViewX(cx); 3156 int vy = contentToViewY(cy); 3157 pinScrollTo(vx, vy, true, 0); 3158 } 3159 3160 /** 3161 * These are from webkit, and are in content coordinate system (unzoomed) 3162 */ 3163 private void contentSizeChanged(boolean updateLayout) { 3164 // suppress 0,0 since we usually see real dimensions soon after 3165 // this avoids drawing the prev content in a funny place. If we find a 3166 // way to consolidate these notifications, this check may become 3167 // obsolete 3168 if ((mContentWidth | mContentHeight) == 0) { 3169 return; 3170 } 3171 3172 if (mHeightCanMeasure) { 3173 if (getMeasuredHeight() != contentToViewDimension(mContentHeight) 3174 || updateLayout) { 3175 requestLayout(); 3176 } 3177 } else if (mWidthCanMeasure) { 3178 if (getMeasuredWidth() != contentToViewDimension(mContentWidth) 3179 || updateLayout) { 3180 requestLayout(); 3181 } 3182 } else { 3183 // If we don't request a layout, try to send our view size to the 3184 // native side to ensure that WebCore has the correct dimensions. 3185 sendViewSizeZoom(); 3186 } 3187 } 3188 3189 /** 3190 * Set the WebViewClient that will receive various notifications and 3191 * requests. This will replace the current handler. 3192 * @param client An implementation of WebViewClient. 3193 */ 3194 public void setWebViewClient(WebViewClient client) { 3195 mCallbackProxy.setWebViewClient(client); 3196 } 3197 3198 /** 3199 * Gets the WebViewClient 3200 * @return the current WebViewClient instance. 3201 * 3202 *@hide pending API council approval. 3203 */ 3204 public WebViewClient getWebViewClient() { 3205 return mCallbackProxy.getWebViewClient(); 3206 } 3207 3208 /** 3209 * Register the interface to be used when content can not be handled by 3210 * the rendering engine, and should be downloaded instead. This will replace 3211 * the current handler. 3212 * @param listener An implementation of DownloadListener. 3213 */ 3214 public void setDownloadListener(DownloadListener listener) { 3215 mCallbackProxy.setDownloadListener(listener); 3216 } 3217 3218 /** 3219 * Set the chrome handler. This is an implementation of WebChromeClient for 3220 * use in handling Javascript dialogs, favicons, titles, and the progress. 3221 * This will replace the current handler. 3222 * @param client An implementation of WebChromeClient. 3223 */ 3224 public void setWebChromeClient(WebChromeClient client) { 3225 mCallbackProxy.setWebChromeClient(client); 3226 } 3227 3228 /** 3229 * Gets the chrome handler. 3230 * @return the current WebChromeClient instance. 3231 * 3232 * @hide API council approval. 3233 */ 3234 public WebChromeClient getWebChromeClient() { 3235 return mCallbackProxy.getWebChromeClient(); 3236 } 3237 3238 /** 3239 * Set the back/forward list client. This is an implementation of 3240 * WebBackForwardListClient for handling new items and changes in the 3241 * history index. 3242 * @param client An implementation of WebBackForwardListClient. 3243 * {@hide} 3244 */ 3245 public void setWebBackForwardListClient(WebBackForwardListClient client) { 3246 mCallbackProxy.setWebBackForwardListClient(client); 3247 } 3248 3249 /** 3250 * Gets the WebBackForwardListClient. 3251 * {@hide} 3252 */ 3253 public WebBackForwardListClient getWebBackForwardListClient() { 3254 return mCallbackProxy.getWebBackForwardListClient(); 3255 } 3256 3257 /** 3258 * Set the Picture listener. This is an interface used to receive 3259 * notifications of a new Picture. 3260 * @param listener An implementation of WebView.PictureListener. 3261 */ 3262 public void setPictureListener(PictureListener listener) { 3263 mPictureListener = listener; 3264 } 3265 3266 /** 3267 * {@hide} 3268 */ 3269 /* FIXME: Debug only! Remove for SDK! */ 3270 public void externalRepresentation(Message callback) { 3271 mWebViewCore.sendMessage(EventHub.REQUEST_EXT_REPRESENTATION, callback); 3272 } 3273 3274 /** 3275 * {@hide} 3276 */ 3277 /* FIXME: Debug only! Remove for SDK! */ 3278 public void documentAsText(Message callback) { 3279 mWebViewCore.sendMessage(EventHub.REQUEST_DOC_AS_TEXT, callback); 3280 } 3281 3282 /** 3283 * Use this function to bind an object to Javascript so that the 3284 * methods can be accessed from Javascript. 3285 * <p><strong>IMPORTANT:</strong> 3286 * <ul> 3287 * <li> Using addJavascriptInterface() allows JavaScript to control your 3288 * application. This can be a very useful feature or a dangerous security 3289 * issue. When the HTML in the WebView is untrustworthy (for example, part 3290 * or all of the HTML is provided by some person or process), then an 3291 * attacker could inject HTML that will execute your code and possibly any 3292 * code of the attacker's choosing.<br> 3293 * Do not use addJavascriptInterface() unless all of the HTML in this 3294 * WebView was written by you.</li> 3295 * <li> The Java object that is bound runs in another thread and not in 3296 * the thread that it was constructed in.</li> 3297 * </ul></p> 3298 * @param obj The class instance to bind to Javascript 3299 * @param interfaceName The name to used to expose the class in Javascript 3300 */ 3301 public void addJavascriptInterface(Object obj, String interfaceName) { 3302 WebViewCore.JSInterfaceData arg = new WebViewCore.JSInterfaceData(); 3303 arg.mObject = obj; 3304 arg.mInterfaceName = interfaceName; 3305 mWebViewCore.sendMessage(EventHub.ADD_JS_INTERFACE, arg); 3306 } 3307 3308 /** 3309 * Return the WebSettings object used to control the settings for this 3310 * WebView. 3311 * @return A WebSettings object that can be used to control this WebView's 3312 * settings. 3313 */ 3314 public WebSettings getSettings() { 3315 return mWebViewCore.getSettings(); 3316 } 3317 3318 /** 3319 * Use this method to inform the webview about packages that are installed 3320 * in the system. This information will be used by the 3321 * navigator.isApplicationInstalled() API. 3322 * @param packageNames is a set of package names that are known to be 3323 * installed in the system. 3324 * 3325 * @hide not a public API 3326 */ 3327 public void addPackageNames(Set<String> packageNames) { 3328 mWebViewCore.sendMessage(EventHub.ADD_PACKAGE_NAMES, packageNames); 3329 } 3330 3331 /** 3332 * Use this method to inform the webview about single packages that are 3333 * installed in the system. This information will be used by the 3334 * navigator.isApplicationInstalled() API. 3335 * @param packageName is the name of a package that is known to be 3336 * installed in the system. 3337 * 3338 * @hide not a public API 3339 */ 3340 public void addPackageName(String packageName) { 3341 mWebViewCore.sendMessage(EventHub.ADD_PACKAGE_NAME, packageName); 3342 } 3343 3344 /** 3345 * Use this method to inform the webview about packages that are uninstalled 3346 * in the system. This information will be used by the 3347 * navigator.isApplicationInstalled() API. 3348 * @param packageName is the name of a package that has been uninstalled in 3349 * the system. 3350 * 3351 * @hide not a public API 3352 */ 3353 public void removePackageName(String packageName) { 3354 mWebViewCore.sendMessage(EventHub.REMOVE_PACKAGE_NAME, packageName); 3355 } 3356 3357 /** 3358 * Return the list of currently loaded plugins. 3359 * @return The list of currently loaded plugins. 3360 * 3361 * @deprecated This was used for Gears, which has been deprecated. 3362 */ 3363 @Deprecated 3364 public static synchronized PluginList getPluginList() { 3365 return new PluginList(); 3366 } 3367 3368 /** 3369 * @deprecated This was used for Gears, which has been deprecated. 3370 */ 3371 @Deprecated 3372 public void refreshPlugins(boolean reloadOpenPages) { } 3373 3374 //------------------------------------------------------------------------- 3375 // Override View methods 3376 //------------------------------------------------------------------------- 3377 3378 @Override 3379 protected void finalize() throws Throwable { 3380 try { 3381 destroy(); 3382 } finally { 3383 super.finalize(); 3384 } 3385 } 3386 3387 @Override 3388 protected boolean drawChild(Canvas canvas, View child, long drawingTime) { 3389 if (child == mTitleBar) { 3390 // When drawing the title bar, move it horizontally to always show 3391 // at the top of the WebView. 3392 mTitleBar.offsetLeftAndRight(mScrollX - mTitleBar.getLeft()); 3393 } 3394 return super.drawChild(canvas, child, drawingTime); 3395 } 3396 3397 private void drawContent(Canvas canvas) { 3398 // Update the buttons in the picture, so when we draw the picture 3399 // to the screen, they are in the correct state. 3400 // Tell the native side if user is a) touching the screen, 3401 // b) pressing the trackball down, or c) pressing the enter key 3402 // If the cursor is on a button, we need to draw it in the pressed 3403 // state. 3404 // If mNativeClass is 0, we should not reach here, so we do not 3405 // need to check it again. 3406 nativeRecordButtons(hasFocus() && hasWindowFocus(), 3407 mTouchMode == TOUCH_SHORTPRESS_START_MODE 3408 || mTrackballDown || mGotCenterDown, false); 3409 drawCoreAndCursorRing(canvas, mBackgroundColor, mDrawCursorRing); 3410 } 3411 3412 @Override 3413 protected void onDraw(Canvas canvas) { 3414 // if mNativeClass is 0, the WebView has been destroyed. Do nothing. 3415 if (mNativeClass == 0) { 3416 return; 3417 } 3418 3419 // if both mContentWidth and mContentHeight are 0, it means there is no 3420 // valid Picture passed to WebView yet. This can happen when WebView 3421 // just starts. Draw the background and return. 3422 if ((mContentWidth | mContentHeight) == 0 && mHistoryPicture == null) { 3423 canvas.drawColor(mBackgroundColor); 3424 return; 3425 } 3426 3427 int saveCount = canvas.save(); 3428 if (mInOverScrollMode && !getSettings() 3429 .getUseWebViewBackgroundForOverscrollBackground()) { 3430 if (mOverScrollBackground == null) { 3431 mOverScrollBackground = new Paint(); 3432 Bitmap bm = BitmapFactory.decodeResource( 3433 mContext.getResources(), 3434 com.android.internal.R.drawable.status_bar_background); 3435 mOverScrollBackground.setShader(new BitmapShader(bm, 3436 Shader.TileMode.REPEAT, Shader.TileMode.REPEAT)); 3437 mOverScrollBorder = new Paint(); 3438 mOverScrollBorder.setStyle(Paint.Style.STROKE); 3439 mOverScrollBorder.setStrokeWidth(0); 3440 mOverScrollBorder.setColor(0xffbbbbbb); 3441 } 3442 3443 int top = 0; 3444 int right = computeRealHorizontalScrollRange(); 3445 int bottom = top + computeRealVerticalScrollRange(); 3446 // first draw the background and anchor to the top of the view 3447 canvas.save(); 3448 canvas.translate(mScrollX, mScrollY); 3449 canvas.clipRect(-mScrollX, top - mScrollY, right - mScrollX, bottom 3450 - mScrollY, Region.Op.DIFFERENCE); 3451 canvas.drawPaint(mOverScrollBackground); 3452 canvas.restore(); 3453 // then draw the border 3454 canvas.drawRect(-1, top - 1, right, bottom, mOverScrollBorder); 3455 // next clip the region for the content 3456 canvas.clipRect(0, top, right, bottom); 3457 } 3458 if (mTitleBar != null) { 3459 canvas.translate(0, (int) mTitleBar.getHeight()); 3460 } 3461 if (mDragTrackerHandler == null) { 3462 drawContent(canvas); 3463 } else { 3464 if (!mDragTrackerHandler.draw(canvas)) { 3465 // sometimes the tracker doesn't draw, even though its active 3466 drawContent(canvas); 3467 } 3468 if (mDragTrackerHandler.isFinished()) { 3469 mDragTrackerHandler = null; 3470 } 3471 } 3472 canvas.restoreToCount(saveCount); 3473 3474 // Now draw the shadow. 3475 int titleH = getVisibleTitleHeight(); 3476 if (mTitleBar != null && titleH == 0) { 3477 int height = (int) (5f * getContext().getResources() 3478 .getDisplayMetrics().density); 3479 mTitleShadow.setBounds(mScrollX, mScrollY, mScrollX + getWidth(), 3480 mScrollY + height); 3481 mTitleShadow.draw(canvas); 3482 } 3483 3484 if (AUTO_REDRAW_HACK && mAutoRedraw) { 3485 invalidate(); 3486 } 3487 mWebViewCore.signalRepaintDone(); 3488 } 3489 3490 @Override 3491 public void draw(Canvas canvas) { 3492 super.draw(canvas); 3493 if (mEdgeGlowTop != null && drawEdgeGlows(canvas)) { 3494 invalidate(); 3495 } 3496 } 3497 3498 /** 3499 * Draw the glow effect along the sides of the widget. mEdgeGlow* must be non-null. 3500 * 3501 * @param canvas Canvas to draw into, transformed into view coordinates. 3502 * @return true if glow effects are still animating and the view should invalidate again. 3503 */ 3504 private boolean drawEdgeGlows(Canvas canvas) { 3505 final int scrollX = mScrollX; 3506 final int scrollY = mScrollY; 3507 final int width = getWidth(); 3508 int height = getHeight(); 3509 3510 boolean invalidateForGlow = false; 3511 if (!mEdgeGlowTop.isFinished()) { 3512 final int restoreCount = canvas.save(); 3513 3514 canvas.translate(-width / 2 + scrollX, Math.min(0, scrollY)); 3515 mEdgeGlowTop.setSize(width * 2, height); 3516 invalidateForGlow |= mEdgeGlowTop.draw(canvas); 3517 canvas.restoreToCount(restoreCount); 3518 } 3519 if (!mEdgeGlowBottom.isFinished()) { 3520 final int restoreCount = canvas.save(); 3521 3522 canvas.translate(-width / 2 + scrollX, Math.max(computeMaxScrollY(), scrollY) + height); 3523 canvas.rotate(180, width, 0); 3524 mEdgeGlowBottom.setSize(width * 2, height); 3525 invalidateForGlow |= mEdgeGlowBottom.draw(canvas); 3526 canvas.restoreToCount(restoreCount); 3527 } 3528 if (!mEdgeGlowLeft.isFinished()) { 3529 final int restoreCount = canvas.save(); 3530 3531 canvas.rotate(270); 3532 canvas.translate(-height * 1.5f - scrollY, Math.min(0, scrollX)); 3533 mEdgeGlowLeft.setSize(height * 2, width); 3534 invalidateForGlow |= mEdgeGlowLeft.draw(canvas); 3535 canvas.restoreToCount(restoreCount); 3536 } 3537 if (!mEdgeGlowRight.isFinished()) { 3538 final int restoreCount = canvas.save(); 3539 3540 canvas.rotate(90); 3541 canvas.translate(-height / 2 + scrollY, 3542 -(Math.max(computeMaxScrollX(), scrollX) + width)); 3543 mEdgeGlowRight.setSize(height * 2, width); 3544 invalidateForGlow |= mEdgeGlowRight.draw(canvas); 3545 canvas.restoreToCount(restoreCount); 3546 } 3547 return invalidateForGlow; 3548 } 3549 3550 @Override 3551 public void setLayoutParams(ViewGroup.LayoutParams params) { 3552 if (params.height == LayoutParams.WRAP_CONTENT) { 3553 mWrapContent = true; 3554 } 3555 super.setLayoutParams(params); 3556 } 3557 3558 @Override 3559 public boolean performLongClick() { 3560 // performLongClick() is the result of a delayed message. If we switch 3561 // to windows overview, the WebView will be temporarily removed from the 3562 // view system. In that case, do nothing. 3563 if (getParent() == null) return false; 3564 if (mNativeClass != 0 && nativeCursorIsTextInput()) { 3565 // Send the click so that the textfield is in focus 3566 centerKeyPressOnTextField(); 3567 rebuildWebTextView(); 3568 } else { 3569 clearTextEntry(true); 3570 } 3571 if (inEditingMode()) { 3572 return mWebTextView.performLongClick(); 3573 } 3574 /* if long click brings up a context menu, the super function 3575 * returns true and we're done. Otherwise, nothing happened when 3576 * the user clicked. */ 3577 if (super.performLongClick()) { 3578 return true; 3579 } 3580 /* In the case where the application hasn't already handled the long 3581 * click action, look for a word under the click. If one is found, 3582 * animate the text selection into view. 3583 * FIXME: no animation code yet */ 3584 if (mSelectingText) return false; // long click does nothing on selection 3585 int x = viewToContentX((int) mLastTouchX + mScrollX); 3586 int y = viewToContentY((int) mLastTouchY + mScrollY); 3587 setUpSelect(); 3588 if (mNativeClass != 0 && nativeWordSelection(x, y)) { 3589 nativeSetExtendSelection(); 3590 WebChromeClient client = getWebChromeClient(); 3591 if (client != null) client.onSelectionStart(this); 3592 return true; 3593 } 3594 notifySelectDialogDismissed(); 3595 return false; 3596 } 3597 3598 boolean inAnimateZoom() { 3599 return mZoomScale != 0; 3600 } 3601 3602 /** 3603 * Need to adjust the WebTextView after a change in zoom, since mActualScale 3604 * has changed. This is especially important for password fields, which are 3605 * drawn by the WebTextView, since it conveys more information than what 3606 * webkit draws. Thus we need to reposition it to show in the correct 3607 * place. 3608 */ 3609 private boolean mNeedToAdjustWebTextView; 3610 3611 private boolean didUpdateTextViewBounds(boolean allowIntersect) { 3612 Rect contentBounds = nativeFocusCandidateNodeBounds(); 3613 Rect vBox = contentToViewRect(contentBounds); 3614 Rect visibleRect = new Rect(); 3615 calcOurVisibleRect(visibleRect); 3616 // If the textfield is on screen, place the WebTextView in 3617 // its new place, accounting for our new scroll/zoom values, 3618 // and adjust its textsize. 3619 if (allowIntersect ? Rect.intersects(visibleRect, vBox) 3620 : visibleRect.contains(vBox)) { 3621 mWebTextView.setRect(vBox.left, vBox.top, vBox.width(), 3622 vBox.height()); 3623 mWebTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, 3624 contentToViewDimension( 3625 nativeFocusCandidateTextSize())); 3626 return true; 3627 } else { 3628 // The textfield is now off screen. The user probably 3629 // was not zooming to see the textfield better. Remove 3630 // the WebTextView. If the user types a key, and the 3631 // textfield is still in focus, we will reconstruct 3632 // the WebTextView and scroll it back on screen. 3633 mWebTextView.remove(); 3634 return false; 3635 } 3636 } 3637 3638 private void drawExtras(Canvas canvas, int extras, boolean animationsRunning) { 3639 // If mNativeClass is 0, we should not reach here, so we do not 3640 // need to check it again. 3641 if (animationsRunning) { 3642 canvas.setDrawFilter(mWebViewCore.mZoomFilter); 3643 } 3644 nativeDrawExtras(canvas, extras); 3645 canvas.setDrawFilter(null); 3646 } 3647 3648 private void drawCoreAndCursorRing(Canvas canvas, int color, 3649 boolean drawCursorRing) { 3650 if (mDrawHistory) { 3651 canvas.scale(mActualScale, mActualScale); 3652 canvas.drawPicture(mHistoryPicture); 3653 return; 3654 } 3655 3656 boolean animateZoom = mZoomScale != 0; 3657 boolean animateScroll = ((!mScroller.isFinished() 3658 || mVelocityTracker != null) 3659 && (mTouchMode != TOUCH_DRAG_MODE || 3660 mHeldMotionless != MOTIONLESS_TRUE)) 3661 || mDeferTouchMode == TOUCH_DRAG_MODE; 3662 if (mTouchMode == TOUCH_DRAG_MODE) { 3663 if (mHeldMotionless == MOTIONLESS_PENDING) { 3664 mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS); 3665 mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS); 3666 mHeldMotionless = MOTIONLESS_FALSE; 3667 } 3668 if (mHeldMotionless == MOTIONLESS_FALSE) { 3669 mPrivateHandler.sendMessageDelayed(mPrivateHandler 3670 .obtainMessage(DRAG_HELD_MOTIONLESS), MOTIONLESS_TIME); 3671 mHeldMotionless = MOTIONLESS_PENDING; 3672 } 3673 } 3674 if (animateZoom) { 3675 float zoomScale; 3676 int interval = (int) (SystemClock.uptimeMillis() - mZoomStart); 3677 if (interval < ZOOM_ANIMATION_LENGTH) { 3678 float ratio = (float) interval / ZOOM_ANIMATION_LENGTH; 3679 zoomScale = 1.0f / (mInvInitialZoomScale 3680 + (mInvFinalZoomScale - mInvInitialZoomScale) * ratio); 3681 invalidate(); 3682 } else { 3683 zoomScale = mZoomScale; 3684 // set mZoomScale to be 0 as we have done animation 3685 mZoomScale = 0; 3686 WebViewCore.resumeUpdatePicture(mWebViewCore); 3687 // call invalidate() again to draw with the final filters 3688 invalidate(); 3689 if (mNeedToAdjustWebTextView) { 3690 mNeedToAdjustWebTextView = false; 3691 if (didUpdateTextViewBounds(false) 3692 && nativeFocusCandidateIsPassword()) { 3693 // If it is a password field, start drawing the 3694 // WebTextView once again. 3695 mWebTextView.setInPassword(true); 3696 } 3697 } 3698 } 3699 // calculate the intermediate scroll position. As we need to use 3700 // zoomScale, we can't use pinLocX/Y directly. Copy the logic here. 3701 float scale = zoomScale * mInvInitialZoomScale; 3702 int tx = Math.round(scale * (mInitialScrollX + mZoomCenterX) 3703 - mZoomCenterX); 3704 tx = -pinLoc(tx, getViewWidth(), Math.round(mContentWidth 3705 * zoomScale)) + mScrollX; 3706 int titleHeight = getTitleHeight(); 3707 int ty = Math.round(scale 3708 * (mInitialScrollY + mZoomCenterY - titleHeight) 3709 - (mZoomCenterY - titleHeight)); 3710 ty = -(ty <= titleHeight ? Math.max(ty, 0) : pinLoc(ty 3711 - titleHeight, getViewHeight(), Math.round(mContentHeight 3712 * zoomScale)) + titleHeight) + mScrollY; 3713 canvas.translate(tx, ty); 3714 canvas.scale(zoomScale, zoomScale); 3715 if (inEditingMode() && !mNeedToAdjustWebTextView 3716 && mZoomScale != 0) { 3717 // The WebTextView is up. Keep track of this so we can adjust 3718 // its size and placement when we finish zooming 3719 mNeedToAdjustWebTextView = true; 3720 // If it is in password mode, turn it off so it does not draw 3721 // misplaced. 3722 if (nativeFocusCandidateIsPassword()) { 3723 mWebTextView.setInPassword(false); 3724 } 3725 } 3726 } else { 3727 canvas.scale(mActualScale, mActualScale); 3728 } 3729 3730 boolean UIAnimationsRunning = false; 3731 // Currently for each draw we compute the animation values; 3732 // We may in the future decide to do that independently. 3733 if (mNativeClass != 0 && nativeEvaluateLayersAnimations()) { 3734 UIAnimationsRunning = true; 3735 // If we have unfinished (or unstarted) animations, 3736 // we ask for a repaint. 3737 invalidate(); 3738 } 3739 mWebViewCore.drawContentPicture(canvas, color, 3740 (animateZoom || mPreviewZoomOnly || UIAnimationsRunning), 3741 animateScroll); 3742 if (mNativeClass == 0) return; 3743 // decide which adornments to draw 3744 int extras = DRAW_EXTRAS_NONE; 3745 if (mFindIsUp) { 3746 extras = DRAW_EXTRAS_FIND; 3747 } else if (mSelectingText) { 3748 extras = DRAW_EXTRAS_SELECTION; 3749 nativeSetSelectionPointer(mDrawSelectionPointer, 3750 mInvActualScale, 3751 mSelectX, mSelectY - getTitleHeight()); 3752 } else if (drawCursorRing) { 3753 extras = DRAW_EXTRAS_CURSOR_RING; 3754 } 3755 drawExtras(canvas, extras, UIAnimationsRunning); 3756 3757 if (extras == DRAW_EXTRAS_CURSOR_RING) { 3758 if (mTouchMode == TOUCH_SHORTPRESS_START_MODE) { 3759 mTouchMode = TOUCH_SHORTPRESS_MODE; 3760 } 3761 } 3762 if (mFocusSizeChanged) { 3763 mFocusSizeChanged = false; 3764 // If we are zooming, this will get handled above, when the zoom 3765 // finishes. We also do not need to do this unless the WebTextView 3766 // is showing. 3767 if (!animateZoom && inEditingMode()) { 3768 didUpdateTextViewBounds(true); 3769 } 3770 } 3771 } 3772 3773 // draw history 3774 private boolean mDrawHistory = false; 3775 private Picture mHistoryPicture = null; 3776 private int mHistoryWidth = 0; 3777 private int mHistoryHeight = 0; 3778 3779 // Only check the flag, can be called from WebCore thread 3780 boolean drawHistory() { 3781 return mDrawHistory; 3782 } 3783 3784 // Should only be called in UI thread 3785 void switchOutDrawHistory() { 3786 if (null == mWebViewCore) return; // CallbackProxy may trigger this 3787 if (mDrawHistory && mWebViewCore.pictureReady()) { 3788 mDrawHistory = false; 3789 mHistoryPicture = null; 3790 invalidate(); 3791 int oldScrollX = mScrollX; 3792 int oldScrollY = mScrollY; 3793 mScrollX = pinLocX(mScrollX); 3794 mScrollY = pinLocY(mScrollY); 3795 if (oldScrollX != mScrollX || oldScrollY != mScrollY) { 3796 mUserScroll = false; 3797 mWebViewCore.sendMessage(EventHub.SYNC_SCROLL, oldScrollX, 3798 oldScrollY); 3799 onScrollChanged(mScrollX, mScrollY, oldScrollX, oldScrollY); 3800 } else { 3801 sendOurVisibleRect(); 3802 } 3803 } 3804 } 3805 3806 WebViewCore.CursorData cursorData() { 3807 WebViewCore.CursorData result = new WebViewCore.CursorData(); 3808 result.mMoveGeneration = nativeMoveGeneration(); 3809 result.mFrame = nativeCursorFramePointer(); 3810 Point position = nativeCursorPosition(); 3811 result.mX = position.x; 3812 result.mY = position.y; 3813 return result; 3814 } 3815 3816 /** 3817 * Delete text from start to end in the focused textfield. If there is no 3818 * focus, or if start == end, silently fail. If start and end are out of 3819 * order, swap them. 3820 * @param start Beginning of selection to delete. 3821 * @param end End of selection to delete. 3822 */ 3823 /* package */ void deleteSelection(int start, int end) { 3824 mTextGeneration++; 3825 WebViewCore.TextSelectionData data 3826 = new WebViewCore.TextSelectionData(start, end); 3827 mWebViewCore.sendMessage(EventHub.DELETE_SELECTION, mTextGeneration, 0, 3828 data); 3829 } 3830 3831 /** 3832 * Set the selection to (start, end) in the focused textfield. If start and 3833 * end are out of order, swap them. 3834 * @param start Beginning of selection. 3835 * @param end End of selection. 3836 */ 3837 /* package */ void setSelection(int start, int end) { 3838 mWebViewCore.sendMessage(EventHub.SET_SELECTION, start, end); 3839 } 3840 3841 @Override 3842 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 3843 InputConnection connection = super.onCreateInputConnection(outAttrs); 3844 outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_FULLSCREEN; 3845 return connection; 3846 } 3847 3848 /** 3849 * Called in response to a message from webkit telling us that the soft 3850 * keyboard should be launched. 3851 */ 3852 private void displaySoftKeyboard(boolean isTextView) { 3853 InputMethodManager imm = (InputMethodManager) 3854 getContext().getSystemService(Context.INPUT_METHOD_SERVICE); 3855 3856 // bring it back to the default scale so that user can enter text 3857 boolean zoom = mActualScale < mDefaultScale; 3858 if (zoom) { 3859 mInZoomOverview = false; 3860 mZoomCenterX = mLastTouchX; 3861 mZoomCenterY = mLastTouchY; 3862 // do not change text wrap scale so that there is no reflow 3863 setNewZoomScale(mDefaultScale, false, false); 3864 } 3865 if (isTextView) { 3866 rebuildWebTextView(); 3867 if (inEditingMode()) { 3868 imm.showSoftInput(mWebTextView, 0); 3869 if (zoom) { 3870 didUpdateTextViewBounds(true); 3871 } 3872 return; 3873 } 3874 } 3875 // Used by plugins. 3876 // Also used if the navigation cache is out of date, and 3877 // does not recognize that a textfield is in focus. In that 3878 // case, use WebView as the targeted view. 3879 // see http://b/issue?id=2457459 3880 imm.showSoftInput(this, 0); 3881 } 3882 3883 // Called by WebKit to instruct the UI to hide the keyboard 3884 private void hideSoftKeyboard() { 3885 InputMethodManager imm = (InputMethodManager) 3886 getContext().getSystemService(Context.INPUT_METHOD_SERVICE); 3887 3888 imm.hideSoftInputFromWindow(this.getWindowToken(), 0); 3889 } 3890 3891 /* 3892 * This method checks the current focus and cursor and potentially rebuilds 3893 * mWebTextView to have the appropriate properties, such as password, 3894 * multiline, and what text it contains. It also removes it if necessary. 3895 */ 3896 /* package */ void rebuildWebTextView() { 3897 // If the WebView does not have focus, do nothing until it gains focus. 3898 if (!hasFocus() && (null == mWebTextView || !mWebTextView.hasFocus())) { 3899 return; 3900 } 3901 boolean alreadyThere = inEditingMode(); 3902 // inEditingMode can only return true if mWebTextView is non-null, 3903 // so we can safely call remove() if (alreadyThere) 3904 if (0 == mNativeClass || !nativeFocusCandidateIsTextInput()) { 3905 if (alreadyThere) { 3906 mWebTextView.remove(); 3907 } 3908 return; 3909 } 3910 // At this point, we know we have found an input field, so go ahead 3911 // and create the WebTextView if necessary. 3912 if (mWebTextView == null) { 3913 mWebTextView = new WebTextView(mContext, WebView.this); 3914 // Initialize our generation number. 3915 mTextGeneration = 0; 3916 } 3917 mWebTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, 3918 contentToViewDimension(nativeFocusCandidateTextSize())); 3919 Rect visibleRect = new Rect(); 3920 calcOurContentVisibleRect(visibleRect); 3921 // Note that sendOurVisibleRect calls viewToContent, so the coordinates 3922 // should be in content coordinates. 3923 Rect bounds = nativeFocusCandidateNodeBounds(); 3924 Rect vBox = contentToViewRect(bounds); 3925 mWebTextView.setRect(vBox.left, vBox.top, vBox.width(), vBox.height()); 3926 if (!Rect.intersects(bounds, visibleRect)) { 3927 mWebTextView.bringIntoView(); 3928 } 3929 String text = nativeFocusCandidateText(); 3930 int nodePointer = nativeFocusCandidatePointer(); 3931 if (alreadyThere && mWebTextView.isSameTextField(nodePointer)) { 3932 // It is possible that we have the same textfield, but it has moved, 3933 // i.e. In the case of opening/closing the screen. 3934 // In that case, we need to set the dimensions, but not the other 3935 // aspects. 3936 // If the text has been changed by webkit, update it. However, if 3937 // there has been more UI text input, ignore it. We will receive 3938 // another update when that text is recognized. 3939 if (text != null && !text.equals(mWebTextView.getText().toString()) 3940 && nativeTextGeneration() == mTextGeneration) { 3941 mWebTextView.setTextAndKeepSelection(text); 3942 } 3943 } else { 3944 mWebTextView.setGravity(nativeFocusCandidateIsRtlText() ? 3945 Gravity.RIGHT : Gravity.NO_GRAVITY); 3946 // This needs to be called before setType, which may call 3947 // requestFormData, and it needs to have the correct nodePointer. 3948 mWebTextView.setNodePointer(nodePointer); 3949 mWebTextView.setType(nativeFocusCandidateType()); 3950 if (null == text) { 3951 if (DebugFlags.WEB_VIEW) { 3952 Log.v(LOGTAG, "rebuildWebTextView null == text"); 3953 } 3954 text = ""; 3955 } 3956 mWebTextView.setTextAndKeepSelection(text); 3957 InputMethodManager imm = InputMethodManager.peekInstance(); 3958 if (imm != null && imm.isActive(mWebTextView)) { 3959 imm.restartInput(mWebTextView); 3960 } 3961 } 3962 mWebTextView.requestFocus(); 3963 } 3964 3965 /** 3966 * Called by WebTextView to find saved form data associated with the 3967 * textfield 3968 * @param name Name of the textfield. 3969 * @param nodePointer Pointer to the node of the textfield, so it can be 3970 * compared to the currently focused textfield when the data is 3971 * retrieved. 3972 */ 3973 /* package */ void requestFormData(String name, int nodePointer) { 3974 if (mWebViewCore.getSettings().getSaveFormData()) { 3975 Message update = mPrivateHandler.obtainMessage(REQUEST_FORM_DATA); 3976 update.arg1 = nodePointer; 3977 RequestFormData updater = new RequestFormData(name, getUrl(), 3978 update); 3979 Thread t = new Thread(updater); 3980 t.start(); 3981 } 3982 } 3983 3984 /** 3985 * Pass a message to find out the <label> associated with the <input> 3986 * identified by nodePointer 3987 * @param framePointer Pointer to the frame containing the <input> node 3988 * @param nodePointer Pointer to the node for which a <label> is desired. 3989 */ 3990 /* package */ void requestLabel(int framePointer, int nodePointer) { 3991 mWebViewCore.sendMessage(EventHub.REQUEST_LABEL, framePointer, 3992 nodePointer); 3993 } 3994 3995 /* 3996 * This class requests an Adapter for the WebTextView which shows past 3997 * entries stored in the database. It is a Runnable so that it can be done 3998 * in its own thread, without slowing down the UI. 3999 */ 4000 private class RequestFormData implements Runnable { 4001 private String mName; 4002 private String mUrl; 4003 private Message mUpdateMessage; 4004 4005 public RequestFormData(String name, String url, Message msg) { 4006 mName = name; 4007 mUrl = url; 4008 mUpdateMessage = msg; 4009 } 4010 4011 public void run() { 4012 ArrayList<String> pastEntries = mDatabase.getFormData(mUrl, mName); 4013 if (pastEntries.size() > 0) { 4014 AutoCompleteAdapter adapter = new 4015 AutoCompleteAdapter(mContext, pastEntries); 4016 mUpdateMessage.obj = adapter; 4017 mUpdateMessage.sendToTarget(); 4018 } 4019 } 4020 } 4021 4022 /** 4023 * Dump the display tree to "/sdcard/displayTree.txt" 4024 * 4025 * @hide debug only 4026 */ 4027 public void dumpDisplayTree() { 4028 nativeDumpDisplayTree(getUrl()); 4029 } 4030 4031 /** 4032 * Dump the dom tree to adb shell if "toFile" is False, otherwise dump it to 4033 * "/sdcard/domTree.txt" 4034 * 4035 * @hide debug only 4036 */ 4037 public void dumpDomTree(boolean toFile) { 4038 mWebViewCore.sendMessage(EventHub.DUMP_DOMTREE, toFile ? 1 : 0, 0); 4039 } 4040 4041 /** 4042 * Dump the render tree to adb shell if "toFile" is False, otherwise dump it 4043 * to "/sdcard/renderTree.txt" 4044 * 4045 * @hide debug only 4046 */ 4047 public void dumpRenderTree(boolean toFile) { 4048 mWebViewCore.sendMessage(EventHub.DUMP_RENDERTREE, toFile ? 1 : 0, 0); 4049 } 4050 4051 /** 4052 * Dump the V8 counters to standard output. 4053 * Note that you need a build with V8 and WEBCORE_INSTRUMENTATION set to 4054 * true. Otherwise, this will do nothing. 4055 * 4056 * @hide debug only 4057 */ 4058 public void dumpV8Counters() { 4059 mWebViewCore.sendMessage(EventHub.DUMP_V8COUNTERS); 4060 } 4061 4062 // This is used to determine long press with the center key. Does not 4063 // affect long press with the trackball/touch. 4064 private boolean mGotCenterDown = false; 4065 4066 @Override 4067 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 4068 // send complex characters to webkit for use by JS and plugins 4069 if (keyCode == KeyEvent.KEYCODE_UNKNOWN && event.getCharacters() != null) { 4070 // pass the key to DOM 4071 mWebViewCore.sendMessage(EventHub.KEY_DOWN, event); 4072 mWebViewCore.sendMessage(EventHub.KEY_UP, event); 4073 // return true as DOM handles the key 4074 return true; 4075 } 4076 return false; 4077 } 4078 4079 @Override 4080 public boolean onKeyDown(int keyCode, KeyEvent event) { 4081 if (DebugFlags.WEB_VIEW) { 4082 Log.v(LOGTAG, "keyDown at " + System.currentTimeMillis() 4083 + ", " + event + ", unicode=" + event.getUnicodeChar()); 4084 } 4085 4086 if (mNativeClass == 0) { 4087 return false; 4088 } 4089 4090 // do this hack up front, so it always works, regardless of touch-mode 4091 if (AUTO_REDRAW_HACK && (keyCode == KeyEvent.KEYCODE_CALL)) { 4092 mAutoRedraw = !mAutoRedraw; 4093 if (mAutoRedraw) { 4094 invalidate(); 4095 } 4096 return true; 4097 } 4098 4099 // Bubble up the key event if 4100 // 1. it is a system key; or 4101 // 2. the host application wants to handle it; 4102 if (event.isSystem() 4103 || mCallbackProxy.uiOverrideKeyEvent(event)) { 4104 return false; 4105 } 4106 4107 if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT 4108 || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT) { 4109 if (nativeFocusIsPlugin()) { 4110 mShiftIsPressed = true; 4111 } else if (!nativeCursorWantsKeyEvents() && !mSelectingText) { 4112 setUpSelect(); 4113 } 4114 } 4115 4116 if (keyCode >= KeyEvent.KEYCODE_DPAD_UP 4117 && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) { 4118 switchOutDrawHistory(); 4119 if (nativeFocusIsPlugin()) { 4120 letPluginHandleNavKey(keyCode, event.getEventTime(), true); 4121 return true; 4122 } 4123 if (mSelectingText) { 4124 int xRate = keyCode == KeyEvent.KEYCODE_DPAD_LEFT 4125 ? -1 : keyCode == KeyEvent.KEYCODE_DPAD_RIGHT ? 1 : 0; 4126 int yRate = keyCode == KeyEvent.KEYCODE_DPAD_UP ? 4127 -1 : keyCode == KeyEvent.KEYCODE_DPAD_DOWN ? 1 : 0; 4128 int multiplier = event.getRepeatCount() + 1; 4129 moveSelection(xRate * multiplier, yRate * multiplier); 4130 return true; 4131 } 4132 if (navHandledKey(keyCode, 1, false, event.getEventTime())) { 4133 playSoundEffect(keyCodeToSoundsEffect(keyCode)); 4134 return true; 4135 } 4136 // Bubble up the key event as WebView doesn't handle it 4137 return false; 4138 } 4139 4140 if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { 4141 switchOutDrawHistory(); 4142 if (event.getRepeatCount() == 0) { 4143 if (mSelectingText) { 4144 return true; // discard press if copy in progress 4145 } 4146 mGotCenterDown = true; 4147 mPrivateHandler.sendMessageDelayed(mPrivateHandler 4148 .obtainMessage(LONG_PRESS_CENTER), LONG_PRESS_TIMEOUT); 4149 // Already checked mNativeClass, so we do not need to check it 4150 // again. 4151 nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true); 4152 return true; 4153 } 4154 // Bubble up the key event as WebView doesn't handle it 4155 return false; 4156 } 4157 4158 if (keyCode != KeyEvent.KEYCODE_SHIFT_LEFT 4159 && keyCode != KeyEvent.KEYCODE_SHIFT_RIGHT) { 4160 // turn off copy select if a shift-key combo is pressed 4161 selectionDone(); 4162 mShiftIsPressed = false; 4163 } 4164 4165 if (getSettings().getNavDump()) { 4166 switch (keyCode) { 4167 case KeyEvent.KEYCODE_4: 4168 dumpDisplayTree(); 4169 break; 4170 case KeyEvent.KEYCODE_5: 4171 case KeyEvent.KEYCODE_6: 4172 dumpDomTree(keyCode == KeyEvent.KEYCODE_5); 4173 break; 4174 case KeyEvent.KEYCODE_7: 4175 case KeyEvent.KEYCODE_8: 4176 dumpRenderTree(keyCode == KeyEvent.KEYCODE_7); 4177 break; 4178 case KeyEvent.KEYCODE_9: 4179 nativeInstrumentReport(); 4180 return true; 4181 } 4182 } 4183 4184 if (nativeCursorIsTextInput()) { 4185 // This message will put the node in focus, for the DOM's notion 4186 // of focus, and make the focuscontroller active 4187 mWebViewCore.sendMessage(EventHub.CLICK, nativeCursorFramePointer(), 4188 nativeCursorNodePointer()); 4189 // This will bring up the WebTextView and put it in focus, for 4190 // our view system's notion of focus 4191 rebuildWebTextView(); 4192 // Now we need to pass the event to it 4193 if (inEditingMode()) { 4194 mWebTextView.setDefaultSelection(); 4195 return mWebTextView.dispatchKeyEvent(event); 4196 } 4197 } else if (nativeHasFocusNode()) { 4198 // In this case, the cursor is not on a text input, but the focus 4199 // might be. Check it, and if so, hand over to the WebTextView. 4200 rebuildWebTextView(); 4201 if (inEditingMode()) { 4202 mWebTextView.setDefaultSelection(); 4203 return mWebTextView.dispatchKeyEvent(event); 4204 } 4205 } 4206 4207 // TODO: should we pass all the keys to DOM or check the meta tag 4208 if (nativeCursorWantsKeyEvents() || true) { 4209 // pass the key to DOM 4210 mWebViewCore.sendMessage(EventHub.KEY_DOWN, event); 4211 // return true as DOM handles the key 4212 return true; 4213 } 4214 4215 // Bubble up the key event as WebView doesn't handle it 4216 return false; 4217 } 4218 4219 @Override 4220 public boolean onKeyUp(int keyCode, KeyEvent event) { 4221 if (DebugFlags.WEB_VIEW) { 4222 Log.v(LOGTAG, "keyUp at " + System.currentTimeMillis() 4223 + ", " + event + ", unicode=" + event.getUnicodeChar()); 4224 } 4225 4226 if (mNativeClass == 0) { 4227 return false; 4228 } 4229 4230 // special CALL handling when cursor node's href is "tel:XXX" 4231 if (keyCode == KeyEvent.KEYCODE_CALL && nativeHasCursorNode()) { 4232 String text = nativeCursorText(); 4233 if (!nativeCursorIsTextInput() && text != null 4234 && text.startsWith(SCHEME_TEL)) { 4235 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(text)); 4236 getContext().startActivity(intent); 4237 return true; 4238 } 4239 } 4240 4241 // Bubble up the key event if 4242 // 1. it is a system key; or 4243 // 2. the host application wants to handle it; 4244 if (event.isSystem() || mCallbackProxy.uiOverrideKeyEvent(event)) { 4245 return false; 4246 } 4247 4248 if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT 4249 || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT) { 4250 if (nativeFocusIsPlugin()) { 4251 mShiftIsPressed = false; 4252 } else if (copySelection()) { 4253 selectionDone(); 4254 return true; 4255 } 4256 } 4257 4258 if (keyCode >= KeyEvent.KEYCODE_DPAD_UP 4259 && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) { 4260 if (nativeFocusIsPlugin()) { 4261 letPluginHandleNavKey(keyCode, event.getEventTime(), false); 4262 return true; 4263 } 4264 // always handle the navigation keys in the UI thread 4265 // Bubble up the key event as WebView doesn't handle it 4266 return false; 4267 } 4268 4269 if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { 4270 // remove the long press message first 4271 mPrivateHandler.removeMessages(LONG_PRESS_CENTER); 4272 mGotCenterDown = false; 4273 4274 if (mSelectingText) { 4275 if (mExtendSelection) { 4276 copySelection(); 4277 selectionDone(); 4278 } else { 4279 mExtendSelection = true; 4280 nativeSetExtendSelection(); 4281 invalidate(); // draw the i-beam instead of the arrow 4282 } 4283 return true; // discard press if copy in progress 4284 } 4285 4286 // perform the single click 4287 Rect visibleRect = sendOurVisibleRect(); 4288 // Note that sendOurVisibleRect calls viewToContent, so the 4289 // coordinates should be in content coordinates. 4290 if (!nativeCursorIntersects(visibleRect)) { 4291 return false; 4292 } 4293 WebViewCore.CursorData data = cursorData(); 4294 mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE, data); 4295 playSoundEffect(SoundEffectConstants.CLICK); 4296 if (nativeCursorIsTextInput()) { 4297 rebuildWebTextView(); 4298 centerKeyPressOnTextField(); 4299 if (inEditingMode()) { 4300 mWebTextView.setDefaultSelection(); 4301 } 4302 return true; 4303 } 4304 clearTextEntry(true); 4305 nativeSetFollowedLink(true); 4306 if (!mCallbackProxy.uiOverrideUrlLoading(nativeCursorText())) { 4307 mWebViewCore.sendMessage(EventHub.CLICK, data.mFrame, 4308 nativeCursorNodePointer()); 4309 } 4310 return true; 4311 } 4312 4313 // TODO: should we pass all the keys to DOM or check the meta tag 4314 if (nativeCursorWantsKeyEvents() || true) { 4315 // pass the key to DOM 4316 mWebViewCore.sendMessage(EventHub.KEY_UP, event); 4317 // return true as DOM handles the key 4318 return true; 4319 } 4320 4321 // Bubble up the key event as WebView doesn't handle it 4322 return false; 4323 } 4324 4325 /** 4326 * @hide pending API council approval. 4327 */ 4328 public void setUpSelect() { 4329 if (0 == mNativeClass) return; // client isn't initialized 4330 if (inFullScreenMode()) return; 4331 if (mSelectingText) return; 4332 mExtendSelection = false; 4333 mSelectingText = mDrawSelectionPointer = true; 4334 // don't let the picture change during text selection 4335 WebViewCore.pauseUpdatePicture(mWebViewCore); 4336 nativeResetSelection(); 4337 if (nativeHasCursorNode()) { 4338 Rect rect = nativeCursorNodeBounds(); 4339 mSelectX = contentToViewX(rect.left); 4340 mSelectY = contentToViewY(rect.top); 4341 } else if (mLastTouchY > getVisibleTitleHeight()) { 4342 mSelectX = mScrollX + (int) mLastTouchX; 4343 mSelectY = mScrollY + (int) mLastTouchY; 4344 } else { 4345 mSelectX = mScrollX + getViewWidth() / 2; 4346 mSelectY = mScrollY + getViewHeightWithTitle() / 2; 4347 } 4348 nativeHideCursor(); 4349 } 4350 4351 /** 4352 * Use this method to put the WebView into text selection mode. 4353 * Do not rely on this functionality; it will be deprecated in the future. 4354 */ 4355 public void emulateShiftHeld() { 4356 setUpSelect(); 4357 } 4358 4359 /** 4360 * @hide pending API council approval. 4361 */ 4362 public void selectAll() { 4363 if (0 == mNativeClass) return; // client isn't initialized 4364 if (inFullScreenMode()) return; 4365 if (!mSelectingText) setUpSelect(); 4366 nativeSelectAll(); 4367 mDrawSelectionPointer = false; 4368 mExtendSelection = true; 4369 invalidate(); 4370 } 4371 4372 /** 4373 * @hide pending API council approval. 4374 */ 4375 public boolean selectDialogIsUp() { 4376 return mSelectingText; 4377 } 4378 4379 /** 4380 * @hide pending API council approval. 4381 */ 4382 public void notifySelectDialogDismissed() { 4383 mSelectingText = false; 4384 WebViewCore.resumeUpdatePicture(mWebViewCore); 4385 } 4386 4387 /** 4388 * @hide pending API council approval. 4389 */ 4390 public void selectionDone() { 4391 if (mSelectingText) { 4392 WebChromeClient client = getWebChromeClient(); 4393 if (client != null) client.onSelectionDone(this); 4394 invalidate(); // redraw without selection 4395 notifySelectDialogDismissed(); 4396 } 4397 } 4398 4399 /** 4400 * @hide pending API council approval. 4401 */ 4402 public boolean copySelection() { 4403 boolean copiedSomething = false; 4404 String selection = getSelection(); 4405 if (selection != "") { 4406 if (DebugFlags.WEB_VIEW) { 4407 Log.v(LOGTAG, "copySelection \"" + selection + "\""); 4408 } 4409 Toast.makeText(mContext 4410 , com.android.internal.R.string.text_copied 4411 , Toast.LENGTH_SHORT).show(); 4412 copiedSomething = true; 4413 try { 4414 IClipboard clip = IClipboard.Stub.asInterface( 4415 ServiceManager.getService("clipboard")); 4416 clip.setClipboardText(selection); 4417 } catch (android.os.RemoteException e) { 4418 Log.e(LOGTAG, "Clipboard failed", e); 4419 } 4420 } 4421 invalidate(); // remove selection region and pointer 4422 return copiedSomething; 4423 } 4424 4425 /** 4426 * @hide pending API council approval. 4427 */ 4428 public String getSelection() { 4429 if (mNativeClass == 0) return ""; 4430 return nativeGetSelection(); 4431 } 4432 4433 @Override 4434 protected void onAttachedToWindow() { 4435 super.onAttachedToWindow(); 4436 if (hasWindowFocus()) setActive(true); 4437 } 4438 4439 @Override 4440 protected void onDetachedFromWindow() { 4441 clearHelpers(); 4442 dismissZoomControl(); 4443 if (hasWindowFocus()) setActive(false); 4444 super.onDetachedFromWindow(); 4445 } 4446 4447 /** 4448 * @deprecated WebView no longer needs to implement 4449 * ViewGroup.OnHierarchyChangeListener. This method does nothing now. 4450 */ 4451 @Deprecated 4452 public void onChildViewAdded(View parent, View child) {} 4453 4454 /** 4455 * @deprecated WebView no longer needs to implement 4456 * ViewGroup.OnHierarchyChangeListener. This method does nothing now. 4457 */ 4458 @Deprecated 4459 public void onChildViewRemoved(View p, View child) {} 4460 4461 /** 4462 * @deprecated WebView should not have implemented 4463 * ViewTreeObserver.OnGlobalFocusChangeListener. This method 4464 * does nothing now. 4465 */ 4466 @Deprecated 4467 public void onGlobalFocusChanged(View oldFocus, View newFocus) { 4468 } 4469 4470 private void setActive(boolean active) { 4471 if (active) { 4472 if (hasFocus()) { 4473 // If our window regained focus, and we have focus, then begin 4474 // drawing the cursor ring 4475 mDrawCursorRing = true; 4476 if (mNativeClass != 0) { 4477 nativeRecordButtons(true, false, true); 4478 if (inEditingMode()) { 4479 mWebViewCore.sendMessage(EventHub.SET_ACTIVE, 1, 0); 4480 } 4481 } 4482 } else { 4483 // If our window gained focus, but we do not have it, do not 4484 // draw the cursor ring. 4485 mDrawCursorRing = false; 4486 // We do not call nativeRecordButtons here because we assume 4487 // that when we lost focus, or window focus, it got called with 4488 // false for the first parameter 4489 } 4490 } else { 4491 if (mWebViewCore != null && getSettings().getBuiltInZoomControls() 4492 && (mZoomButtonsController == null || 4493 !mZoomButtonsController.isVisible())) { 4494 /* 4495 * The zoom controls come in their own window, so our window 4496 * loses focus. Our policy is to not draw the cursor ring if 4497 * our window is not focused, but this is an exception since 4498 * the user can still navigate the web page with the zoom 4499 * controls showing. 4500 */ 4501 // If our window has lost focus, stop drawing the cursor ring 4502 mDrawCursorRing = false; 4503 } 4504 mGotKeyDown = false; 4505 mShiftIsPressed = false; 4506 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 4507 mTouchMode = TOUCH_DONE_MODE; 4508 if (mNativeClass != 0) { 4509 nativeRecordButtons(false, false, true); 4510 } 4511 setFocusControllerInactive(); 4512 } 4513 invalidate(); 4514 } 4515 4516 // To avoid drawing the cursor ring, and remove the TextView when our window 4517 // loses focus. 4518 @Override 4519 public void onWindowFocusChanged(boolean hasWindowFocus) { 4520 setActive(hasWindowFocus); 4521 if (hasWindowFocus) { 4522 JWebCoreJavaBridge.setActiveWebView(this); 4523 } else { 4524 JWebCoreJavaBridge.removeActiveWebView(this); 4525 } 4526 super.onWindowFocusChanged(hasWindowFocus); 4527 } 4528 4529 /* 4530 * Pass a message to WebCore Thread, telling the WebCore::Page's 4531 * FocusController to be "inactive" so that it will 4532 * not draw the blinking cursor. It gets set to "active" to draw the cursor 4533 * in WebViewCore.cpp, when the WebCore thread receives key events/clicks. 4534 */ 4535 /* package */ void setFocusControllerInactive() { 4536 // Do not need to also check whether mWebViewCore is null, because 4537 // mNativeClass is only set if mWebViewCore is non null 4538 if (mNativeClass == 0) return; 4539 mWebViewCore.sendMessage(EventHub.SET_ACTIVE, 0, 0); 4540 } 4541 4542 @Override 4543 protected void onFocusChanged(boolean focused, int direction, 4544 Rect previouslyFocusedRect) { 4545 if (DebugFlags.WEB_VIEW) { 4546 Log.v(LOGTAG, "MT focusChanged " + focused + ", " + direction); 4547 } 4548 if (focused) { 4549 // When we regain focus, if we have window focus, resume drawing 4550 // the cursor ring 4551 if (hasWindowFocus()) { 4552 mDrawCursorRing = true; 4553 if (mNativeClass != 0) { 4554 nativeRecordButtons(true, false, true); 4555 } 4556 //} else { 4557 // The WebView has gained focus while we do not have 4558 // windowfocus. When our window lost focus, we should have 4559 // called nativeRecordButtons(false...) 4560 } 4561 } else { 4562 // When we lost focus, unless focus went to the TextView (which is 4563 // true if we are in editing mode), stop drawing the cursor ring. 4564 if (!inEditingMode()) { 4565 mDrawCursorRing = false; 4566 if (mNativeClass != 0) { 4567 nativeRecordButtons(false, false, true); 4568 } 4569 setFocusControllerInactive(); 4570 } 4571 mGotKeyDown = false; 4572 } 4573 4574 super.onFocusChanged(focused, direction, previouslyFocusedRect); 4575 } 4576 4577 /** 4578 * @hide 4579 */ 4580 @Override 4581 protected boolean setFrame(int left, int top, int right, int bottom) { 4582 boolean changed = super.setFrame(left, top, right, bottom); 4583 if (!changed && mHeightCanMeasure) { 4584 // When mHeightCanMeasure is true, we will set mLastHeightSent to 0 4585 // in WebViewCore after we get the first layout. We do call 4586 // requestLayout() when we get contentSizeChanged(). But the View 4587 // system won't call onSizeChanged if the dimension is not changed. 4588 // In this case, we need to call sendViewSizeZoom() explicitly to 4589 // notify the WebKit about the new dimensions. 4590 sendViewSizeZoom(); 4591 } 4592 return changed; 4593 } 4594 4595 private static class PostScale implements Runnable { 4596 final WebView mWebView; 4597 final boolean mUpdateTextWrap; 4598 4599 public PostScale(WebView webView, boolean updateTextWrap) { 4600 mWebView = webView; 4601 mUpdateTextWrap = updateTextWrap; 4602 } 4603 4604 public void run() { 4605 if (mWebView.mWebViewCore != null) { 4606 // we always force, in case our height changed, in which case we 4607 // still want to send the notification over to webkit. 4608 mWebView.setNewZoomScale(mWebView.mActualScale, 4609 mUpdateTextWrap, true); 4610 // update the zoom buttons as the scale can be changed 4611 if (mWebView.getSettings().getBuiltInZoomControls()) { 4612 mWebView.updateZoomButtonsEnabled(); 4613 } 4614 } 4615 } 4616 } 4617 4618 @Override 4619 protected void onSizeChanged(int w, int h, int ow, int oh) { 4620 super.onSizeChanged(w, h, ow, oh); 4621 // Center zooming to the center of the screen. 4622 if (mZoomScale == 0) { // unless we're already zooming 4623 // To anchor at top left corner. 4624 mZoomCenterX = 0; 4625 mZoomCenterY = getVisibleTitleHeight(); 4626 mAnchorX = viewToContentX((int) mZoomCenterX + mScrollX); 4627 mAnchorY = viewToContentY((int) mZoomCenterY + mScrollY); 4628 } 4629 4630 // adjust the max viewport width depending on the view dimensions. This 4631 // is to ensure the scaling is not going insane. So do not shrink it if 4632 // the view size is temporarily smaller, e.g. when soft keyboard is up. 4633 int newMaxViewportWidth = (int) (Math.max(w, h) / DEFAULT_MIN_ZOOM_SCALE); 4634 if (newMaxViewportWidth > sMaxViewportWidth) { 4635 sMaxViewportWidth = newMaxViewportWidth; 4636 } 4637 4638 // update mMinZoomScale if the minimum zoom scale is not fixed 4639 if (!mMinZoomScaleFixed) { 4640 // when change from narrow screen to wide screen, the new viewWidth 4641 // can be wider than the old content width. We limit the minimum 4642 // scale to 1.0f. The proper minimum scale will be calculated when 4643 // the new picture shows up. 4644 mMinZoomScale = Math.min(1.0f, (float) getViewWidth() 4645 / (mDrawHistory ? mHistoryPicture.getWidth() 4646 : mZoomOverviewWidth)); 4647 if (mInitialScaleInPercent > 0) { 4648 // limit the minZoomScale to the initialScale if it is set 4649 float initialScale = mInitialScaleInPercent / 100.0f; 4650 if (mMinZoomScale > initialScale) { 4651 mMinZoomScale = initialScale; 4652 } 4653 } 4654 } 4655 4656 dismissZoomControl(); 4657 4658 // onSizeChanged() is called during WebView layout. And any 4659 // requestLayout() is blocked during layout. As setNewZoomScale() will 4660 // call its child View to reposition itself through ViewManager's 4661 // scaleAll(), we need to post a Runnable to ensure requestLayout(). 4662 // <b/> 4663 // only update the text wrap scale if width changed. 4664 post(new PostScale(this, w != ow)); 4665 } 4666 4667 @Override 4668 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 4669 super.onScrollChanged(l, t, oldl, oldt); 4670 if (!mInOverScrollMode) { 4671 sendOurVisibleRect(); 4672 // update WebKit if visible title bar height changed. The logic is same 4673 // as getVisibleTitleHeight. 4674 int titleHeight = getTitleHeight(); 4675 if (Math.max(titleHeight - t, 0) != Math.max(titleHeight - oldt, 0)) { 4676 sendViewSizeZoom(); 4677 } 4678 } 4679 } 4680 4681 @Override 4682 public boolean dispatchKeyEvent(KeyEvent event) { 4683 boolean dispatch = true; 4684 4685 // Textfields and plugins need to receive the shift up key even if 4686 // another key was released while the shift key was held down. 4687 if (!inEditingMode() && (mNativeClass == 0 || !nativeFocusIsPlugin())) { 4688 if (event.getAction() == KeyEvent.ACTION_DOWN) { 4689 mGotKeyDown = true; 4690 } else { 4691 if (!mGotKeyDown) { 4692 /* 4693 * We got a key up for which we were not the recipient of 4694 * the original key down. Don't give it to the view. 4695 */ 4696 dispatch = false; 4697 } 4698 mGotKeyDown = false; 4699 } 4700 } 4701 4702 if (dispatch) { 4703 return super.dispatchKeyEvent(event); 4704 } else { 4705 // We didn't dispatch, so let something else handle the key 4706 return false; 4707 } 4708 } 4709 4710 // Here are the snap align logic: 4711 // 1. If it starts nearly horizontally or vertically, snap align; 4712 // 2. If there is a dramitic direction change, let it go; 4713 // 3. If there is a same direction back and forth, lock it. 4714 4715 // adjustable parameters 4716 private int mMinLockSnapReverseDistance; 4717 private static final float MAX_SLOPE_FOR_DIAG = 1.5f; 4718 private static final int MIN_BREAK_SNAP_CROSS_DISTANCE = 80; 4719 4720 private static int sign(float x) { 4721 return x > 0 ? 1 : (x < 0 ? -1 : 0); 4722 } 4723 4724 // if the page can scroll <= this value, we won't allow the drag tracker 4725 // to have any effect. 4726 private static final int MIN_SCROLL_AMOUNT_TO_DISABLE_DRAG_TRACKER = 4; 4727 4728 private class DragTrackerHandler { 4729 private final DragTracker mProxy; 4730 private final float mStartY, mStartX; 4731 private final float mMinDY, mMinDX; 4732 private final float mMaxDY, mMaxDX; 4733 private float mCurrStretchY, mCurrStretchX; 4734 private int mSX, mSY; 4735 private Interpolator mInterp; 4736 private float[] mXY = new float[2]; 4737 4738 // inner (non-state) classes can't have enums :( 4739 private static final int DRAGGING_STATE = 0; 4740 private static final int ANIMATING_STATE = 1; 4741 private static final int FINISHED_STATE = 2; 4742 private int mState; 4743 4744 public DragTrackerHandler(float x, float y, DragTracker proxy) { 4745 mProxy = proxy; 4746 4747 int docBottom = computeRealVerticalScrollRange() + getTitleHeight(); 4748 int viewTop = getScrollY(); 4749 int viewBottom = viewTop + getHeight(); 4750 4751 mStartY = y; 4752 mMinDY = -viewTop; 4753 mMaxDY = docBottom - viewBottom; 4754 4755 if (DebugFlags.DRAG_TRACKER || DEBUG_DRAG_TRACKER) { 4756 Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, " dragtracker y= " + y + 4757 " up/down= " + mMinDY + " " + mMaxDY); 4758 } 4759 4760 int docRight = computeRealHorizontalScrollRange(); 4761 int viewLeft = getScrollX(); 4762 int viewRight = viewLeft + getWidth(); 4763 mStartX = x; 4764 mMinDX = -viewLeft; 4765 mMaxDX = docRight - viewRight; 4766 4767 mState = DRAGGING_STATE; 4768 mProxy.onStartDrag(x, y); 4769 4770 // ensure we buildBitmap at least once 4771 mSX = -99999; 4772 } 4773 4774 private float computeStretch(float delta, float min, float max) { 4775 float stretch = 0; 4776 if (max - min > MIN_SCROLL_AMOUNT_TO_DISABLE_DRAG_TRACKER) { 4777 if (delta < min) { 4778 stretch = delta - min; 4779 } else if (delta > max) { 4780 stretch = delta - max; 4781 } 4782 } 4783 return stretch; 4784 } 4785 4786 public void dragTo(float x, float y) { 4787 float sy = computeStretch(mStartY - y, mMinDY, mMaxDY); 4788 float sx = computeStretch(mStartX - x, mMinDX, mMaxDX); 4789 4790 if ((mSnapScrollMode & SNAP_X) != 0) { 4791 sy = 0; 4792 } else if ((mSnapScrollMode & SNAP_Y) != 0) { 4793 sx = 0; 4794 } 4795 4796 if (mCurrStretchX != sx || mCurrStretchY != sy) { 4797 mCurrStretchX = sx; 4798 mCurrStretchY = sy; 4799 if (DebugFlags.DRAG_TRACKER || DEBUG_DRAG_TRACKER) { 4800 Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, "---- stretch " + sx + 4801 " " + sy); 4802 } 4803 if (mProxy.onStretchChange(sx, sy)) { 4804 invalidate(); 4805 } 4806 } 4807 } 4808 4809 public void stopDrag() { 4810 final int DURATION = 200; 4811 int now = (int)SystemClock.uptimeMillis(); 4812 mInterp = new Interpolator(2); 4813 mXY[0] = mCurrStretchX; 4814 mXY[1] = mCurrStretchY; 4815 // float[] blend = new float[] { 0.5f, 0, 0.75f, 1 }; 4816 float[] blend = new float[] { 0, 0.5f, 0.75f, 1 }; 4817 mInterp.setKeyFrame(0, now, mXY, blend); 4818 float[] zerozero = new float[] { 0, 0 }; 4819 mInterp.setKeyFrame(1, now + DURATION, zerozero, null); 4820 mState = ANIMATING_STATE; 4821 4822 if (DebugFlags.DRAG_TRACKER || DEBUG_DRAG_TRACKER) { 4823 Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, "----- stopDrag, starting animation"); 4824 } 4825 } 4826 4827 // Call this after each draw. If it ruturns null, the tracker is done 4828 public boolean isFinished() { 4829 return mState == FINISHED_STATE; 4830 } 4831 4832 private int hiddenHeightOfTitleBar() { 4833 return getTitleHeight() - getVisibleTitleHeight(); 4834 } 4835 4836 // need a way to know if 565 or 8888 is the right config for 4837 // capturing the display and giving it to the drag proxy 4838 private Bitmap.Config offscreenBitmapConfig() { 4839 // hard code 565 for now 4840 return Bitmap.Config.RGB_565; 4841 } 4842 4843 /* If the tracker draws, then this returns true, otherwise it will 4844 return false, and draw nothing. 4845 */ 4846 public boolean draw(Canvas canvas) { 4847 if (mCurrStretchX != 0 || mCurrStretchY != 0) { 4848 int sx = getScrollX(); 4849 int sy = getScrollY() - hiddenHeightOfTitleBar(); 4850 if (mSX != sx || mSY != sy) { 4851 buildBitmap(sx, sy); 4852 mSX = sx; 4853 mSY = sy; 4854 } 4855 4856 if (mState == ANIMATING_STATE) { 4857 Interpolator.Result result = mInterp.timeToValues(mXY); 4858 if (result == Interpolator.Result.FREEZE_END) { 4859 mState = FINISHED_STATE; 4860 return false; 4861 } else { 4862 mProxy.onStretchChange(mXY[0], mXY[1]); 4863 invalidate(); 4864 // fall through to the draw 4865 } 4866 } 4867 int count = canvas.save(Canvas.MATRIX_SAVE_FLAG); 4868 canvas.translate(sx, sy); 4869 mProxy.onDraw(canvas); 4870 canvas.restoreToCount(count); 4871 return true; 4872 } 4873 if (DebugFlags.DRAG_TRACKER || DEBUG_DRAG_TRACKER) { 4874 Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, " -- draw false " + 4875 mCurrStretchX + " " + mCurrStretchY); 4876 } 4877 return false; 4878 } 4879 4880 private void buildBitmap(int sx, int sy) { 4881 int w = getWidth(); 4882 int h = getViewHeight(); 4883 Bitmap bm = Bitmap.createBitmap(w, h, offscreenBitmapConfig()); 4884 Canvas canvas = new Canvas(bm); 4885 canvas.translate(-sx, -sy); 4886 drawContent(canvas); 4887 4888 if (DebugFlags.DRAG_TRACKER || DEBUG_DRAG_TRACKER) { 4889 Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, "--- buildBitmap " + sx + 4890 " " + sy + " " + w + " " + h); 4891 } 4892 mProxy.onBitmapChange(bm); 4893 } 4894 } 4895 4896 /** @hide */ 4897 public static class DragTracker { 4898 public void onStartDrag(float x, float y) {} 4899 public boolean onStretchChange(float sx, float sy) { 4900 // return true to have us inval the view 4901 return false; 4902 } 4903 public void onStopDrag() {} 4904 public void onBitmapChange(Bitmap bm) {} 4905 public void onDraw(Canvas canvas) {} 4906 } 4907 4908 /** @hide */ 4909 public DragTracker getDragTracker() { 4910 return mDragTracker; 4911 } 4912 4913 /** @hide */ 4914 public void setDragTracker(DragTracker tracker) { 4915 mDragTracker = tracker; 4916 } 4917 4918 private DragTracker mDragTracker; 4919 private DragTrackerHandler mDragTrackerHandler; 4920 4921 private class ScaleDetectorListener implements 4922 ScaleGestureDetector.OnScaleGestureListener { 4923 4924 public boolean onScaleBegin(ScaleGestureDetector detector) { 4925 // cancel the single touch handling 4926 cancelTouch(); 4927 dismissZoomControl(); 4928 // reset the zoom overview mode so that the page won't auto grow 4929 mInZoomOverview = false; 4930 // If it is in password mode, turn it off so it does not draw 4931 // misplaced. 4932 if (inEditingMode() && nativeFocusCandidateIsPassword()) { 4933 mWebTextView.setInPassword(false); 4934 } 4935 4936 mViewManager.startZoom(); 4937 4938 return true; 4939 } 4940 4941 public void onScaleEnd(ScaleGestureDetector detector) { 4942 if (mPreviewZoomOnly) { 4943 mPreviewZoomOnly = false; 4944 mAnchorX = viewToContentX((int) mZoomCenterX + mScrollX); 4945 mAnchorY = viewToContentY((int) mZoomCenterY + mScrollY); 4946 // don't reflow when zoom in; when zoom out, do reflow if the 4947 // new scale is almost minimum scale; 4948 boolean reflowNow = (mActualScale - mMinZoomScale 4949 <= MINIMUM_SCALE_INCREMENT) 4950 || ((mActualScale <= 0.8 * mTextWrapScale)); 4951 // force zoom after mPreviewZoomOnly is set to false so that the 4952 // new view size will be passed to the WebKit 4953 setNewZoomScale(mActualScale, reflowNow, true); 4954 // call invalidate() to draw without zoom filter 4955 invalidate(); 4956 } 4957 // adjust the edit text view if needed 4958 if (inEditingMode() && didUpdateTextViewBounds(false) 4959 && nativeFocusCandidateIsPassword()) { 4960 // If it is a password field, start drawing the 4961 // WebTextView once again. 4962 mWebTextView.setInPassword(true); 4963 } 4964 // start a drag, TOUCH_PINCH_DRAG, can't use TOUCH_INIT_MODE as it 4965 // may trigger the unwanted click, can't use TOUCH_DRAG_MODE as it 4966 // may trigger the unwanted fling. 4967 mTouchMode = TOUCH_PINCH_DRAG; 4968 mConfirmMove = true; 4969 startTouch(detector.getFocusX(), detector.getFocusY(), 4970 mLastTouchTime); 4971 4972 mViewManager.endZoom(); 4973 } 4974 4975 public boolean onScale(ScaleGestureDetector detector) { 4976 float scale = (float) (Math.round(detector.getScaleFactor() 4977 * mActualScale * 100) / 100.0); 4978 if (Math.abs(scale - mActualScale) >= MINIMUM_SCALE_INCREMENT) { 4979 mPreviewZoomOnly = true; 4980 // limit the scale change per step 4981 if (scale > mActualScale) { 4982 scale = Math.min(scale, mActualScale * 1.25f); 4983 } else { 4984 scale = Math.max(scale, mActualScale * 0.8f); 4985 } 4986 mZoomCenterX = detector.getFocusX(); 4987 mZoomCenterY = detector.getFocusY(); 4988 setNewZoomScale(scale, false, false); 4989 invalidate(); 4990 return true; 4991 } 4992 return false; 4993 } 4994 } 4995 4996 private boolean hitFocusedPlugin(int contentX, int contentY) { 4997 if (DebugFlags.WEB_VIEW) { 4998 Log.v(LOGTAG, "nativeFocusIsPlugin()=" + nativeFocusIsPlugin()); 4999 Rect r = nativeFocusNodeBounds(); 5000 Log.v(LOGTAG, "nativeFocusNodeBounds()=(" + r.left + ", " + r.top 5001 + ", " + r.right + ", " + r.bottom + ")"); 5002 } 5003 return nativeFocusIsPlugin() 5004 && nativeFocusNodeBounds().contains(contentX, contentY); 5005 } 5006 5007 private boolean shouldForwardTouchEvent() { 5008 return mFullScreenHolder != null || (mForwardTouchEvents 5009 && !mSelectingText 5010 && mPreventDefault != PREVENT_DEFAULT_IGNORE); 5011 } 5012 5013 private boolean inFullScreenMode() { 5014 return mFullScreenHolder != null; 5015 } 5016 5017 @Override 5018 public boolean onTouchEvent(MotionEvent ev) { 5019 if (mNativeClass == 0 || (!isClickable() && !isLongClickable())) { 5020 return false; 5021 } 5022 5023 if (DebugFlags.WEB_VIEW) { 5024 Log.v(LOGTAG, ev + " at " + ev.getEventTime() + " mTouchMode=" 5025 + mTouchMode); 5026 } 5027 5028 int action; 5029 float x, y; 5030 long eventTime = ev.getEventTime(); 5031 5032 // FIXME: we may consider to give WebKit an option to handle multi-touch 5033 // events later. 5034 if (mSupportMultiTouch && ev.getPointerCount() > 1) { 5035 if (mAllowPanAndScale || mMinZoomScale < mMaxZoomScale) { 5036 mScaleDetector.onTouchEvent(ev); 5037 if (mScaleDetector.isInProgress()) { 5038 mLastTouchTime = eventTime; 5039 if (!mAllowPanAndScale) { 5040 return true; 5041 } 5042 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 5043 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 5044 } 5045 x = mScaleDetector.getFocusX(); 5046 y = mScaleDetector.getFocusY(); 5047 action = ev.getAction() & MotionEvent.ACTION_MASK; 5048 if (action == MotionEvent.ACTION_POINTER_DOWN) { 5049 cancelTouch(); 5050 action = MotionEvent.ACTION_DOWN; 5051 } else if (action == MotionEvent.ACTION_POINTER_UP) { 5052 // set mLastTouchX/Y to the remaining point 5053 mLastTouchX = x; 5054 mLastTouchY = y; 5055 } else if (action == MotionEvent.ACTION_MOVE) { 5056 // negative x or y indicate it is on the edge, skip it. 5057 if (x < 0 || y < 0) { 5058 return true; 5059 } 5060 } 5061 } else { 5062 // if the page disallow zoom, skip multi-pointer action 5063 return true; 5064 } 5065 } else { 5066 action = ev.getAction(); 5067 x = ev.getX(); 5068 y = ev.getY(); 5069 } 5070 5071 // Due to the touch screen edge effect, a touch closer to the edge 5072 // always snapped to the edge. As getViewWidth() can be different from 5073 // getWidth() due to the scrollbar, adjusting the point to match 5074 // getViewWidth(). Same applied to the height. 5075 if (x > getViewWidth() - 1) { 5076 x = getViewWidth() - 1; 5077 } 5078 if (y > getViewHeightWithTitle() - 1) { 5079 y = getViewHeightWithTitle() - 1; 5080 } 5081 5082 float fDeltaX = mLastTouchX - x; 5083 float fDeltaY = mLastTouchY - y; 5084 int deltaX = (int) fDeltaX; 5085 int deltaY = (int) fDeltaY; 5086 int contentX = viewToContentX((int) x + mScrollX); 5087 int contentY = viewToContentY((int) y + mScrollY); 5088 5089 switch (action) { 5090 case MotionEvent.ACTION_DOWN: { 5091 mPreventDefault = PREVENT_DEFAULT_NO; 5092 mConfirmMove = false; 5093 if (!mScroller.isFinished()) { 5094 // stop the current scroll animation, but if this is 5095 // the start of a fling, allow it to add to the current 5096 // fling's velocity 5097 mScroller.abortAnimation(); 5098 mTouchMode = TOUCH_DRAG_START_MODE; 5099 mConfirmMove = true; 5100 mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY); 5101 } else if (mPrivateHandler.hasMessages(RELEASE_SINGLE_TAP)) { 5102 mPrivateHandler.removeMessages(RELEASE_SINGLE_TAP); 5103 if (deltaX * deltaX + deltaY * deltaY < mDoubleTapSlopSquare) { 5104 mTouchMode = TOUCH_DOUBLE_TAP_MODE; 5105 } else { 5106 // commit the short press action for the previous tap 5107 doShortPress(); 5108 mTouchMode = TOUCH_INIT_MODE; 5109 mDeferTouchProcess = (!inFullScreenMode() 5110 && mForwardTouchEvents) ? hitFocusedPlugin( 5111 contentX, contentY) : false; 5112 } 5113 } else { // the normal case 5114 mPreviewZoomOnly = false; 5115 mTouchMode = TOUCH_INIT_MODE; 5116 mDeferTouchProcess = (!inFullScreenMode() 5117 && mForwardTouchEvents) ? hitFocusedPlugin( 5118 contentX, contentY) : false; 5119 mWebViewCore.sendMessage( 5120 EventHub.UPDATE_FRAME_CACHE_IF_LOADING); 5121 if (mLogEvent && eventTime - mLastTouchUpTime < 1000) { 5122 EventLog.writeEvent(EventLogTags.BROWSER_DOUBLE_TAP_DURATION, 5123 (eventTime - mLastTouchUpTime), eventTime); 5124 } 5125 if (mSelectingText) { 5126 mDrawSelectionPointer = false; 5127 mSelectionStarted = nativeStartSelection(contentX, contentY); 5128 if (DebugFlags.WEB_VIEW) { 5129 Log.v(LOGTAG, "select=" + contentX + "," + contentY); 5130 } 5131 invalidate(); 5132 } 5133 } 5134 // Trigger the link 5135 if (mTouchMode == TOUCH_INIT_MODE 5136 || mTouchMode == TOUCH_DOUBLE_TAP_MODE) { 5137 mPrivateHandler.sendEmptyMessageDelayed( 5138 SWITCH_TO_SHORTPRESS, TAP_TIMEOUT); 5139 mPrivateHandler.sendEmptyMessageDelayed( 5140 SWITCH_TO_LONGPRESS, LONG_PRESS_TIMEOUT); 5141 if (inFullScreenMode() || mDeferTouchProcess) { 5142 mPreventDefault = PREVENT_DEFAULT_YES; 5143 } else if (mForwardTouchEvents) { 5144 mPreventDefault = PREVENT_DEFAULT_MAYBE_YES; 5145 } else { 5146 mPreventDefault = PREVENT_DEFAULT_NO; 5147 } 5148 // pass the touch events from UI thread to WebCore thread 5149 if (shouldForwardTouchEvent()) { 5150 TouchEventData ted = new TouchEventData(); 5151 ted.mAction = action; 5152 ted.mX = contentX; 5153 ted.mY = contentY; 5154 ted.mMetaState = ev.getMetaState(); 5155 ted.mReprocess = mDeferTouchProcess; 5156 if (mDeferTouchProcess) { 5157 // still needs to set them for compute deltaX/Y 5158 mLastTouchX = x; 5159 mLastTouchY = y; 5160 ted.mViewX = x; 5161 ted.mViewY = y; 5162 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 5163 break; 5164 } 5165 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 5166 if (!inFullScreenMode()) { 5167 mPrivateHandler.sendMessageDelayed(mPrivateHandler 5168 .obtainMessage(PREVENT_DEFAULT_TIMEOUT, 5169 action, 0), TAP_TIMEOUT); 5170 } 5171 } 5172 } 5173 startTouch(x, y, eventTime); 5174 break; 5175 } 5176 case MotionEvent.ACTION_MOVE: { 5177 boolean firstMove = false; 5178 if (!mConfirmMove && (deltaX * deltaX + deltaY * deltaY) 5179 >= mTouchSlopSquare) { 5180 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 5181 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 5182 mConfirmMove = true; 5183 firstMove = true; 5184 if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) { 5185 mTouchMode = TOUCH_INIT_MODE; 5186 } 5187 } 5188 // pass the touch events from UI thread to WebCore thread 5189 if (shouldForwardTouchEvent() && mConfirmMove && (firstMove 5190 || eventTime - mLastSentTouchTime > mCurrentTouchInterval)) { 5191 mLastSentTouchTime = eventTime; 5192 TouchEventData ted = new TouchEventData(); 5193 ted.mAction = action; 5194 ted.mX = contentX; 5195 ted.mY = contentY; 5196 ted.mMetaState = ev.getMetaState(); 5197 ted.mReprocess = mDeferTouchProcess; 5198 if (mDeferTouchProcess) { 5199 ted.mViewX = x; 5200 ted.mViewY = y; 5201 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 5202 break; 5203 } 5204 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 5205 if (firstMove && !inFullScreenMode()) { 5206 mPrivateHandler.sendMessageDelayed(mPrivateHandler 5207 .obtainMessage(PREVENT_DEFAULT_TIMEOUT, 5208 action, 0), TAP_TIMEOUT); 5209 } 5210 } 5211 if (mTouchMode == TOUCH_DONE_MODE 5212 || mPreventDefault == PREVENT_DEFAULT_YES) { 5213 // no dragging during scroll zoom animation, or when prevent 5214 // default is yes 5215 break; 5216 } 5217 if (mVelocityTracker == null) { 5218 Log.e(LOGTAG, "Got null mVelocityTracker when " 5219 + "mPreventDefault = " + mPreventDefault 5220 + " mDeferTouchProcess = " + mDeferTouchProcess 5221 + " mTouchMode = " + mTouchMode); 5222 } 5223 mVelocityTracker.addMovement(ev); 5224 if (mSelectingText && mSelectionStarted) { 5225 if (DebugFlags.WEB_VIEW) { 5226 Log.v(LOGTAG, "extend=" + contentX + "," + contentY); 5227 } 5228 nativeExtendSelection(contentX, contentY); 5229 invalidate(); 5230 break; 5231 } 5232 5233 if (mTouchMode != TOUCH_DRAG_MODE) { 5234 5235 if (!mConfirmMove) { 5236 break; 5237 } 5238 if (mPreventDefault == PREVENT_DEFAULT_MAYBE_YES 5239 || mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN) { 5240 // track mLastTouchTime as we may need to do fling at 5241 // ACTION_UP 5242 mLastTouchTime = eventTime; 5243 break; 5244 } 5245 5246 // Only lock dragging to one axis if we don't have a scale in progress. 5247 // Scaling implies free-roaming movement. Note we'll only ever get here 5248 // if mAllowPanAndScale is true. 5249 if (mScaleDetector != null && !mScaleDetector.isInProgress()) { 5250 // if it starts nearly horizontal or vertical, enforce it 5251 int ax = Math.abs(deltaX); 5252 int ay = Math.abs(deltaY); 5253 if (ax > MAX_SLOPE_FOR_DIAG * ay) { 5254 mSnapScrollMode = SNAP_X; 5255 mSnapPositive = deltaX > 0; 5256 } else if (ay > MAX_SLOPE_FOR_DIAG * ax) { 5257 mSnapScrollMode = SNAP_Y; 5258 mSnapPositive = deltaY > 0; 5259 } 5260 } 5261 5262 mTouchMode = TOUCH_DRAG_MODE; 5263 mLastTouchX = x; 5264 mLastTouchY = y; 5265 fDeltaX = 0.0f; 5266 fDeltaY = 0.0f; 5267 deltaX = 0; 5268 deltaY = 0; 5269 5270 startDrag(); 5271 } 5272 5273 if (mDragTrackerHandler != null) { 5274 mDragTrackerHandler.dragTo(x, y); 5275 } 5276 5277 // do pan 5278 boolean done = false; 5279 boolean keepScrollBarsVisible = false; 5280 if (Math.abs(fDeltaX) < 1.0f && Math.abs(fDeltaY) < 1.0f) { 5281 mLastTouchX = x; 5282 mLastTouchY = y; 5283 keepScrollBarsVisible = done = true; 5284 } else { 5285 if (mSnapScrollMode == SNAP_X || mSnapScrollMode == SNAP_Y) { 5286 int ax = Math.abs(deltaX); 5287 int ay = Math.abs(deltaY); 5288 if (mSnapScrollMode == SNAP_X) { 5289 // radical change means getting out of snap mode 5290 if (ay > MAX_SLOPE_FOR_DIAG * ax 5291 && ay > MIN_BREAK_SNAP_CROSS_DISTANCE) { 5292 mSnapScrollMode = SNAP_NONE; 5293 } 5294 // reverse direction means lock in the snap mode 5295 if (ax > MAX_SLOPE_FOR_DIAG * ay && 5296 (mSnapPositive 5297 ? deltaX < -mMinLockSnapReverseDistance 5298 : deltaX > mMinLockSnapReverseDistance)) { 5299 mSnapScrollMode |= SNAP_LOCK; 5300 } 5301 } else { 5302 // radical change means getting out of snap mode 5303 if (ax > MAX_SLOPE_FOR_DIAG * ay 5304 && ax > MIN_BREAK_SNAP_CROSS_DISTANCE) { 5305 mSnapScrollMode = SNAP_NONE; 5306 } 5307 // reverse direction means lock in the snap mode 5308 if (ay > MAX_SLOPE_FOR_DIAG * ax && 5309 (mSnapPositive 5310 ? deltaY < -mMinLockSnapReverseDistance 5311 : deltaY > mMinLockSnapReverseDistance)) { 5312 mSnapScrollMode |= SNAP_LOCK; 5313 } 5314 } 5315 } 5316 if (mSnapScrollMode != SNAP_NONE) { 5317 if ((mSnapScrollMode & SNAP_X) == SNAP_X) { 5318 deltaY = 0; 5319 } else { 5320 deltaX = 0; 5321 } 5322 } 5323 if ((deltaX | deltaY) != 0) { 5324 if (deltaX != 0) { 5325 mLastTouchX = x; 5326 } 5327 if (deltaY != 0) { 5328 mLastTouchY = y; 5329 } 5330 mHeldMotionless = MOTIONLESS_FALSE; 5331 } else { 5332 // keep the scrollbar on the screen even there is no 5333 // scroll 5334 mLastTouchX = x; 5335 mLastTouchY = y; 5336 keepScrollBarsVisible = true; 5337 } 5338 mLastTouchTime = eventTime; 5339 mUserScroll = true; 5340 } 5341 5342 doDrag(deltaX, deltaY); 5343 5344 if (keepScrollBarsVisible) { 5345 if (mHeldMotionless != MOTIONLESS_TRUE) { 5346 mHeldMotionless = MOTIONLESS_TRUE; 5347 invalidate(); 5348 } 5349 // keep the scrollbar on the screen even there is no scroll 5350 awakenScrollBars(ViewConfiguration.getScrollDefaultDelay(), 5351 false); 5352 // return false to indicate that we can't pan out of the 5353 // view space 5354 return !done; 5355 } 5356 break; 5357 } 5358 case MotionEvent.ACTION_UP: { 5359 // pass the touch events from UI thread to WebCore thread 5360 if (shouldForwardTouchEvent()) { 5361 TouchEventData ted = new TouchEventData(); 5362 ted.mAction = action; 5363 ted.mX = contentX; 5364 ted.mY = contentY; 5365 ted.mMetaState = ev.getMetaState(); 5366 ted.mReprocess = mDeferTouchProcess; 5367 if (mDeferTouchProcess) { 5368 ted.mViewX = x; 5369 ted.mViewY = y; 5370 } 5371 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 5372 } 5373 mLastTouchUpTime = eventTime; 5374 switch (mTouchMode) { 5375 case TOUCH_DOUBLE_TAP_MODE: // double tap 5376 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 5377 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 5378 if (inFullScreenMode() || mDeferTouchProcess) { 5379 TouchEventData ted = new TouchEventData(); 5380 ted.mAction = WebViewCore.ACTION_DOUBLETAP; 5381 ted.mX = contentX; 5382 ted.mY = contentY; 5383 ted.mMetaState = ev.getMetaState(); 5384 ted.mReprocess = mDeferTouchProcess; 5385 if (mDeferTouchProcess) { 5386 ted.mViewX = x; 5387 ted.mViewY = y; 5388 } 5389 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 5390 } else if (mPreventDefault != PREVENT_DEFAULT_YES){ 5391 doDoubleTap(); 5392 mTouchMode = TOUCH_DONE_MODE; 5393 } 5394 break; 5395 case TOUCH_INIT_MODE: // tap 5396 case TOUCH_SHORTPRESS_START_MODE: 5397 case TOUCH_SHORTPRESS_MODE: 5398 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 5399 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 5400 if (mConfirmMove) { 5401 Log.w(LOGTAG, "Miss a drag as we are waiting for" + 5402 " WebCore's response for touch down."); 5403 if (mPreventDefault != PREVENT_DEFAULT_YES 5404 && (computeMaxScrollX() > 0 5405 || computeMaxScrollY() > 0)) { 5406 // UI takes control back, cancel WebCore touch 5407 cancelWebCoreTouchEvent(contentX, contentY, 5408 true); 5409 // we will not rewrite drag code here, but we 5410 // will try fling if it applies. 5411 WebViewCore.reducePriority(); 5412 // to get better performance, pause updating the 5413 // picture 5414 WebViewCore.pauseUpdatePicture(mWebViewCore); 5415 // fall through to TOUCH_DRAG_MODE 5416 } else { 5417 // WebKit may consume the touch event and modify 5418 // DOM. drawContentPicture() will be called with 5419 // animateSroll as true for better performance. 5420 // Force redraw in high-quality. 5421 invalidate(); 5422 break; 5423 } 5424 } else { 5425 if (mSelectingText) { 5426 if (nativeHitSelection(contentX, contentY)) { 5427 copySelection(); 5428 } 5429 selectionDone(); 5430 break; 5431 } 5432 if (mTouchMode == TOUCH_INIT_MODE) { 5433 mPrivateHandler.sendEmptyMessageDelayed( 5434 RELEASE_SINGLE_TAP, ViewConfiguration 5435 .getDoubleTapTimeout()); 5436 } else { 5437 doShortPress(); 5438 } 5439 break; 5440 } 5441 case TOUCH_DRAG_MODE: 5442 mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS); 5443 mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS); 5444 // if the user waits a while w/o moving before the 5445 // up, we don't want to do a fling 5446 if (eventTime - mLastTouchTime <= MIN_FLING_TIME) { 5447 if (mVelocityTracker == null) { 5448 Log.e(LOGTAG, "Got null mVelocityTracker when " 5449 + "mPreventDefault = " 5450 + mPreventDefault 5451 + " mDeferTouchProcess = " 5452 + mDeferTouchProcess); 5453 } 5454 mVelocityTracker.addMovement(ev); 5455 // set to MOTIONLESS_IGNORE so that it won't keep 5456 // removing and sending message in 5457 // drawCoreAndCursorRing() 5458 mHeldMotionless = MOTIONLESS_IGNORE; 5459 doFling(); 5460 break; 5461 } else { 5462 if (mScroller.springBack(mScrollX, mScrollY, 0, 5463 computeMaxScrollX(), 0, 5464 computeMaxScrollY())) { 5465 invalidate(); 5466 } 5467 } 5468 // redraw in high-quality, as we're done dragging 5469 mHeldMotionless = MOTIONLESS_TRUE; 5470 invalidate(); 5471 // fall through 5472 case TOUCH_DRAG_START_MODE: 5473 // TOUCH_DRAG_START_MODE should not happen for the real 5474 // device as we almost certain will get a MOVE. But this 5475 // is possible on emulator. 5476 mLastVelocity = 0; 5477 WebViewCore.resumePriority(); 5478 WebViewCore.resumeUpdatePicture(mWebViewCore); 5479 break; 5480 } 5481 stopTouch(); 5482 break; 5483 } 5484 case MotionEvent.ACTION_CANCEL: { 5485 if (mTouchMode == TOUCH_DRAG_MODE) { 5486 mScroller.springBack(mScrollX, mScrollY, 0, 5487 computeMaxScrollX(), 0, computeMaxScrollY()); 5488 invalidate(); 5489 } 5490 cancelWebCoreTouchEvent(contentX, contentY, false); 5491 cancelTouch(); 5492 break; 5493 } 5494 } 5495 return true; 5496 } 5497 5498 private void cancelWebCoreTouchEvent(int x, int y, boolean removeEvents) { 5499 if (shouldForwardTouchEvent()) { 5500 if (removeEvents) { 5501 mWebViewCore.removeMessages(EventHub.TOUCH_EVENT); 5502 } 5503 TouchEventData ted = new TouchEventData(); 5504 ted.mX = x; 5505 ted.mY = y; 5506 ted.mAction = MotionEvent.ACTION_CANCEL; 5507 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 5508 mPreventDefault = PREVENT_DEFAULT_IGNORE; 5509 } 5510 } 5511 5512 private void startTouch(float x, float y, long eventTime) { 5513 // Remember where the motion event started 5514 mLastTouchX = x; 5515 mLastTouchY = y; 5516 mLastTouchTime = eventTime; 5517 mVelocityTracker = VelocityTracker.obtain(); 5518 mSnapScrollMode = SNAP_NONE; 5519 if (mDragTracker != null) { 5520 mDragTrackerHandler = new DragTrackerHandler(x, y, mDragTracker); 5521 } 5522 } 5523 5524 private void startDrag() { 5525 WebViewCore.reducePriority(); 5526 // to get better performance, pause updating the picture 5527 WebViewCore.pauseUpdatePicture(mWebViewCore); 5528 if (!mDragFromTextInput) { 5529 nativeHideCursor(); 5530 } 5531 WebSettings settings = getSettings(); 5532 if (settings.supportZoom() 5533 && settings.getBuiltInZoomControls() 5534 && !getZoomButtonsController().isVisible() 5535 && mMinZoomScale < mMaxZoomScale 5536 && (mHorizontalScrollBarMode != SCROLLBAR_ALWAYSOFF 5537 || mVerticalScrollBarMode != SCROLLBAR_ALWAYSOFF)) { 5538 mZoomButtonsController.setVisible(true); 5539 int count = settings.getDoubleTapToastCount(); 5540 if (mInZoomOverview && count > 0) { 5541 settings.setDoubleTapToastCount(--count); 5542 Toast.makeText(mContext, 5543 com.android.internal.R.string.double_tap_toast, 5544 Toast.LENGTH_LONG).show(); 5545 } 5546 } 5547 } 5548 5549 private void doDrag(int deltaX, int deltaY) { 5550 if ((deltaX | deltaY) != 0) { 5551 final int oldX = mScrollX; 5552 final int oldY = mScrollY; 5553 final int rangeX = computeMaxScrollX(); 5554 final int rangeY = computeMaxScrollY(); 5555 overScrollBy(deltaX, deltaY, oldX, oldY, 5556 rangeX, rangeY, 5557 mOverscrollDistance, mOverscrollDistance, true); 5558 5559 if (mEdgeGlowTop != null) { 5560 // Don't show left/right glows if we fit the whole content. 5561 if (rangeX > 0) { 5562 final int pulledToX = oldX + deltaX; 5563 if (pulledToX < 0) { 5564 mEdgeGlowLeft.onPull((float) deltaX / getWidth()); 5565 if (!mEdgeGlowRight.isFinished()) { 5566 mEdgeGlowRight.onRelease(); 5567 } 5568 } else if (pulledToX > rangeX) { 5569 mEdgeGlowRight.onPull((float) deltaX / getWidth()); 5570 if (!mEdgeGlowLeft.isFinished()) { 5571 mEdgeGlowLeft.onRelease(); 5572 } 5573 } 5574 } 5575 5576 if (rangeY > 0 || getOverScrollMode() == OVER_SCROLL_ALWAYS) { 5577 final int pulledToY = oldY + deltaY; 5578 if (pulledToY < 0) { 5579 mEdgeGlowTop.onPull((float) deltaY / getHeight()); 5580 if (!mEdgeGlowBottom.isFinished()) { 5581 mEdgeGlowBottom.onRelease(); 5582 } 5583 } else if (pulledToY > rangeY) { 5584 mEdgeGlowBottom.onPull((float) deltaY / getHeight()); 5585 if (!mEdgeGlowTop.isFinished()) { 5586 mEdgeGlowTop.onRelease(); 5587 } 5588 } 5589 } 5590 } 5591 } 5592 if (!getSettings().getBuiltInZoomControls()) { 5593 boolean showPlusMinus = mMinZoomScale < mMaxZoomScale; 5594 if (mZoomControls != null && showPlusMinus) { 5595 if (mZoomControls.getVisibility() == View.VISIBLE) { 5596 mPrivateHandler.removeCallbacks(mZoomControlRunnable); 5597 } else { 5598 mZoomControls.show(showPlusMinus, false); 5599 } 5600 mPrivateHandler.postDelayed(mZoomControlRunnable, 5601 ZOOM_CONTROLS_TIMEOUT); 5602 } 5603 } 5604 } 5605 5606 private void stopTouch() { 5607 if (mDragTrackerHandler != null) { 5608 mDragTrackerHandler.stopDrag(); 5609 } 5610 // we also use mVelocityTracker == null to tell us that we are 5611 // not "moving around", so we can take the slower/prettier 5612 // mode in the drawing code 5613 if (mVelocityTracker != null) { 5614 mVelocityTracker.recycle(); 5615 mVelocityTracker = null; 5616 } 5617 5618 // Release any pulled glows 5619 if (mEdgeGlowTop != null) { 5620 mEdgeGlowTop.onRelease(); 5621 mEdgeGlowBottom.onRelease(); 5622 mEdgeGlowLeft.onRelease(); 5623 mEdgeGlowRight.onRelease(); 5624 } 5625 } 5626 5627 private void cancelTouch() { 5628 if (mDragTrackerHandler != null) { 5629 mDragTrackerHandler.stopDrag(); 5630 } 5631 // we also use mVelocityTracker == null to tell us that we are 5632 // not "moving around", so we can take the slower/prettier 5633 // mode in the drawing code 5634 if (mVelocityTracker != null) { 5635 mVelocityTracker.recycle(); 5636 mVelocityTracker = null; 5637 } 5638 5639 // Release any pulled glows 5640 if (mEdgeGlowTop != null) { 5641 mEdgeGlowTop.onRelease(); 5642 mEdgeGlowBottom.onRelease(); 5643 mEdgeGlowLeft.onRelease(); 5644 mEdgeGlowRight.onRelease(); 5645 } 5646 5647 if (mTouchMode == TOUCH_DRAG_MODE) { 5648 WebViewCore.resumePriority(); 5649 WebViewCore.resumeUpdatePicture(mWebViewCore); 5650 } 5651 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 5652 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 5653 mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS); 5654 mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS); 5655 mHeldMotionless = MOTIONLESS_TRUE; 5656 mTouchMode = TOUCH_DONE_MODE; 5657 nativeHideCursor(); 5658 } 5659 5660 private long mTrackballFirstTime = 0; 5661 private long mTrackballLastTime = 0; 5662 private float mTrackballRemainsX = 0.0f; 5663 private float mTrackballRemainsY = 0.0f; 5664 private int mTrackballXMove = 0; 5665 private int mTrackballYMove = 0; 5666 private boolean mSelectingText = false; 5667 private boolean mSelectionStarted = false; 5668 private boolean mExtendSelection = false; 5669 private boolean mDrawSelectionPointer = false; 5670 private static final int TRACKBALL_KEY_TIMEOUT = 1000; 5671 private static final int TRACKBALL_TIMEOUT = 200; 5672 private static final int TRACKBALL_WAIT = 100; 5673 private static final int TRACKBALL_SCALE = 400; 5674 private static final int TRACKBALL_SCROLL_COUNT = 5; 5675 private static final int TRACKBALL_MOVE_COUNT = 10; 5676 private static final int TRACKBALL_MULTIPLIER = 3; 5677 private static final int SELECT_CURSOR_OFFSET = 16; 5678 private int mSelectX = 0; 5679 private int mSelectY = 0; 5680 private boolean mFocusSizeChanged = false; 5681 private boolean mShiftIsPressed = false; 5682 private boolean mTrackballDown = false; 5683 private long mTrackballUpTime = 0; 5684 private long mLastCursorTime = 0; 5685 private Rect mLastCursorBounds; 5686 5687 // Set by default; BrowserActivity clears to interpret trackball data 5688 // directly for movement. Currently, the framework only passes 5689 // arrow key events, not trackball events, from one child to the next 5690 private boolean mMapTrackballToArrowKeys = true; 5691 5692 public void setMapTrackballToArrowKeys(boolean setMap) { 5693 mMapTrackballToArrowKeys = setMap; 5694 } 5695 5696 void resetTrackballTime() { 5697 mTrackballLastTime = 0; 5698 } 5699 5700 @Override 5701 public boolean onTrackballEvent(MotionEvent ev) { 5702 long time = ev.getEventTime(); 5703 if ((ev.getMetaState() & KeyEvent.META_ALT_ON) != 0) { 5704 if (ev.getY() > 0) pageDown(true); 5705 if (ev.getY() < 0) pageUp(true); 5706 return true; 5707 } 5708 if (ev.getAction() == MotionEvent.ACTION_DOWN) { 5709 if (mSelectingText) { 5710 return true; // discard press if copy in progress 5711 } 5712 mTrackballDown = true; 5713 if (mNativeClass == 0) { 5714 return false; 5715 } 5716 nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true); 5717 if (time - mLastCursorTime <= TRACKBALL_TIMEOUT 5718 && !mLastCursorBounds.equals(nativeGetCursorRingBounds())) { 5719 nativeSelectBestAt(mLastCursorBounds); 5720 } 5721 if (DebugFlags.WEB_VIEW) { 5722 Log.v(LOGTAG, "onTrackballEvent down ev=" + ev 5723 + " time=" + time 5724 + " mLastCursorTime=" + mLastCursorTime); 5725 } 5726 if (isInTouchMode()) requestFocusFromTouch(); 5727 return false; // let common code in onKeyDown at it 5728 } 5729 if (ev.getAction() == MotionEvent.ACTION_UP) { 5730 // LONG_PRESS_CENTER is set in common onKeyDown 5731 mPrivateHandler.removeMessages(LONG_PRESS_CENTER); 5732 mTrackballDown = false; 5733 mTrackballUpTime = time; 5734 if (mSelectingText) { 5735 if (mExtendSelection) { 5736 copySelection(); 5737 selectionDone(); 5738 } else { 5739 mExtendSelection = true; 5740 nativeSetExtendSelection(); 5741 invalidate(); // draw the i-beam instead of the arrow 5742 } 5743 return true; // discard press if copy in progress 5744 } 5745 if (DebugFlags.WEB_VIEW) { 5746 Log.v(LOGTAG, "onTrackballEvent up ev=" + ev 5747 + " time=" + time 5748 ); 5749 } 5750 return false; // let common code in onKeyUp at it 5751 } 5752 if (mMapTrackballToArrowKeys && mShiftIsPressed == false) { 5753 if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent gmail quit"); 5754 return false; 5755 } 5756 if (mTrackballDown) { 5757 if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent down quit"); 5758 return true; // discard move if trackball is down 5759 } 5760 if (time - mTrackballUpTime < TRACKBALL_TIMEOUT) { 5761 if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent up timeout quit"); 5762 return true; 5763 } 5764 // TODO: alternatively we can do panning as touch does 5765 switchOutDrawHistory(); 5766 if (time - mTrackballLastTime > TRACKBALL_TIMEOUT) { 5767 if (DebugFlags.WEB_VIEW) { 5768 Log.v(LOGTAG, "onTrackballEvent time=" 5769 + time + " last=" + mTrackballLastTime); 5770 } 5771 mTrackballFirstTime = time; 5772 mTrackballXMove = mTrackballYMove = 0; 5773 } 5774 mTrackballLastTime = time; 5775 if (DebugFlags.WEB_VIEW) { 5776 Log.v(LOGTAG, "onTrackballEvent ev=" + ev + " time=" + time); 5777 } 5778 mTrackballRemainsX += ev.getX(); 5779 mTrackballRemainsY += ev.getY(); 5780 doTrackball(time); 5781 return true; 5782 } 5783 5784 void moveSelection(float xRate, float yRate) { 5785 if (mNativeClass == 0) 5786 return; 5787 int width = getViewWidth(); 5788 int height = getViewHeight(); 5789 mSelectX += xRate; 5790 mSelectY += yRate; 5791 int maxX = width + mScrollX; 5792 int maxY = height + mScrollY; 5793 mSelectX = Math.min(maxX, Math.max(mScrollX - SELECT_CURSOR_OFFSET 5794 , mSelectX)); 5795 mSelectY = Math.min(maxY, Math.max(mScrollY - SELECT_CURSOR_OFFSET 5796 , mSelectY)); 5797 if (DebugFlags.WEB_VIEW) { 5798 Log.v(LOGTAG, "moveSelection" 5799 + " mSelectX=" + mSelectX 5800 + " mSelectY=" + mSelectY 5801 + " mScrollX=" + mScrollX 5802 + " mScrollY=" + mScrollY 5803 + " xRate=" + xRate 5804 + " yRate=" + yRate 5805 ); 5806 } 5807 nativeMoveSelection(viewToContentX(mSelectX), viewToContentY(mSelectY)); 5808 int scrollX = mSelectX < mScrollX ? -SELECT_CURSOR_OFFSET 5809 : mSelectX > maxX - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET 5810 : 0; 5811 int scrollY = mSelectY < mScrollY ? -SELECT_CURSOR_OFFSET 5812 : mSelectY > maxY - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET 5813 : 0; 5814 pinScrollBy(scrollX, scrollY, true, 0); 5815 Rect select = new Rect(mSelectX, mSelectY, mSelectX + 1, mSelectY + 1); 5816 requestRectangleOnScreen(select); 5817 invalidate(); 5818 } 5819 5820 private int scaleTrackballX(float xRate, int width) { 5821 int xMove = (int) (xRate / TRACKBALL_SCALE * width); 5822 int nextXMove = xMove; 5823 if (xMove > 0) { 5824 if (xMove > mTrackballXMove) { 5825 xMove -= mTrackballXMove; 5826 } 5827 } else if (xMove < mTrackballXMove) { 5828 xMove -= mTrackballXMove; 5829 } 5830 mTrackballXMove = nextXMove; 5831 return xMove; 5832 } 5833 5834 private int scaleTrackballY(float yRate, int height) { 5835 int yMove = (int) (yRate / TRACKBALL_SCALE * height); 5836 int nextYMove = yMove; 5837 if (yMove > 0) { 5838 if (yMove > mTrackballYMove) { 5839 yMove -= mTrackballYMove; 5840 } 5841 } else if (yMove < mTrackballYMove) { 5842 yMove -= mTrackballYMove; 5843 } 5844 mTrackballYMove = nextYMove; 5845 return yMove; 5846 } 5847 5848 private int keyCodeToSoundsEffect(int keyCode) { 5849 switch(keyCode) { 5850 case KeyEvent.KEYCODE_DPAD_UP: 5851 return SoundEffectConstants.NAVIGATION_UP; 5852 case KeyEvent.KEYCODE_DPAD_RIGHT: 5853 return SoundEffectConstants.NAVIGATION_RIGHT; 5854 case KeyEvent.KEYCODE_DPAD_DOWN: 5855 return SoundEffectConstants.NAVIGATION_DOWN; 5856 case KeyEvent.KEYCODE_DPAD_LEFT: 5857 return SoundEffectConstants.NAVIGATION_LEFT; 5858 } 5859 throw new IllegalArgumentException("keyCode must be one of " + 5860 "{KEYCODE_DPAD_UP, KEYCODE_DPAD_RIGHT, KEYCODE_DPAD_DOWN, " + 5861 "KEYCODE_DPAD_LEFT}."); 5862 } 5863 5864 private void doTrackball(long time) { 5865 int elapsed = (int) (mTrackballLastTime - mTrackballFirstTime); 5866 if (elapsed == 0) { 5867 elapsed = TRACKBALL_TIMEOUT; 5868 } 5869 float xRate = mTrackballRemainsX * 1000 / elapsed; 5870 float yRate = mTrackballRemainsY * 1000 / elapsed; 5871 int viewWidth = getViewWidth(); 5872 int viewHeight = getViewHeight(); 5873 if (mSelectingText) { 5874 if (!mDrawSelectionPointer) { 5875 // The last selection was made by touch, disabling drawing the 5876 // selection pointer. Allow the trackball to adjust the 5877 // position of the touch control. 5878 mSelectX = contentToViewX(nativeSelectionX()); 5879 mSelectY = contentToViewY(nativeSelectionY()); 5880 mDrawSelectionPointer = mExtendSelection = true; 5881 nativeSetExtendSelection(); 5882 } 5883 moveSelection(scaleTrackballX(xRate, viewWidth), 5884 scaleTrackballY(yRate, viewHeight)); 5885 mTrackballRemainsX = mTrackballRemainsY = 0; 5886 return; 5887 } 5888 float ax = Math.abs(xRate); 5889 float ay = Math.abs(yRate); 5890 float maxA = Math.max(ax, ay); 5891 if (DebugFlags.WEB_VIEW) { 5892 Log.v(LOGTAG, "doTrackball elapsed=" + elapsed 5893 + " xRate=" + xRate 5894 + " yRate=" + yRate 5895 + " mTrackballRemainsX=" + mTrackballRemainsX 5896 + " mTrackballRemainsY=" + mTrackballRemainsY); 5897 } 5898 int width = mContentWidth - viewWidth; 5899 int height = mContentHeight - viewHeight; 5900 if (width < 0) width = 0; 5901 if (height < 0) height = 0; 5902 ax = Math.abs(mTrackballRemainsX * TRACKBALL_MULTIPLIER); 5903 ay = Math.abs(mTrackballRemainsY * TRACKBALL_MULTIPLIER); 5904 maxA = Math.max(ax, ay); 5905 int count = Math.max(0, (int) maxA); 5906 int oldScrollX = mScrollX; 5907 int oldScrollY = mScrollY; 5908 if (count > 0) { 5909 int selectKeyCode = ax < ay ? mTrackballRemainsY < 0 ? 5910 KeyEvent.KEYCODE_DPAD_UP : KeyEvent.KEYCODE_DPAD_DOWN : 5911 mTrackballRemainsX < 0 ? KeyEvent.KEYCODE_DPAD_LEFT : 5912 KeyEvent.KEYCODE_DPAD_RIGHT; 5913 count = Math.min(count, TRACKBALL_MOVE_COUNT); 5914 if (DebugFlags.WEB_VIEW) { 5915 Log.v(LOGTAG, "doTrackball keyCode=" + selectKeyCode 5916 + " count=" + count 5917 + " mTrackballRemainsX=" + mTrackballRemainsX 5918 + " mTrackballRemainsY=" + mTrackballRemainsY); 5919 } 5920 if (mNativeClass != 0 && nativeFocusIsPlugin()) { 5921 for (int i = 0; i < count; i++) { 5922 letPluginHandleNavKey(selectKeyCode, time, true); 5923 } 5924 letPluginHandleNavKey(selectKeyCode, time, false); 5925 } else if (navHandledKey(selectKeyCode, count, false, time)) { 5926 playSoundEffect(keyCodeToSoundsEffect(selectKeyCode)); 5927 } 5928 mTrackballRemainsX = mTrackballRemainsY = 0; 5929 } 5930 if (count >= TRACKBALL_SCROLL_COUNT) { 5931 int xMove = scaleTrackballX(xRate, width); 5932 int yMove = scaleTrackballY(yRate, height); 5933 if (DebugFlags.WEB_VIEW) { 5934 Log.v(LOGTAG, "doTrackball pinScrollBy" 5935 + " count=" + count 5936 + " xMove=" + xMove + " yMove=" + yMove 5937 + " mScrollX-oldScrollX=" + (mScrollX-oldScrollX) 5938 + " mScrollY-oldScrollY=" + (mScrollY-oldScrollY) 5939 ); 5940 } 5941 if (Math.abs(mScrollX - oldScrollX) > Math.abs(xMove)) { 5942 xMove = 0; 5943 } 5944 if (Math.abs(mScrollY - oldScrollY) > Math.abs(yMove)) { 5945 yMove = 0; 5946 } 5947 if (xMove != 0 || yMove != 0) { 5948 pinScrollBy(xMove, yMove, true, 0); 5949 } 5950 mUserScroll = true; 5951 } 5952 } 5953 5954 private int computeMaxScrollX() { 5955 return Math.max(computeRealHorizontalScrollRange() - getViewWidth(), 0); 5956 } 5957 5958 private int computeMaxScrollY() { 5959 return Math.max(computeRealVerticalScrollRange() + getTitleHeight() 5960 - getViewHeightWithTitle(), 0); 5961 } 5962 5963 public void flingScroll(int vx, int vy) { 5964 mScroller.fling(mScrollX, mScrollY, vx, vy, 0, computeMaxScrollX(), 0, 5965 computeMaxScrollY(), mOverflingDistance, mOverflingDistance); 5966 invalidate(); 5967 } 5968 5969 private void doFling() { 5970 if (mVelocityTracker == null) { 5971 return; 5972 } 5973 int maxX = computeMaxScrollX(); 5974 int maxY = computeMaxScrollY(); 5975 5976 mVelocityTracker.computeCurrentVelocity(1000, mMaximumFling); 5977 int vx = (int) mVelocityTracker.getXVelocity(); 5978 int vy = (int) mVelocityTracker.getYVelocity(); 5979 5980 if (mSnapScrollMode != SNAP_NONE) { 5981 if ((mSnapScrollMode & SNAP_X) == SNAP_X) { 5982 vy = 0; 5983 } else { 5984 vx = 0; 5985 } 5986 } 5987 if (true /* EMG release: make our fling more like Maps' */) { 5988 // maps cuts their velocity in half 5989 vx = vx * 3 / 4; 5990 vy = vy * 3 / 4; 5991 } 5992 if ((maxX == 0 && vy == 0) || (maxY == 0 && vx == 0)) { 5993 WebViewCore.resumePriority(); 5994 WebViewCore.resumeUpdatePicture(mWebViewCore); 5995 if (mScroller.springBack(mScrollX, mScrollY, 0, computeMaxScrollX(), 5996 0, computeMaxScrollY())) { 5997 invalidate(); 5998 } 5999 return; 6000 } 6001 float currentVelocity = mScroller.getCurrVelocity(); 6002 if (mLastVelocity > 0 && currentVelocity > 0) { 6003 float deltaR = (float) (Math.abs(Math.atan2(mLastVelY, mLastVelX) 6004 - Math.atan2(vy, vx))); 6005 final float circle = (float) (Math.PI) * 2.0f; 6006 if (deltaR > circle * 0.9f || deltaR < circle * 0.1f) { 6007 vx += currentVelocity * mLastVelX / mLastVelocity; 6008 vy += currentVelocity * mLastVelY / mLastVelocity; 6009 if (DebugFlags.WEB_VIEW) { 6010 Log.v(LOGTAG, "doFling vx= " + vx + " vy=" + vy); 6011 } 6012 } else if (DebugFlags.WEB_VIEW) { 6013 Log.v(LOGTAG, "doFling missed " + deltaR / circle); 6014 } 6015 } else if (DebugFlags.WEB_VIEW) { 6016 Log.v(LOGTAG, "doFling start last=" + mLastVelocity 6017 + " current=" + currentVelocity 6018 + " vx=" + vx + " vy=" + vy 6019 + " maxX=" + maxX + " maxY=" + maxY 6020 + " mScrollX=" + mScrollX + " mScrollY=" + mScrollY); 6021 } 6022 6023 // Allow sloppy flings without overscrolling at the edges. 6024 if ((mScrollX == 0 || mScrollX == maxX) && Math.abs(vx) < Math.abs(vy)) { 6025 vx = 0; 6026 } 6027 if ((mScrollY == 0 || mScrollY == maxY) && Math.abs(vy) < Math.abs(vx)) { 6028 vy = 0; 6029 } 6030 6031 if (mOverscrollDistance < mOverflingDistance) { 6032 if (mScrollX == -mOverscrollDistance || mScrollX == maxX + mOverscrollDistance) { 6033 vx = 0; 6034 } 6035 if (mScrollY == -mOverscrollDistance || mScrollY == maxY + mOverscrollDistance) { 6036 vy = 0; 6037 } 6038 } 6039 6040 mLastVelX = vx; 6041 mLastVelY = vy; 6042 mLastVelocity = (float) Math.hypot(vx, vy); 6043 6044 // no horizontal overscroll if the content just fits 6045 mScroller.fling(mScrollX, mScrollY, -vx, -vy, 0, maxX, 0, maxY, 6046 maxX == 0 ? 0 : mOverflingDistance, mOverflingDistance); 6047 // Duration is calculated based on velocity. With range boundaries and overscroll 6048 // we may not know how long the final animation will take. (Hence the deprecation 6049 // warning on the call below.) It's not a big deal for scroll bars but if webcore 6050 // resumes during this effect we will take a performance hit. See computeScroll; 6051 // we resume webcore there when the animation is finished. 6052 final int time = mScroller.getDuration(); 6053 awakenScrollBars(time); 6054 invalidate(); 6055 } 6056 6057 private boolean zoomWithPreview(float scale, boolean updateTextWrapScale) { 6058 float oldScale = mActualScale; 6059 mInitialScrollX = mScrollX; 6060 mInitialScrollY = mScrollY; 6061 6062 // snap to DEFAULT_SCALE if it is close 6063 if (Math.abs(scale - mDefaultScale) < MINIMUM_SCALE_INCREMENT) { 6064 scale = mDefaultScale; 6065 } 6066 6067 setNewZoomScale(scale, updateTextWrapScale, false); 6068 6069 if (oldScale != mActualScale) { 6070 // use mZoomPickerScale to see zoom preview first 6071 mZoomStart = SystemClock.uptimeMillis(); 6072 mInvInitialZoomScale = 1.0f / oldScale; 6073 mInvFinalZoomScale = 1.0f / mActualScale; 6074 mZoomScale = mActualScale; 6075 WebViewCore.pauseUpdatePicture(mWebViewCore); 6076 invalidate(); 6077 return true; 6078 } else { 6079 return false; 6080 } 6081 } 6082 6083 /** 6084 * Returns a view containing zoom controls i.e. +/- buttons. The caller is 6085 * in charge of installing this view to the view hierarchy. This view will 6086 * become visible when the user starts scrolling via touch and fade away if 6087 * the user does not interact with it. 6088 * <p/> 6089 * API version 3 introduces a built-in zoom mechanism that is shown 6090 * automatically by the MapView. This is the preferred approach for 6091 * showing the zoom UI. 6092 * 6093 * @deprecated The built-in zoom mechanism is preferred, see 6094 * {@link WebSettings#setBuiltInZoomControls(boolean)}. 6095 */ 6096 @Deprecated 6097 public View getZoomControls() { 6098 if (!getSettings().supportZoom()) { 6099 Log.w(LOGTAG, "This WebView doesn't support zoom."); 6100 return null; 6101 } 6102 if (mZoomControls == null) { 6103 mZoomControls = createZoomControls(); 6104 6105 /* 6106 * need to be set to VISIBLE first so that getMeasuredHeight() in 6107 * {@link #onSizeChanged()} can return the measured value for proper 6108 * layout. 6109 */ 6110 mZoomControls.setVisibility(View.VISIBLE); 6111 mZoomControlRunnable = new Runnable() { 6112 public void run() { 6113 6114 /* Don't dismiss the controls if the user has 6115 * focus on them. Wait and check again later. 6116 */ 6117 if (!mZoomControls.hasFocus()) { 6118 mZoomControls.hide(); 6119 } else { 6120 mPrivateHandler.removeCallbacks(mZoomControlRunnable); 6121 mPrivateHandler.postDelayed(mZoomControlRunnable, 6122 ZOOM_CONTROLS_TIMEOUT); 6123 } 6124 } 6125 }; 6126 } 6127 return mZoomControls; 6128 } 6129 6130 private ExtendedZoomControls createZoomControls() { 6131 ExtendedZoomControls zoomControls = new ExtendedZoomControls(mContext 6132 , null); 6133 zoomControls.setOnZoomInClickListener(new OnClickListener() { 6134 public void onClick(View v) { 6135 // reset time out 6136 mPrivateHandler.removeCallbacks(mZoomControlRunnable); 6137 mPrivateHandler.postDelayed(mZoomControlRunnable, 6138 ZOOM_CONTROLS_TIMEOUT); 6139 zoomIn(); 6140 } 6141 }); 6142 zoomControls.setOnZoomOutClickListener(new OnClickListener() { 6143 public void onClick(View v) { 6144 // reset time out 6145 mPrivateHandler.removeCallbacks(mZoomControlRunnable); 6146 mPrivateHandler.postDelayed(mZoomControlRunnable, 6147 ZOOM_CONTROLS_TIMEOUT); 6148 zoomOut(); 6149 } 6150 }); 6151 return zoomControls; 6152 } 6153 6154 /** 6155 * Gets the {@link ZoomButtonsController} which can be used to add 6156 * additional buttons to the zoom controls window. 6157 * 6158 * @return The instance of {@link ZoomButtonsController} used by this class, 6159 * or null if it is unavailable. 6160 * @hide 6161 */ 6162 public ZoomButtonsController getZoomButtonsController() { 6163 if (mZoomButtonsController == null) { 6164 mZoomButtonsController = new ZoomButtonsController(this); 6165 mZoomButtonsController.setOnZoomListener(mZoomListener); 6166 // ZoomButtonsController positions the buttons at the bottom, but in 6167 // the middle. Change their layout parameters so they appear on the 6168 // right. 6169 View controls = mZoomButtonsController.getZoomControls(); 6170 ViewGroup.LayoutParams params = controls.getLayoutParams(); 6171 if (params instanceof FrameLayout.LayoutParams) { 6172 FrameLayout.LayoutParams frameParams = (FrameLayout.LayoutParams) params; 6173 frameParams.gravity = Gravity.RIGHT; 6174 } 6175 } 6176 return mZoomButtonsController; 6177 } 6178 6179 /** 6180 * Perform zoom in in the webview 6181 * @return TRUE if zoom in succeeds. FALSE if no zoom changes. 6182 */ 6183 public boolean zoomIn() { 6184 // TODO: alternatively we can disallow this during draw history mode 6185 switchOutDrawHistory(); 6186 mInZoomOverview = false; 6187 // Center zooming to the center of the screen. 6188 mZoomCenterX = getViewWidth() * .5f; 6189 mZoomCenterY = getViewHeight() * .5f; 6190 mAnchorX = viewToContentX((int) mZoomCenterX + mScrollX); 6191 mAnchorY = viewToContentY((int) mZoomCenterY + mScrollY); 6192 return zoomWithPreview(mActualScale * 1.25f, true); 6193 } 6194 6195 /** 6196 * Perform zoom out in the webview 6197 * @return TRUE if zoom out succeeds. FALSE if no zoom changes. 6198 */ 6199 public boolean zoomOut() { 6200 // TODO: alternatively we can disallow this during draw history mode 6201 switchOutDrawHistory(); 6202 // Center zooming to the center of the screen. 6203 mZoomCenterX = getViewWidth() * .5f; 6204 mZoomCenterY = getViewHeight() * .5f; 6205 mAnchorX = viewToContentX((int) mZoomCenterX + mScrollX); 6206 mAnchorY = viewToContentY((int) mZoomCenterY + mScrollY); 6207 return zoomWithPreview(mActualScale * 0.8f, true); 6208 } 6209 6210 private void updateSelection() { 6211 if (mNativeClass == 0) { 6212 return; 6213 } 6214 // mLastTouchX and mLastTouchY are the point in the current viewport 6215 int contentX = viewToContentX((int) mLastTouchX + mScrollX); 6216 int contentY = viewToContentY((int) mLastTouchY + mScrollY); 6217 Rect rect = new Rect(contentX - mNavSlop, contentY - mNavSlop, 6218 contentX + mNavSlop, contentY + mNavSlop); 6219 nativeSelectBestAt(rect); 6220 } 6221 6222 /** 6223 * Scroll the focused text field/area to match the WebTextView 6224 * @param xPercent New x position of the WebTextView from 0 to 1. 6225 * @param y New y position of the WebTextView in view coordinates 6226 */ 6227 /*package*/ void scrollFocusedTextInput(float xPercent, int y) { 6228 if (!inEditingMode() || mWebViewCore == null) { 6229 return; 6230 } 6231 mWebViewCore.sendMessage(EventHub.SCROLL_TEXT_INPUT, 6232 // Since this position is relative to the top of the text input 6233 // field, we do not need to take the title bar's height into 6234 // consideration. 6235 viewToContentDimension(y), 6236 new Float(xPercent)); 6237 } 6238 6239 /** 6240 * Set our starting point and time for a drag from the WebTextView. 6241 */ 6242 /*package*/ void initiateTextFieldDrag(float x, float y, long eventTime) { 6243 if (!inEditingMode()) { 6244 return; 6245 } 6246 mLastTouchX = x + (float) (mWebTextView.getLeft() - mScrollX); 6247 mLastTouchY = y + (float) (mWebTextView.getTop() - mScrollY); 6248 mLastTouchTime = eventTime; 6249 if (!mScroller.isFinished()) { 6250 abortAnimation(); 6251 mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY); 6252 } 6253 mSnapScrollMode = SNAP_NONE; 6254 mVelocityTracker = VelocityTracker.obtain(); 6255 mTouchMode = TOUCH_DRAG_START_MODE; 6256 } 6257 6258 /** 6259 * Given a motion event from the WebTextView, set its location to our 6260 * coordinates, and handle the event. 6261 */ 6262 /*package*/ boolean textFieldDrag(MotionEvent event) { 6263 if (!inEditingMode()) { 6264 return false; 6265 } 6266 mDragFromTextInput = true; 6267 event.offsetLocation((float) (mWebTextView.getLeft() - mScrollX), 6268 (float) (mWebTextView.getTop() - mScrollY)); 6269 boolean result = onTouchEvent(event); 6270 mDragFromTextInput = false; 6271 return result; 6272 } 6273 6274 /** 6275 * Due a touch up from a WebTextView. This will be handled by webkit to 6276 * change the selection. 6277 * @param event MotionEvent in the WebTextView's coordinates. 6278 */ 6279 /*package*/ void touchUpOnTextField(MotionEvent event) { 6280 if (!inEditingMode()) { 6281 return; 6282 } 6283 int x = viewToContentX((int) event.getX() + mWebTextView.getLeft()); 6284 int y = viewToContentY((int) event.getY() + mWebTextView.getTop()); 6285 nativeMotionUp(x, y, mNavSlop); 6286 } 6287 6288 /** 6289 * Called when pressing the center key or trackball on a textfield. 6290 */ 6291 /*package*/ void centerKeyPressOnTextField() { 6292 mWebViewCore.sendMessage(EventHub.CLICK, nativeCursorFramePointer(), 6293 nativeCursorNodePointer()); 6294 } 6295 6296 private void doShortPress() { 6297 if (mNativeClass == 0) { 6298 return; 6299 } 6300 if (mPreventDefault == PREVENT_DEFAULT_YES) { 6301 return; 6302 } 6303 mTouchMode = TOUCH_DONE_MODE; 6304 switchOutDrawHistory(); 6305 // mLastTouchX and mLastTouchY are the point in the current viewport 6306 int contentX = viewToContentX((int) mLastTouchX + mScrollX); 6307 int contentY = viewToContentY((int) mLastTouchY + mScrollY); 6308 if (nativePointInNavCache(contentX, contentY, mNavSlop)) { 6309 WebViewCore.MotionUpData motionUpData = new WebViewCore 6310 .MotionUpData(); 6311 motionUpData.mFrame = nativeCacheHitFramePointer(); 6312 motionUpData.mNode = nativeCacheHitNodePointer(); 6313 motionUpData.mBounds = nativeCacheHitNodeBounds(); 6314 motionUpData.mX = contentX; 6315 motionUpData.mY = contentY; 6316 mWebViewCore.sendMessageAtFrontOfQueue(EventHub.VALID_NODE_BOUNDS, 6317 motionUpData); 6318 } else { 6319 doMotionUp(contentX, contentY); 6320 } 6321 } 6322 6323 private void doMotionUp(int contentX, int contentY) { 6324 if (mLogEvent && nativeMotionUp(contentX, contentY, mNavSlop)) { 6325 EventLog.writeEvent(EventLogTags.BROWSER_SNAP_CENTER); 6326 } 6327 if (nativeHasCursorNode() && !nativeCursorIsTextInput()) { 6328 playSoundEffect(SoundEffectConstants.CLICK); 6329 } 6330 } 6331 6332 /* 6333 * Return true if the view (Plugin) is fully visible and maximized inside 6334 * the WebView. 6335 */ 6336 private boolean isPluginFitOnScreen(ViewManager.ChildView view) { 6337 int viewWidth = getViewWidth(); 6338 int viewHeight = getViewHeightWithTitle(); 6339 float scale = Math.min((float) viewWidth / view.width, 6340 (float) viewHeight / view.height); 6341 if (scale < mMinZoomScale) { 6342 scale = mMinZoomScale; 6343 } else if (scale > mMaxZoomScale) { 6344 scale = mMaxZoomScale; 6345 } 6346 if (Math.abs(scale - mActualScale) < MINIMUM_SCALE_INCREMENT) { 6347 if (contentToViewX(view.x) >= mScrollX 6348 && contentToViewX(view.x + view.width) <= mScrollX 6349 + viewWidth 6350 && contentToViewY(view.y) >= mScrollY 6351 && contentToViewY(view.y + view.height) <= mScrollY 6352 + viewHeight) { 6353 return true; 6354 } 6355 } 6356 return false; 6357 } 6358 6359 /* 6360 * Maximize and center the rectangle, specified in the document coordinate 6361 * space, inside the WebView. If the zoom doesn't need to be changed, do an 6362 * animated scroll to center it. If the zoom needs to be changed, find the 6363 * zoom center and do a smooth zoom transition. 6364 */ 6365 private void centerFitRect(int docX, int docY, int docWidth, int docHeight) { 6366 int viewWidth = getViewWidth(); 6367 int viewHeight = getViewHeightWithTitle(); 6368 float scale = Math.min((float) viewWidth / docWidth, (float) viewHeight 6369 / docHeight); 6370 if (scale < mMinZoomScale) { 6371 scale = mMinZoomScale; 6372 } else if (scale > mMaxZoomScale) { 6373 scale = mMaxZoomScale; 6374 } 6375 if (Math.abs(scale - mActualScale) < MINIMUM_SCALE_INCREMENT) { 6376 pinScrollTo(contentToViewX(docX + docWidth / 2) - viewWidth / 2, 6377 contentToViewY(docY + docHeight / 2) - viewHeight / 2, 6378 true, 0); 6379 } else { 6380 float oldScreenX = docX * mActualScale - mScrollX; 6381 float rectViewX = docX * scale; 6382 float rectViewWidth = docWidth * scale; 6383 float newMaxWidth = mContentWidth * scale; 6384 float newScreenX = (viewWidth - rectViewWidth) / 2; 6385 // pin the newX to the WebView 6386 if (newScreenX > rectViewX) { 6387 newScreenX = rectViewX; 6388 } else if (newScreenX > (newMaxWidth - rectViewX - rectViewWidth)) { 6389 newScreenX = viewWidth - (newMaxWidth - rectViewX); 6390 } 6391 mZoomCenterX = (oldScreenX * scale - newScreenX * mActualScale) 6392 / (scale - mActualScale); 6393 float oldScreenY = docY * mActualScale + getTitleHeight() 6394 - mScrollY; 6395 float rectViewY = docY * scale + getTitleHeight(); 6396 float rectViewHeight = docHeight * scale; 6397 float newMaxHeight = mContentHeight * scale + getTitleHeight(); 6398 float newScreenY = (viewHeight - rectViewHeight) / 2; 6399 // pin the newY to the WebView 6400 if (newScreenY > rectViewY) { 6401 newScreenY = rectViewY; 6402 } else if (newScreenY > (newMaxHeight - rectViewY - rectViewHeight)) { 6403 newScreenY = viewHeight - (newMaxHeight - rectViewY); 6404 } 6405 mZoomCenterY = (oldScreenY * scale - newScreenY * mActualScale) 6406 / (scale - mActualScale); 6407 zoomWithPreview(scale, false); 6408 } 6409 } 6410 6411 void dismissZoomControl() { 6412 if (mWebViewCore == null) { 6413 // maybe called after WebView's destroy(). As we can't get settings, 6414 // just hide zoom control for both styles. 6415 if (mZoomButtonsController != null) { 6416 mZoomButtonsController.setVisible(false); 6417 } 6418 if (mZoomControls != null) { 6419 mZoomControls.hide(); 6420 } 6421 return; 6422 } 6423 WebSettings settings = getSettings(); 6424 if (settings.getBuiltInZoomControls()) { 6425 if (mZoomButtonsController != null) { 6426 mZoomButtonsController.setVisible(false); 6427 } 6428 } else { 6429 if (mZoomControlRunnable != null) { 6430 mPrivateHandler.removeCallbacks(mZoomControlRunnable); 6431 } 6432 if (mZoomControls != null) { 6433 mZoomControls.hide(); 6434 } 6435 } 6436 } 6437 6438 // Rule for double tap: 6439 // 1. if the current scale is not same as the text wrap scale and layout 6440 // algorithm is NARROW_COLUMNS, fit to column; 6441 // 2. if the current state is not overview mode, change to overview mode; 6442 // 3. if the current state is overview mode, change to default scale. 6443 private void doDoubleTap() { 6444 if (mWebViewCore.getSettings().getUseWideViewPort() == false) { 6445 return; 6446 } 6447 mZoomCenterX = mLastTouchX; 6448 mZoomCenterY = mLastTouchY; 6449 mAnchorX = viewToContentX((int) mZoomCenterX + mScrollX); 6450 mAnchorY = viewToContentY((int) mZoomCenterY + mScrollY); 6451 WebSettings settings = getSettings(); 6452 settings.setDoubleTapToastCount(0); 6453 // remove the zoom control after double tap 6454 dismissZoomControl(); 6455 ViewManager.ChildView plugin = mViewManager.hitTest(mAnchorX, mAnchorY); 6456 if (plugin != null) { 6457 if (isPluginFitOnScreen(plugin)) { 6458 mInZoomOverview = true; 6459 // Force the titlebar fully reveal in overview mode 6460 if (mScrollY < getTitleHeight()) mScrollY = 0; 6461 zoomWithPreview((float) getViewWidth() / mZoomOverviewWidth, 6462 true); 6463 } else { 6464 mInZoomOverview = false; 6465 centerFitRect(plugin.x, plugin.y, plugin.width, plugin.height); 6466 } 6467 return; 6468 } 6469 boolean zoomToDefault = false; 6470 if ((settings.getLayoutAlgorithm() == WebSettings.LayoutAlgorithm.NARROW_COLUMNS) 6471 && (Math.abs(mActualScale - mTextWrapScale) >= MINIMUM_SCALE_INCREMENT)) { 6472 setNewZoomScale(mActualScale, true, true); 6473 float overviewScale = (float) getViewWidth() / mZoomOverviewWidth; 6474 if (Math.abs(mActualScale - overviewScale) < MINIMUM_SCALE_INCREMENT) { 6475 mInZoomOverview = true; 6476 } 6477 } else if (!mInZoomOverview) { 6478 float newScale = (float) getViewWidth() / mZoomOverviewWidth; 6479 if (Math.abs(mActualScale - newScale) >= MINIMUM_SCALE_INCREMENT) { 6480 mInZoomOverview = true; 6481 // Force the titlebar fully reveal in overview mode 6482 if (mScrollY < getTitleHeight()) mScrollY = 0; 6483 zoomWithPreview(newScale, true); 6484 } else if (Math.abs(mActualScale - mDefaultScale) >= MINIMUM_SCALE_INCREMENT) { 6485 zoomToDefault = true; 6486 } 6487 } else { 6488 zoomToDefault = true; 6489 } 6490 if (zoomToDefault) { 6491 mInZoomOverview = false; 6492 int left = nativeGetBlockLeftEdge(mAnchorX, mAnchorY, mActualScale); 6493 if (left != NO_LEFTEDGE) { 6494 // add a 5pt padding to the left edge. 6495 int viewLeft = contentToViewX(left < 5 ? 0 : (left - 5)) 6496 - mScrollX; 6497 // Re-calculate the zoom center so that the new scroll x will be 6498 // on the left edge. 6499 if (viewLeft > 0) { 6500 mZoomCenterX = viewLeft * mDefaultScale 6501 / (mDefaultScale - mActualScale); 6502 } else { 6503 scrollBy(viewLeft, 0); 6504 mZoomCenterX = 0; 6505 } 6506 } 6507 zoomWithPreview(mDefaultScale, true); 6508 } 6509 } 6510 6511 // Called by JNI to handle a touch on a node representing an email address, 6512 // address, or phone number 6513 private void overrideLoading(String url) { 6514 mCallbackProxy.uiOverrideUrlLoading(url); 6515 } 6516 6517 @Override 6518 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 6519 boolean result = false; 6520 if (inEditingMode()) { 6521 result = mWebTextView.requestFocus(direction, 6522 previouslyFocusedRect); 6523 } else { 6524 result = super.requestFocus(direction, previouslyFocusedRect); 6525 if (mWebViewCore.getSettings().getNeedInitialFocus()) { 6526 // For cases such as GMail, where we gain focus from a direction, 6527 // we want to move to the first available link. 6528 // FIXME: If there are no visible links, we may not want to 6529 int fakeKeyDirection = 0; 6530 switch(direction) { 6531 case View.FOCUS_UP: 6532 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_UP; 6533 break; 6534 case View.FOCUS_DOWN: 6535 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_DOWN; 6536 break; 6537 case View.FOCUS_LEFT: 6538 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_LEFT; 6539 break; 6540 case View.FOCUS_RIGHT: 6541 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_RIGHT; 6542 break; 6543 default: 6544 return result; 6545 } 6546 if (mNativeClass != 0 && !nativeHasCursorNode()) { 6547 navHandledKey(fakeKeyDirection, 1, true, 0); 6548 } 6549 } 6550 } 6551 return result; 6552 } 6553 6554 @Override 6555 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 6556 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 6557 6558 int heightMode = MeasureSpec.getMode(heightMeasureSpec); 6559 int heightSize = MeasureSpec.getSize(heightMeasureSpec); 6560 int widthMode = MeasureSpec.getMode(widthMeasureSpec); 6561 int widthSize = MeasureSpec.getSize(widthMeasureSpec); 6562 6563 int measuredHeight = heightSize; 6564 int measuredWidth = widthSize; 6565 6566 // Grab the content size from WebViewCore. 6567 int contentHeight = contentToViewDimension(mContentHeight); 6568 int contentWidth = contentToViewDimension(mContentWidth); 6569 6570// Log.d(LOGTAG, "------- measure " + heightMode); 6571 6572 if (heightMode != MeasureSpec.EXACTLY) { 6573 mHeightCanMeasure = true; 6574 measuredHeight = contentHeight; 6575 if (heightMode == MeasureSpec.AT_MOST) { 6576 // If we are larger than the AT_MOST height, then our height can 6577 // no longer be measured and we should scroll internally. 6578 if (measuredHeight > heightSize) { 6579 measuredHeight = heightSize; 6580 mHeightCanMeasure = false; 6581 } 6582 } 6583 } else { 6584 mHeightCanMeasure = false; 6585 } 6586 if (mNativeClass != 0) { 6587 nativeSetHeightCanMeasure(mHeightCanMeasure); 6588 } 6589 // For the width, always use the given size unless unspecified. 6590 if (widthMode == MeasureSpec.UNSPECIFIED) { 6591 mWidthCanMeasure = true; 6592 measuredWidth = contentWidth; 6593 } else { 6594 mWidthCanMeasure = false; 6595 } 6596 6597 synchronized (this) { 6598 setMeasuredDimension(measuredWidth, measuredHeight); 6599 } 6600 } 6601 6602 @Override 6603 public boolean requestChildRectangleOnScreen(View child, 6604 Rect rect, 6605 boolean immediate) { 6606 rect.offset(child.getLeft() - child.getScrollX(), 6607 child.getTop() - child.getScrollY()); 6608 6609 Rect content = new Rect(viewToContentX(mScrollX), 6610 viewToContentY(mScrollY), 6611 viewToContentX(mScrollX + getWidth() 6612 - getVerticalScrollbarWidth()), 6613 viewToContentY(mScrollY + getViewHeightWithTitle())); 6614 content = nativeSubtractLayers(content); 6615 int screenTop = contentToViewY(content.top); 6616 int screenBottom = contentToViewY(content.bottom); 6617 int height = screenBottom - screenTop; 6618 int scrollYDelta = 0; 6619 6620 if (rect.bottom > screenBottom) { 6621 int oneThirdOfScreenHeight = height / 3; 6622 if (rect.height() > 2 * oneThirdOfScreenHeight) { 6623 // If the rectangle is too tall to fit in the bottom two thirds 6624 // of the screen, place it at the top. 6625 scrollYDelta = rect.top - screenTop; 6626 } else { 6627 // If the rectangle will still fit on screen, we want its 6628 // top to be in the top third of the screen. 6629 scrollYDelta = rect.top - (screenTop + oneThirdOfScreenHeight); 6630 } 6631 } else if (rect.top < screenTop) { 6632 scrollYDelta = rect.top - screenTop; 6633 } 6634 6635 int screenLeft = contentToViewX(content.left); 6636 int screenRight = contentToViewX(content.right); 6637 int width = screenRight - screenLeft; 6638 int scrollXDelta = 0; 6639 6640 if (rect.right > screenRight && rect.left > screenLeft) { 6641 if (rect.width() > width) { 6642 scrollXDelta += (rect.left - screenLeft); 6643 } else { 6644 scrollXDelta += (rect.right - screenRight); 6645 } 6646 } else if (rect.left < screenLeft) { 6647 scrollXDelta -= (screenLeft - rect.left); 6648 } 6649 6650 if ((scrollYDelta | scrollXDelta) != 0) { 6651 return pinScrollBy(scrollXDelta, scrollYDelta, !immediate, 0); 6652 } 6653 6654 return false; 6655 } 6656 6657 /* package */ void replaceTextfieldText(int oldStart, int oldEnd, 6658 String replace, int newStart, int newEnd) { 6659 WebViewCore.ReplaceTextData arg = new WebViewCore.ReplaceTextData(); 6660 arg.mReplace = replace; 6661 arg.mNewStart = newStart; 6662 arg.mNewEnd = newEnd; 6663 mTextGeneration++; 6664 arg.mTextGeneration = mTextGeneration; 6665 mWebViewCore.sendMessage(EventHub.REPLACE_TEXT, oldStart, oldEnd, arg); 6666 } 6667 6668 /* package */ void passToJavaScript(String currentText, KeyEvent event) { 6669 WebViewCore.JSKeyData arg = new WebViewCore.JSKeyData(); 6670 arg.mEvent = event; 6671 arg.mCurrentText = currentText; 6672 // Increase our text generation number, and pass it to webcore thread 6673 mTextGeneration++; 6674 mWebViewCore.sendMessage(EventHub.PASS_TO_JS, mTextGeneration, 0, arg); 6675 // WebKit's document state is not saved until about to leave the page. 6676 // To make sure the host application, like Browser, has the up to date 6677 // document state when it goes to background, we force to save the 6678 // document state. 6679 mWebViewCore.removeMessages(EventHub.SAVE_DOCUMENT_STATE); 6680 mWebViewCore.sendMessageDelayed(EventHub.SAVE_DOCUMENT_STATE, 6681 cursorData(), 1000); 6682 } 6683 6684 /* package */ synchronized WebViewCore getWebViewCore() { 6685 return mWebViewCore; 6686 } 6687 6688 //------------------------------------------------------------------------- 6689 // Methods can be called from a separate thread, like WebViewCore 6690 // If it needs to call the View system, it has to send message. 6691 //------------------------------------------------------------------------- 6692 6693 /** 6694 * General handler to receive message coming from webkit thread 6695 */ 6696 class PrivateHandler extends Handler { 6697 @Override 6698 public void handleMessage(Message msg) { 6699 // exclude INVAL_RECT_MSG_ID since it is frequently output 6700 if (DebugFlags.WEB_VIEW && msg.what != INVAL_RECT_MSG_ID) { 6701 if (msg.what >= FIRST_PRIVATE_MSG_ID 6702 && msg.what <= LAST_PRIVATE_MSG_ID) { 6703 Log.v(LOGTAG, HandlerPrivateDebugString[msg.what 6704 - FIRST_PRIVATE_MSG_ID]); 6705 } else if (msg.what >= FIRST_PACKAGE_MSG_ID 6706 && msg.what <= LAST_PACKAGE_MSG_ID) { 6707 Log.v(LOGTAG, HandlerPackageDebugString[msg.what 6708 - FIRST_PACKAGE_MSG_ID]); 6709 } else { 6710 Log.v(LOGTAG, Integer.toString(msg.what)); 6711 } 6712 } 6713 if (mWebViewCore == null) { 6714 // after WebView's destroy() is called, skip handling messages. 6715 return; 6716 } 6717 switch (msg.what) { 6718 case REMEMBER_PASSWORD: { 6719 mDatabase.setUsernamePassword( 6720 msg.getData().getString("host"), 6721 msg.getData().getString("username"), 6722 msg.getData().getString("password")); 6723 ((Message) msg.obj).sendToTarget(); 6724 break; 6725 } 6726 case NEVER_REMEMBER_PASSWORD: { 6727 mDatabase.setUsernamePassword( 6728 msg.getData().getString("host"), null, null); 6729 ((Message) msg.obj).sendToTarget(); 6730 break; 6731 } 6732 case PREVENT_DEFAULT_TIMEOUT: { 6733 // if timeout happens, cancel it so that it won't block UI 6734 // to continue handling touch events 6735 if ((msg.arg1 == MotionEvent.ACTION_DOWN 6736 && mPreventDefault == PREVENT_DEFAULT_MAYBE_YES) 6737 || (msg.arg1 == MotionEvent.ACTION_MOVE 6738 && mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN)) { 6739 cancelWebCoreTouchEvent( 6740 viewToContentX((int) mLastTouchX + mScrollX), 6741 viewToContentY((int) mLastTouchY + mScrollY), 6742 true); 6743 } 6744 break; 6745 } 6746 case SWITCH_TO_SHORTPRESS: { 6747 if (mTouchMode == TOUCH_INIT_MODE) { 6748 if (mPreventDefault != PREVENT_DEFAULT_YES) { 6749 mTouchMode = TOUCH_SHORTPRESS_START_MODE; 6750 updateSelection(); 6751 } else { 6752 // set to TOUCH_SHORTPRESS_MODE so that it won't 6753 // trigger double tap any more 6754 mTouchMode = TOUCH_SHORTPRESS_MODE; 6755 } 6756 } else if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) { 6757 mTouchMode = TOUCH_DONE_MODE; 6758 } 6759 break; 6760 } 6761 case SWITCH_TO_LONGPRESS: { 6762 if (inFullScreenMode() || mDeferTouchProcess) { 6763 TouchEventData ted = new TouchEventData(); 6764 ted.mAction = WebViewCore.ACTION_LONGPRESS; 6765 ted.mX = viewToContentX((int) mLastTouchX + mScrollX); 6766 ted.mY = viewToContentY((int) mLastTouchY + mScrollY); 6767 // metaState for long press is tricky. Should it be the 6768 // state when the press started or when the press was 6769 // released? Or some intermediary key state? For 6770 // simplicity for now, we don't set it. 6771 ted.mMetaState = 0; 6772 ted.mReprocess = mDeferTouchProcess; 6773 if (mDeferTouchProcess) { 6774 ted.mViewX = mLastTouchX; 6775 ted.mViewY = mLastTouchY; 6776 } 6777 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 6778 } else if (mPreventDefault != PREVENT_DEFAULT_YES) { 6779 mTouchMode = TOUCH_DONE_MODE; 6780 performLongClick(); 6781 rebuildWebTextView(); 6782 } 6783 break; 6784 } 6785 case RELEASE_SINGLE_TAP: { 6786 doShortPress(); 6787 break; 6788 } 6789 case SCROLL_BY_MSG_ID: 6790 setContentScrollBy(msg.arg1, msg.arg2, (Boolean) msg.obj); 6791 break; 6792 case SYNC_SCROLL_TO_MSG_ID: 6793 if (mUserScroll) { 6794 // if user has scrolled explicitly, don't sync the 6795 // scroll position any more 6796 mUserScroll = false; 6797 break; 6798 } 6799 // fall through 6800 case SCROLL_TO_MSG_ID: 6801 if (setContentScrollTo(msg.arg1, msg.arg2)) { 6802 // if we can't scroll to the exact position due to pin, 6803 // send a message to WebCore to re-scroll when we get a 6804 // new picture 6805 mUserScroll = false; 6806 mWebViewCore.sendMessage(EventHub.SYNC_SCROLL, 6807 msg.arg1, msg.arg2); 6808 } 6809 break; 6810 case SPAWN_SCROLL_TO_MSG_ID: 6811 spawnContentScrollTo(msg.arg1, msg.arg2); 6812 break; 6813 case UPDATE_ZOOM_RANGE: { 6814 WebViewCore.RestoreState restoreState 6815 = (WebViewCore.RestoreState) msg.obj; 6816 // mScrollX contains the new minPrefWidth 6817 updateZoomRange(restoreState, getViewWidth(), 6818 restoreState.mScrollX, false); 6819 break; 6820 } 6821 case NEW_PICTURE_MSG_ID: { 6822 // If we've previously delayed deleting a root 6823 // layer, do it now. 6824 if (mDelayedDeleteRootLayer) { 6825 mDelayedDeleteRootLayer = false; 6826 nativeSetRootLayer(0); 6827 } 6828 WebSettings settings = mWebViewCore.getSettings(); 6829 // called for new content 6830 final int viewWidth = getViewWidth(); 6831 final WebViewCore.DrawData draw = 6832 (WebViewCore.DrawData) msg.obj; 6833 final Point viewSize = draw.mViewPoint; 6834 boolean useWideViewport = settings.getUseWideViewPort(); 6835 WebViewCore.RestoreState restoreState = draw.mRestoreState; 6836 boolean hasRestoreState = restoreState != null; 6837 if (hasRestoreState) { 6838 updateZoomRange(restoreState, viewSize.x, 6839 draw.mMinPrefWidth, true); 6840 if (!mDrawHistory) { 6841 mInZoomOverview = false; 6842 6843 if (mInitialScaleInPercent > 0) { 6844 setNewZoomScale(mInitialScaleInPercent / 100.0f, 6845 mInitialScaleInPercent != mTextWrapScale * 100, 6846 false); 6847 } else if (restoreState.mViewScale > 0) { 6848 mTextWrapScale = restoreState.mTextWrapScale; 6849 setNewZoomScale(restoreState.mViewScale, false, 6850 false); 6851 } else { 6852 mInZoomOverview = useWideViewport 6853 && settings.getLoadWithOverviewMode(); 6854 float scale; 6855 if (mInZoomOverview) { 6856 scale = (float) viewWidth 6857 / DEFAULT_VIEWPORT_WIDTH; 6858 } else { 6859 scale = restoreState.mTextWrapScale; 6860 } 6861 setNewZoomScale(scale, Math.abs(scale 6862 - mTextWrapScale) >= MINIMUM_SCALE_INCREMENT, 6863 false); 6864 } 6865 setContentScrollTo(restoreState.mScrollX, 6866 restoreState.mScrollY); 6867 // As we are on a new page, remove the WebTextView. This 6868 // is necessary for page loads driven by webkit, and in 6869 // particular when the user was on a password field, so 6870 // the WebTextView was visible. 6871 clearTextEntry(false); 6872 // update the zoom buttons as the scale can be changed 6873 if (getSettings().getBuiltInZoomControls()) { 6874 updateZoomButtonsEnabled(); 6875 } 6876 } 6877 } 6878 // We update the layout (i.e. request a layout from the 6879 // view system) if the last view size that we sent to 6880 // WebCore matches the view size of the picture we just 6881 // received in the fixed dimension. 6882 final boolean updateLayout = viewSize.x == mLastWidthSent 6883 && viewSize.y == mLastHeightSent; 6884 recordNewContentSize(draw.mWidthHeight.x, 6885 draw.mWidthHeight.y 6886 + (mFindIsUp ? mFindHeight : 0), updateLayout); 6887 if (DebugFlags.WEB_VIEW) { 6888 Rect b = draw.mInvalRegion.getBounds(); 6889 Log.v(LOGTAG, "NEW_PICTURE_MSG_ID {" + 6890 b.left+","+b.top+","+b.right+","+b.bottom+"}"); 6891 } 6892 invalidateContentRect(draw.mInvalRegion.getBounds()); 6893 if (mPictureListener != null) { 6894 mPictureListener.onNewPicture(WebView.this, capturePicture()); 6895 } 6896 if (useWideViewport) { 6897 // limit mZoomOverviewWidth upper bound to 6898 // sMaxViewportWidth so that if the page doesn't behave 6899 // well, the WebView won't go insane. limit the lower 6900 // bound to match the default scale for mobile sites. 6901 mZoomOverviewWidth = Math.min(sMaxViewportWidth, Math 6902 .max((int) (viewWidth / mDefaultScale), Math 6903 .max(draw.mMinPrefWidth, 6904 draw.mViewPoint.x))); 6905 } 6906 if (!mMinZoomScaleFixed) { 6907 mMinZoomScale = (float) viewWidth / mZoomOverviewWidth; 6908 } 6909 if (!mDrawHistory && mInZoomOverview) { 6910 // fit the content width to the current view. Ignore 6911 // the rounding error case. 6912 if (Math.abs((viewWidth * mInvActualScale) 6913 - mZoomOverviewWidth) > 1) { 6914 setNewZoomScale((float) viewWidth 6915 / mZoomOverviewWidth, Math.abs(mActualScale 6916 - mTextWrapScale) < MINIMUM_SCALE_INCREMENT, 6917 false); 6918 } 6919 } 6920 if (draw.mFocusSizeChanged && inEditingMode()) { 6921 mFocusSizeChanged = true; 6922 } 6923 if (hasRestoreState) { 6924 mViewManager.postReadyToDrawAll(); 6925 } 6926 break; 6927 } 6928 case WEBCORE_INITIALIZED_MSG_ID: 6929 // nativeCreate sets mNativeClass to a non-zero value 6930 nativeCreate(msg.arg1); 6931 break; 6932 case UPDATE_TEXTFIELD_TEXT_MSG_ID: 6933 // Make sure that the textfield is currently focused 6934 // and representing the same node as the pointer. 6935 if (inEditingMode() && 6936 mWebTextView.isSameTextField(msg.arg1)) { 6937 if (msg.getData().getBoolean("password")) { 6938 Spannable text = (Spannable) mWebTextView.getText(); 6939 int start = Selection.getSelectionStart(text); 6940 int end = Selection.getSelectionEnd(text); 6941 mWebTextView.setInPassword(true); 6942 // Restore the selection, which may have been 6943 // ruined by setInPassword. 6944 Spannable pword = 6945 (Spannable) mWebTextView.getText(); 6946 Selection.setSelection(pword, start, end); 6947 // If the text entry has created more events, ignore 6948 // this one. 6949 } else if (msg.arg2 == mTextGeneration) { 6950 mWebTextView.setTextAndKeepSelection( 6951 (String) msg.obj); 6952 } 6953 } 6954 break; 6955 case REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID: 6956 displaySoftKeyboard(true); 6957 updateTextSelectionFromMessage(msg.arg1, msg.arg2, 6958 (WebViewCore.TextSelectionData) msg.obj); 6959 break; 6960 case UPDATE_TEXT_SELECTION_MSG_ID: 6961 // If no textfield was in focus, and the user touched one, 6962 // causing it to send this message, then WebTextView has not 6963 // been set up yet. Rebuild it so it can set its selection. 6964 rebuildWebTextView(); 6965 updateTextSelectionFromMessage(msg.arg1, msg.arg2, 6966 (WebViewCore.TextSelectionData) msg.obj); 6967 break; 6968 case RETURN_LABEL: 6969 if (inEditingMode() 6970 && mWebTextView.isSameTextField(msg.arg1)) { 6971 mWebTextView.setHint((String) msg.obj); 6972 InputMethodManager imm 6973 = InputMethodManager.peekInstance(); 6974 // The hint is propagated to the IME in 6975 // onCreateInputConnection. If the IME is already 6976 // active, restart it so that its hint text is updated. 6977 if (imm != null && imm.isActive(mWebTextView)) { 6978 imm.restartInput(mWebTextView); 6979 } 6980 } 6981 break; 6982 case MOVE_OUT_OF_PLUGIN: 6983 navHandledKey(msg.arg1, 1, false, 0); 6984 break; 6985 case UPDATE_TEXT_ENTRY_MSG_ID: 6986 // this is sent after finishing resize in WebViewCore. Make 6987 // sure the text edit box is still on the screen. 6988 selectionDone(); 6989 if (inEditingMode() && nativeCursorIsTextInput()) { 6990 mWebTextView.bringIntoView(); 6991 rebuildWebTextView(); 6992 } 6993 break; 6994 case CLEAR_TEXT_ENTRY: 6995 clearTextEntry(false); 6996 break; 6997 case INVAL_RECT_MSG_ID: { 6998 Rect r = (Rect)msg.obj; 6999 if (r == null) { 7000 invalidate(); 7001 } else { 7002 // we need to scale r from content into view coords, 7003 // which viewInvalidate() does for us 7004 viewInvalidate(r.left, r.top, r.right, r.bottom); 7005 } 7006 break; 7007 } 7008 case IMMEDIATE_REPAINT_MSG_ID: { 7009 invalidate(); 7010 break; 7011 } 7012 case SET_ROOT_LAYER_MSG_ID: { 7013 if (0 == msg.arg1) { 7014 // Null indicates deleting the old layer, but 7015 // don't actually do so until we've got the 7016 // new page to display. 7017 mDelayedDeleteRootLayer = true; 7018 } else { 7019 mDelayedDeleteRootLayer = false; 7020 nativeSetRootLayer(msg.arg1); 7021 invalidate(); 7022 } 7023 break; 7024 } 7025 case REQUEST_FORM_DATA: 7026 AutoCompleteAdapter adapter = (AutoCompleteAdapter) msg.obj; 7027 if (mWebTextView.isSameTextField(msg.arg1)) { 7028 mWebTextView.setAdapterCustom(adapter); 7029 } 7030 break; 7031 case RESUME_WEBCORE_PRIORITY: 7032 WebViewCore.resumePriority(); 7033 WebViewCore.resumeUpdatePicture(mWebViewCore); 7034 break; 7035 7036 case LONG_PRESS_CENTER: 7037 // as this is shared by keydown and trackballdown, reset all 7038 // the states 7039 mGotCenterDown = false; 7040 mTrackballDown = false; 7041 performLongClick(); 7042 break; 7043 7044 case WEBCORE_NEED_TOUCH_EVENTS: 7045 mForwardTouchEvents = (msg.arg1 != 0); 7046 break; 7047 7048 case PREVENT_TOUCH_ID: 7049 if (inFullScreenMode()) { 7050 break; 7051 } 7052 if (msg.obj == null) { 7053 if (msg.arg1 == MotionEvent.ACTION_DOWN 7054 && mPreventDefault == PREVENT_DEFAULT_MAYBE_YES) { 7055 // if prevent default is called from WebCore, UI 7056 // will not handle the rest of the touch events any 7057 // more. 7058 mPreventDefault = msg.arg2 == 1 ? PREVENT_DEFAULT_YES 7059 : PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN; 7060 } else if (msg.arg1 == MotionEvent.ACTION_MOVE 7061 && mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN) { 7062 // the return for the first ACTION_MOVE will decide 7063 // whether UI will handle touch or not. Currently no 7064 // support for alternating prevent default 7065 mPreventDefault = msg.arg2 == 1 ? PREVENT_DEFAULT_YES 7066 : PREVENT_DEFAULT_NO; 7067 } 7068 } else if (msg.arg2 == 0) { 7069 // prevent default is not called in WebCore, so the 7070 // message needs to be reprocessed in UI 7071 TouchEventData ted = (TouchEventData) msg.obj; 7072 switch (ted.mAction) { 7073 case MotionEvent.ACTION_DOWN: 7074 mLastDeferTouchX = ted.mViewX; 7075 mLastDeferTouchY = ted.mViewY; 7076 mDeferTouchMode = TOUCH_INIT_MODE; 7077 break; 7078 case MotionEvent.ACTION_MOVE: { 7079 // no snapping in defer process 7080 if (mDeferTouchMode != TOUCH_DRAG_MODE) { 7081 mDeferTouchMode = TOUCH_DRAG_MODE; 7082 mLastDeferTouchX = ted.mViewX; 7083 mLastDeferTouchY = ted.mViewY; 7084 startDrag(); 7085 } 7086 int deltaX = pinLocX((int) (mScrollX 7087 + mLastDeferTouchX - ted.mViewX)) 7088 - mScrollX; 7089 int deltaY = pinLocY((int) (mScrollY 7090 + mLastDeferTouchY - ted.mViewY)) 7091 - mScrollY; 7092 doDrag(deltaX, deltaY); 7093 if (deltaX != 0) mLastDeferTouchX = ted.mViewX; 7094 if (deltaY != 0) mLastDeferTouchY = ted.mViewY; 7095 break; 7096 } 7097 case MotionEvent.ACTION_UP: 7098 case MotionEvent.ACTION_CANCEL: 7099 if (mDeferTouchMode == TOUCH_DRAG_MODE) { 7100 // no fling in defer process 7101 mScroller.springBack(mScrollX, mScrollY, 0, 7102 computeMaxScrollX(), 0, 7103 computeMaxScrollY()); 7104 invalidate(); 7105 WebViewCore.resumePriority(); 7106 WebViewCore.resumeUpdatePicture(mWebViewCore); 7107 } 7108 mDeferTouchMode = TOUCH_DONE_MODE; 7109 break; 7110 case WebViewCore.ACTION_DOUBLETAP: 7111 // doDoubleTap() needs mLastTouchX/Y as anchor 7112 mLastTouchX = ted.mViewX; 7113 mLastTouchY = ted.mViewY; 7114 doDoubleTap(); 7115 mDeferTouchMode = TOUCH_DONE_MODE; 7116 break; 7117 case WebViewCore.ACTION_LONGPRESS: 7118 HitTestResult hitTest = getHitTestResult(); 7119 if (hitTest != null && hitTest.mType 7120 != HitTestResult.UNKNOWN_TYPE) { 7121 performLongClick(); 7122 rebuildWebTextView(); 7123 } 7124 mDeferTouchMode = TOUCH_DONE_MODE; 7125 break; 7126 } 7127 } 7128 break; 7129 7130 case REQUEST_KEYBOARD: 7131 if (msg.arg1 == 0) { 7132 hideSoftKeyboard(); 7133 } else { 7134 displaySoftKeyboard(false); 7135 } 7136 break; 7137 7138 case FIND_AGAIN: 7139 // Ignore if find has been dismissed. 7140 if (mFindIsUp) { 7141 findAll(mLastFind); 7142 } 7143 break; 7144 7145 case DRAG_HELD_MOTIONLESS: 7146 mHeldMotionless = MOTIONLESS_TRUE; 7147 invalidate(); 7148 // fall through to keep scrollbars awake 7149 7150 case AWAKEN_SCROLL_BARS: 7151 if (mTouchMode == TOUCH_DRAG_MODE 7152 && mHeldMotionless == MOTIONLESS_TRUE) { 7153 awakenScrollBars(ViewConfiguration 7154 .getScrollDefaultDelay(), false); 7155 mPrivateHandler.sendMessageDelayed(mPrivateHandler 7156 .obtainMessage(AWAKEN_SCROLL_BARS), 7157 ViewConfiguration.getScrollDefaultDelay()); 7158 } 7159 break; 7160 7161 case DO_MOTION_UP: 7162 doMotionUp(msg.arg1, msg.arg2); 7163 break; 7164 7165 case SHOW_FULLSCREEN: { 7166 View view = (View) msg.obj; 7167 int npp = msg.arg1; 7168 7169 if (mFullScreenHolder != null) { 7170 Log.w(LOGTAG, "Should not have another full screen."); 7171 mFullScreenHolder.dismiss(); 7172 } 7173 mFullScreenHolder = new PluginFullScreenHolder(WebView.this, npp); 7174 mFullScreenHolder.setContentView(view); 7175 mFullScreenHolder.setCancelable(false); 7176 mFullScreenHolder.setCanceledOnTouchOutside(false); 7177 mFullScreenHolder.show(); 7178 7179 break; 7180 } 7181 case HIDE_FULLSCREEN: 7182 if (inFullScreenMode()) { 7183 mFullScreenHolder.dismiss(); 7184 mFullScreenHolder = null; 7185 } 7186 break; 7187 7188 case DOM_FOCUS_CHANGED: 7189 if (inEditingMode()) { 7190 nativeClearCursor(); 7191 rebuildWebTextView(); 7192 } 7193 break; 7194 7195 case SHOW_RECT_MSG_ID: { 7196 WebViewCore.ShowRectData data = (WebViewCore.ShowRectData) msg.obj; 7197 int x = mScrollX; 7198 int left = contentToViewX(data.mLeft); 7199 int width = contentToViewDimension(data.mWidth); 7200 int maxWidth = contentToViewDimension(data.mContentWidth); 7201 int viewWidth = getViewWidth(); 7202 if (width < viewWidth) { 7203 // center align 7204 x += left + width / 2 - mScrollX - viewWidth / 2; 7205 } else { 7206 x += (int) (left + data.mXPercentInDoc * width 7207 - mScrollX - data.mXPercentInView * viewWidth); 7208 } 7209 if (DebugFlags.WEB_VIEW) { 7210 Log.v(LOGTAG, "showRectMsg=(left=" + left + ",width=" + 7211 width + ",maxWidth=" + maxWidth + 7212 ",viewWidth=" + viewWidth + ",x=" 7213 + x + ",xPercentInDoc=" + data.mXPercentInDoc + 7214 ",xPercentInView=" + data.mXPercentInView+ ")"); 7215 } 7216 // use the passing content width to cap x as the current 7217 // mContentWidth may not be updated yet 7218 x = Math.max(0, 7219 (Math.min(maxWidth, x + viewWidth)) - viewWidth); 7220 int top = contentToViewY(data.mTop); 7221 int height = contentToViewDimension(data.mHeight); 7222 int maxHeight = contentToViewDimension(data.mContentHeight); 7223 int viewHeight = getViewHeight(); 7224 int y = (int) (top + data.mYPercentInDoc * height - 7225 data.mYPercentInView * viewHeight); 7226 if (DebugFlags.WEB_VIEW) { 7227 Log.v(LOGTAG, "showRectMsg=(top=" + top + ",height=" + 7228 height + ",maxHeight=" + maxHeight + 7229 ",viewHeight=" + viewHeight + ",y=" 7230 + y + ",yPercentInDoc=" + data.mYPercentInDoc + 7231 ",yPercentInView=" + data.mYPercentInView+ ")"); 7232 } 7233 // use the passing content height to cap y as the current 7234 // mContentHeight may not be updated yet 7235 y = Math.max(0, 7236 (Math.min(maxHeight, y + viewHeight) - viewHeight)); 7237 // We need to take into account the visible title height 7238 // when scrolling since y is an absolute view position. 7239 y = Math.max(0, y - getVisibleTitleHeight()); 7240 scrollTo(x, y); 7241 } 7242 break; 7243 7244 case CENTER_FIT_RECT: 7245 Rect r = (Rect)msg.obj; 7246 mInZoomOverview = false; 7247 centerFitRect(r.left, r.top, r.width(), r.height()); 7248 break; 7249 7250 case SET_SCROLLBAR_MODES: 7251 mHorizontalScrollBarMode = msg.arg1; 7252 mVerticalScrollBarMode = msg.arg2; 7253 break; 7254 7255 default: 7256 super.handleMessage(msg); 7257 break; 7258 } 7259 } 7260 } 7261 7262 /** 7263 * Used when receiving messages for REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID 7264 * and UPDATE_TEXT_SELECTION_MSG_ID. Update the selection of WebTextView. 7265 */ 7266 private void updateTextSelectionFromMessage(int nodePointer, 7267 int textGeneration, WebViewCore.TextSelectionData data) { 7268 if (inEditingMode() 7269 && mWebTextView.isSameTextField(nodePointer) 7270 && textGeneration == mTextGeneration) { 7271 mWebTextView.setSelectionFromWebKit(data.mStart, data.mEnd); 7272 } 7273 } 7274 7275 // Class used to use a dropdown for a <select> element 7276 private class InvokeListBox implements Runnable { 7277 // Whether the listbox allows multiple selection. 7278 private boolean mMultiple; 7279 // Passed in to a list with multiple selection to tell 7280 // which items are selected. 7281 private int[] mSelectedArray; 7282 // Passed in to a list with single selection to tell 7283 // where the initial selection is. 7284 private int mSelection; 7285 7286 private Container[] mContainers; 7287 7288 // Need these to provide stable ids to my ArrayAdapter, 7289 // which normally does not have stable ids. (Bug 1250098) 7290 private class Container extends Object { 7291 /** 7292 * Possible values for mEnabled. Keep in sync with OptionStatus in 7293 * WebViewCore.cpp 7294 */ 7295 final static int OPTGROUP = -1; 7296 final static int OPTION_DISABLED = 0; 7297 final static int OPTION_ENABLED = 1; 7298 7299 String mString; 7300 int mEnabled; 7301 int mId; 7302 7303 public String toString() { 7304 return mString; 7305 } 7306 } 7307 7308 /** 7309 * Subclass ArrayAdapter so we can disable OptionGroupLabels, 7310 * and allow filtering. 7311 */ 7312 private class MyArrayListAdapter extends ArrayAdapter<Container> { 7313 public MyArrayListAdapter(Context context, Container[] objects, boolean multiple) { 7314 super(context, 7315 multiple ? com.android.internal.R.layout.select_dialog_multichoice : 7316 com.android.internal.R.layout.select_dialog_singlechoice, 7317 objects); 7318 } 7319 7320 @Override 7321 public View getView(int position, View convertView, 7322 ViewGroup parent) { 7323 // Always pass in null so that we will get a new CheckedTextView 7324 // Otherwise, an item which was previously used as an <optgroup> 7325 // element (i.e. has no check), could get used as an <option> 7326 // element, which needs a checkbox/radio, but it would not have 7327 // one. 7328 convertView = super.getView(position, null, parent); 7329 Container c = item(position); 7330 if (c != null && Container.OPTION_ENABLED != c.mEnabled) { 7331 // ListView does not draw dividers between disabled and 7332 // enabled elements. Use a LinearLayout to provide dividers 7333 LinearLayout layout = new LinearLayout(mContext); 7334 layout.setOrientation(LinearLayout.VERTICAL); 7335 if (position > 0) { 7336 View dividerTop = new View(mContext); 7337 dividerTop.setBackgroundResource( 7338 android.R.drawable.divider_horizontal_bright); 7339 layout.addView(dividerTop); 7340 } 7341 7342 if (Container.OPTGROUP == c.mEnabled) { 7343 // Currently select_dialog_multichoice and 7344 // select_dialog_singlechoice are CheckedTextViews. If 7345 // that changes, the class cast will no longer be valid. 7346 Assert.assertTrue( 7347 convertView instanceof CheckedTextView); 7348 ((CheckedTextView) convertView).setCheckMarkDrawable( 7349 null); 7350 } else { 7351 // c.mEnabled == Container.OPTION_DISABLED 7352 // Draw the disabled element in a disabled state. 7353 convertView.setEnabled(false); 7354 } 7355 7356 layout.addView(convertView); 7357 if (position < getCount() - 1) { 7358 View dividerBottom = new View(mContext); 7359 dividerBottom.setBackgroundResource( 7360 android.R.drawable.divider_horizontal_bright); 7361 layout.addView(dividerBottom); 7362 } 7363 return layout; 7364 } 7365 return convertView; 7366 } 7367 7368 @Override 7369 public boolean hasStableIds() { 7370 // AdapterView's onChanged method uses this to determine whether 7371 // to restore the old state. Return false so that the old (out 7372 // of date) state does not replace the new, valid state. 7373 return false; 7374 } 7375 7376 private Container item(int position) { 7377 if (position < 0 || position >= getCount()) { 7378 return null; 7379 } 7380 return (Container) getItem(position); 7381 } 7382 7383 @Override 7384 public long getItemId(int position) { 7385 Container item = item(position); 7386 if (item == null) { 7387 return -1; 7388 } 7389 return item.mId; 7390 } 7391 7392 @Override 7393 public boolean areAllItemsEnabled() { 7394 return false; 7395 } 7396 7397 @Override 7398 public boolean isEnabled(int position) { 7399 Container item = item(position); 7400 if (item == null) { 7401 return false; 7402 } 7403 return Container.OPTION_ENABLED == item.mEnabled; 7404 } 7405 } 7406 7407 private InvokeListBox(String[] array, int[] enabled, int[] selected) { 7408 mMultiple = true; 7409 mSelectedArray = selected; 7410 7411 int length = array.length; 7412 mContainers = new Container[length]; 7413 for (int i = 0; i < length; i++) { 7414 mContainers[i] = new Container(); 7415 mContainers[i].mString = array[i]; 7416 mContainers[i].mEnabled = enabled[i]; 7417 mContainers[i].mId = i; 7418 } 7419 } 7420 7421 private InvokeListBox(String[] array, int[] enabled, int selection) { 7422 mSelection = selection; 7423 mMultiple = false; 7424 7425 int length = array.length; 7426 mContainers = new Container[length]; 7427 for (int i = 0; i < length; i++) { 7428 mContainers[i] = new Container(); 7429 mContainers[i].mString = array[i]; 7430 mContainers[i].mEnabled = enabled[i]; 7431 mContainers[i].mId = i; 7432 } 7433 } 7434 7435 /* 7436 * Whenever the data set changes due to filtering, this class ensures 7437 * that the checked item remains checked. 7438 */ 7439 private class SingleDataSetObserver extends DataSetObserver { 7440 private long mCheckedId; 7441 private ListView mListView; 7442 private Adapter mAdapter; 7443 7444 /* 7445 * Create a new observer. 7446 * @param id The ID of the item to keep checked. 7447 * @param l ListView for getting and clearing the checked states 7448 * @param a Adapter for getting the IDs 7449 */ 7450 public SingleDataSetObserver(long id, ListView l, Adapter a) { 7451 mCheckedId = id; 7452 mListView = l; 7453 mAdapter = a; 7454 } 7455 7456 public void onChanged() { 7457 // The filter may have changed which item is checked. Find the 7458 // item that the ListView thinks is checked. 7459 int position = mListView.getCheckedItemPosition(); 7460 long id = mAdapter.getItemId(position); 7461 if (mCheckedId != id) { 7462 // Clear the ListView's idea of the checked item, since 7463 // it is incorrect 7464 mListView.clearChoices(); 7465 // Search for mCheckedId. If it is in the filtered list, 7466 // mark it as checked 7467 int count = mAdapter.getCount(); 7468 for (int i = 0; i < count; i++) { 7469 if (mAdapter.getItemId(i) == mCheckedId) { 7470 mListView.setItemChecked(i, true); 7471 break; 7472 } 7473 } 7474 } 7475 } 7476 7477 public void onInvalidate() {} 7478 } 7479 7480 public void run() { 7481 final ListView listView = (ListView) LayoutInflater.from(mContext) 7482 .inflate(com.android.internal.R.layout.select_dialog, null); 7483 final MyArrayListAdapter adapter = new 7484 MyArrayListAdapter(mContext, mContainers, mMultiple); 7485 AlertDialog.Builder b = new AlertDialog.Builder(mContext) 7486 .setView(listView).setCancelable(true) 7487 .setInverseBackgroundForced(true); 7488 7489 if (mMultiple) { 7490 b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { 7491 public void onClick(DialogInterface dialog, int which) { 7492 mWebViewCore.sendMessage( 7493 EventHub.LISTBOX_CHOICES, 7494 adapter.getCount(), 0, 7495 listView.getCheckedItemPositions()); 7496 }}); 7497 b.setNegativeButton(android.R.string.cancel, 7498 new DialogInterface.OnClickListener() { 7499 public void onClick(DialogInterface dialog, int which) { 7500 mWebViewCore.sendMessage( 7501 EventHub.SINGLE_LISTBOX_CHOICE, -2, 0); 7502 }}); 7503 } 7504 final AlertDialog dialog = b.create(); 7505 listView.setAdapter(adapter); 7506 listView.setFocusableInTouchMode(true); 7507 // There is a bug (1250103) where the checks in a ListView with 7508 // multiple items selected are associated with the positions, not 7509 // the ids, so the items do not properly retain their checks when 7510 // filtered. Do not allow filtering on multiple lists until 7511 // that bug is fixed. 7512 7513 listView.setTextFilterEnabled(!mMultiple); 7514 if (mMultiple) { 7515 listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); 7516 int length = mSelectedArray.length; 7517 for (int i = 0; i < length; i++) { 7518 listView.setItemChecked(mSelectedArray[i], true); 7519 } 7520 } else { 7521 listView.setOnItemClickListener(new OnItemClickListener() { 7522 public void onItemClick(AdapterView parent, View v, 7523 int position, long id) { 7524 mWebViewCore.sendMessage( 7525 EventHub.SINGLE_LISTBOX_CHOICE, (int)id, 0); 7526 dialog.dismiss(); 7527 } 7528 }); 7529 if (mSelection != -1) { 7530 listView.setSelection(mSelection); 7531 listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 7532 listView.setItemChecked(mSelection, true); 7533 DataSetObserver observer = new SingleDataSetObserver( 7534 adapter.getItemId(mSelection), listView, adapter); 7535 adapter.registerDataSetObserver(observer); 7536 } 7537 } 7538 dialog.setOnCancelListener(new DialogInterface.OnCancelListener() { 7539 public void onCancel(DialogInterface dialog) { 7540 mWebViewCore.sendMessage( 7541 EventHub.SINGLE_LISTBOX_CHOICE, -2, 0); 7542 } 7543 }); 7544 dialog.show(); 7545 } 7546 } 7547 7548 /* 7549 * Request a dropdown menu for a listbox with multiple selection. 7550 * 7551 * @param array Labels for the listbox. 7552 * @param enabledArray State for each element in the list. See static 7553 * integers in Container class. 7554 * @param selectedArray Which positions are initally selected. 7555 */ 7556 void requestListBox(String[] array, int[] enabledArray, int[] 7557 selectedArray) { 7558 mPrivateHandler.post( 7559 new InvokeListBox(array, enabledArray, selectedArray)); 7560 } 7561 7562 private void updateZoomRange(WebViewCore.RestoreState restoreState, 7563 int viewWidth, int minPrefWidth, boolean updateZoomOverview) { 7564 if (restoreState.mMinScale == 0) { 7565 if (restoreState.mMobileSite) { 7566 if (minPrefWidth > Math.max(0, viewWidth)) { 7567 mMinZoomScale = (float) viewWidth / minPrefWidth; 7568 mMinZoomScaleFixed = false; 7569 if (updateZoomOverview) { 7570 WebSettings settings = getSettings(); 7571 mInZoomOverview = settings.getUseWideViewPort() && 7572 settings.getLoadWithOverviewMode(); 7573 } 7574 } else { 7575 mMinZoomScale = restoreState.mDefaultScale; 7576 mMinZoomScaleFixed = true; 7577 } 7578 } else { 7579 mMinZoomScale = DEFAULT_MIN_ZOOM_SCALE; 7580 mMinZoomScaleFixed = false; 7581 } 7582 } else { 7583 mMinZoomScale = restoreState.mMinScale; 7584 mMinZoomScaleFixed = true; 7585 } 7586 if (restoreState.mMaxScale == 0) { 7587 mMaxZoomScale = DEFAULT_MAX_ZOOM_SCALE; 7588 } else { 7589 mMaxZoomScale = restoreState.mMaxScale; 7590 } 7591 } 7592 7593 /* 7594 * Request a dropdown menu for a listbox with single selection or a single 7595 * <select> element. 7596 * 7597 * @param array Labels for the listbox. 7598 * @param enabledArray State for each element in the list. See static 7599 * integers in Container class. 7600 * @param selection Which position is initally selected. 7601 */ 7602 void requestListBox(String[] array, int[] enabledArray, int selection) { 7603 mPrivateHandler.post( 7604 new InvokeListBox(array, enabledArray, selection)); 7605 } 7606 7607 // called by JNI 7608 private void sendMoveFocus(int frame, int node) { 7609 mWebViewCore.sendMessage(EventHub.SET_MOVE_FOCUS, 7610 new WebViewCore.CursorData(frame, node, 0, 0)); 7611 } 7612 7613 // called by JNI 7614 private void sendMoveMouse(int frame, int node, int x, int y) { 7615 mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE, 7616 new WebViewCore.CursorData(frame, node, x, y)); 7617 } 7618 7619 /* 7620 * Send a mouse move event to the webcore thread. 7621 * 7622 * @param removeFocus Pass true if the "mouse" cursor is now over a node 7623 * which wants key events, but it is not the focus. This 7624 * will make the visual appear as though nothing is in 7625 * focus. Remove the WebTextView, if present, and stop 7626 * drawing the blinking caret. 7627 * called by JNI 7628 */ 7629 private void sendMoveMouseIfLatest(boolean removeFocus) { 7630 if (removeFocus) { 7631 clearTextEntry(true); 7632 } 7633 mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE_IF_LATEST, 7634 cursorData()); 7635 } 7636 7637 // called by JNI 7638 private void sendMotionUp(int touchGeneration, 7639 int frame, int node, int x, int y) { 7640 WebViewCore.TouchUpData touchUpData = new WebViewCore.TouchUpData(); 7641 touchUpData.mMoveGeneration = touchGeneration; 7642 touchUpData.mFrame = frame; 7643 touchUpData.mNode = node; 7644 touchUpData.mX = x; 7645 touchUpData.mY = y; 7646 mWebViewCore.sendMessage(EventHub.TOUCH_UP, touchUpData); 7647 } 7648 7649 7650 private int getScaledMaxXScroll() { 7651 int width; 7652 if (mHeightCanMeasure == false) { 7653 width = getViewWidth() / 4; 7654 } else { 7655 Rect visRect = new Rect(); 7656 calcOurVisibleRect(visRect); 7657 width = visRect.width() / 2; 7658 } 7659 // FIXME the divisor should be retrieved from somewhere 7660 return viewToContentX(width); 7661 } 7662 7663 private int getScaledMaxYScroll() { 7664 int height; 7665 if (mHeightCanMeasure == false) { 7666 height = getViewHeight() / 4; 7667 } else { 7668 Rect visRect = new Rect(); 7669 calcOurVisibleRect(visRect); 7670 height = visRect.height() / 2; 7671 } 7672 // FIXME the divisor should be retrieved from somewhere 7673 // the closest thing today is hard-coded into ScrollView.java 7674 // (from ScrollView.java, line 363) int maxJump = height/2; 7675 return Math.round(height * mInvActualScale); 7676 } 7677 7678 /** 7679 * Called by JNI to invalidate view 7680 */ 7681 private void viewInvalidate() { 7682 invalidate(); 7683 } 7684 7685 /** 7686 * Pass the key to the plugin. This assumes that nativeFocusIsPlugin() 7687 * returned true. 7688 */ 7689 private void letPluginHandleNavKey(int keyCode, long time, boolean down) { 7690 int keyEventAction; 7691 int eventHubAction; 7692 if (down) { 7693 keyEventAction = KeyEvent.ACTION_DOWN; 7694 eventHubAction = EventHub.KEY_DOWN; 7695 playSoundEffect(keyCodeToSoundsEffect(keyCode)); 7696 } else { 7697 keyEventAction = KeyEvent.ACTION_UP; 7698 eventHubAction = EventHub.KEY_UP; 7699 } 7700 KeyEvent event = new KeyEvent(time, time, keyEventAction, keyCode, 7701 1, (mShiftIsPressed ? KeyEvent.META_SHIFT_ON : 0) 7702 | (false ? KeyEvent.META_ALT_ON : 0) // FIXME 7703 | (false ? KeyEvent.META_SYM_ON : 0) // FIXME 7704 , 0, 0, 0); 7705 mWebViewCore.sendMessage(eventHubAction, event); 7706 } 7707 7708 // return true if the key was handled 7709 private boolean navHandledKey(int keyCode, int count, boolean noScroll, 7710 long time) { 7711 if (mNativeClass == 0) { 7712 return false; 7713 } 7714 mLastCursorTime = time; 7715 mLastCursorBounds = nativeGetCursorRingBounds(); 7716 boolean keyHandled 7717 = nativeMoveCursor(keyCode, count, noScroll) == false; 7718 if (DebugFlags.WEB_VIEW) { 7719 Log.v(LOGTAG, "navHandledKey mLastCursorBounds=" + mLastCursorBounds 7720 + " mLastCursorTime=" + mLastCursorTime 7721 + " handled=" + keyHandled); 7722 } 7723 if (keyHandled == false || mHeightCanMeasure == false) { 7724 return keyHandled; 7725 } 7726 Rect contentCursorRingBounds = nativeGetCursorRingBounds(); 7727 if (contentCursorRingBounds.isEmpty()) return keyHandled; 7728 Rect viewCursorRingBounds = contentToViewRect(contentCursorRingBounds); 7729 Rect visRect = new Rect(); 7730 calcOurVisibleRect(visRect); 7731 Rect outset = new Rect(visRect); 7732 int maxXScroll = visRect.width() / 2; 7733 int maxYScroll = visRect.height() / 2; 7734 outset.inset(-maxXScroll, -maxYScroll); 7735 if (Rect.intersects(outset, viewCursorRingBounds) == false) { 7736 return keyHandled; 7737 } 7738 // FIXME: Necessary because ScrollView/ListView do not scroll left/right 7739 int maxH = Math.min(viewCursorRingBounds.right - visRect.right, 7740 maxXScroll); 7741 if (maxH > 0) { 7742 pinScrollBy(maxH, 0, true, 0); 7743 } else { 7744 maxH = Math.max(viewCursorRingBounds.left - visRect.left, 7745 -maxXScroll); 7746 if (maxH < 0) { 7747 pinScrollBy(maxH, 0, true, 0); 7748 } 7749 } 7750 if (mLastCursorBounds.isEmpty()) return keyHandled; 7751 if (mLastCursorBounds.equals(contentCursorRingBounds)) { 7752 return keyHandled; 7753 } 7754 if (DebugFlags.WEB_VIEW) { 7755 Log.v(LOGTAG, "navHandledKey contentCursorRingBounds=" 7756 + contentCursorRingBounds); 7757 } 7758 requestRectangleOnScreen(viewCursorRingBounds); 7759 mUserScroll = true; 7760 return keyHandled; 7761 } 7762 7763 /** 7764 * Set the background color. It's white by default. Pass 7765 * zero to make the view transparent. 7766 * @param color the ARGB color described by Color.java 7767 */ 7768 public void setBackgroundColor(int color) { 7769 mBackgroundColor = color; 7770 mWebViewCore.sendMessage(EventHub.SET_BACKGROUND_COLOR, color); 7771 } 7772 7773 public void debugDump() { 7774 nativeDebugDump(); 7775 mWebViewCore.sendMessage(EventHub.DUMP_NAVTREE); 7776 } 7777 7778 /** 7779 * Draw the HTML page into the specified canvas. This call ignores any 7780 * view-specific zoom, scroll offset, or other changes. It does not draw 7781 * any view-specific chrome, such as progress or URL bars. 7782 * 7783 * @hide only needs to be accessible to Browser and testing 7784 */ 7785 public void drawPage(Canvas canvas) { 7786 mWebViewCore.drawContentPicture(canvas, 0, false, false); 7787 } 7788 7789 /** 7790 * Set the time to wait between passing touches to WebCore. See also the 7791 * TOUCH_SENT_INTERVAL member for further discussion. 7792 * 7793 * @hide This is only used by the DRT test application. 7794 */ 7795 public void setTouchInterval(int interval) { 7796 mCurrentTouchInterval = interval; 7797 } 7798 7799 /** 7800 * Update our cache with updatedText. 7801 * @param updatedText The new text to put in our cache. 7802 */ 7803 /* package */ void updateCachedTextfield(String updatedText) { 7804 // Also place our generation number so that when we look at the cache 7805 // we recognize that it is up to date. 7806 nativeUpdateCachedTextfield(updatedText, mTextGeneration); 7807 } 7808 7809 private native int nativeCacheHitFramePointer(); 7810 private native Rect nativeCacheHitNodeBounds(); 7811 private native int nativeCacheHitNodePointer(); 7812 /* package */ native void nativeClearCursor(); 7813 private native void nativeCreate(int ptr); 7814 private native int nativeCursorFramePointer(); 7815 private native Rect nativeCursorNodeBounds(); 7816 private native int nativeCursorNodePointer(); 7817 /* package */ native boolean nativeCursorMatchesFocus(); 7818 private native boolean nativeCursorIntersects(Rect visibleRect); 7819 private native boolean nativeCursorIsAnchor(); 7820 private native boolean nativeCursorIsTextInput(); 7821 private native Point nativeCursorPosition(); 7822 private native String nativeCursorText(); 7823 /** 7824 * Returns true if the native cursor node says it wants to handle key events 7825 * (ala plugins). This can only be called if mNativeClass is non-zero! 7826 */ 7827 private native boolean nativeCursorWantsKeyEvents(); 7828 private native void nativeDebugDump(); 7829 private native void nativeDestroy(); 7830 private native boolean nativeEvaluateLayersAnimations(); 7831 private native void nativeExtendSelection(int x, int y); 7832 private native void nativeDrawExtras(Canvas canvas, int extra); 7833 private native void nativeDumpDisplayTree(String urlOrNull); 7834 private native int nativeFindAll(String findLower, String findUpper); 7835 private native void nativeFindNext(boolean forward); 7836 /* package */ native int nativeFocusCandidateFramePointer(); 7837 /* package */ native boolean nativeFocusCandidateHasNextTextfield(); 7838 /* package */ native boolean nativeFocusCandidateIsPassword(); 7839 private native boolean nativeFocusCandidateIsRtlText(); 7840 private native boolean nativeFocusCandidateIsTextInput(); 7841 /* package */ native int nativeFocusCandidateMaxLength(); 7842 /* package */ native String nativeFocusCandidateName(); 7843 private native Rect nativeFocusCandidateNodeBounds(); 7844 /* package */ native int nativeFocusCandidatePointer(); 7845 private native String nativeFocusCandidateText(); 7846 private native int nativeFocusCandidateTextSize(); 7847 /** 7848 * Returns an integer corresponding to WebView.cpp::type. 7849 * See WebTextView.setType() 7850 */ 7851 private native int nativeFocusCandidateType(); 7852 private native boolean nativeFocusIsPlugin(); 7853 private native Rect nativeFocusNodeBounds(); 7854 /* package */ native int nativeFocusNodePointer(); 7855 private native Rect nativeGetCursorRingBounds(); 7856 private native String nativeGetSelection(); 7857 private native boolean nativeHasCursorNode(); 7858 private native boolean nativeHasFocusNode(); 7859 private native void nativeHideCursor(); 7860 private native boolean nativeHitSelection(int x, int y); 7861 private native String nativeImageURI(int x, int y); 7862 private native void nativeInstrumentReport(); 7863 /* package */ native boolean nativeMoveCursorToNextTextInput(); 7864 // return true if the page has been scrolled 7865 private native boolean nativeMotionUp(int x, int y, int slop); 7866 // returns false if it handled the key 7867 private native boolean nativeMoveCursor(int keyCode, int count, 7868 boolean noScroll); 7869 private native int nativeMoveGeneration(); 7870 private native void nativeMoveSelection(int x, int y); 7871 private native boolean nativePointInNavCache(int x, int y, int slop); 7872 // Like many other of our native methods, you must make sure that 7873 // mNativeClass is not null before calling this method. 7874 private native void nativeRecordButtons(boolean focused, 7875 boolean pressed, boolean invalidate); 7876 private native void nativeResetSelection(); 7877 private native void nativeSelectAll(); 7878 private native void nativeSelectBestAt(Rect rect); 7879 private native int nativeSelectionX(); 7880 private native int nativeSelectionY(); 7881 private native int nativeFindIndex(); 7882 private native void nativeSetExtendSelection(); 7883 private native void nativeSetFindIsEmpty(); 7884 private native void nativeSetFindIsUp(boolean isUp); 7885 private native void nativeSetFollowedLink(boolean followed); 7886 private native void nativeSetHeightCanMeasure(boolean measure); 7887 private native void nativeSetRootLayer(int layer); 7888 private native void nativeSetSelectionPointer(boolean set, 7889 float scale, int x, int y); 7890 private native boolean nativeStartSelection(int x, int y); 7891 private native void nativeSetSelectionRegion(boolean set); 7892 private native Rect nativeSubtractLayers(Rect content); 7893 private native int nativeTextGeneration(); 7894 // Never call this version except by updateCachedTextfield(String) - 7895 // we always want to pass in our generation number. 7896 private native void nativeUpdateCachedTextfield(String updatedText, 7897 int generation); 7898 private native boolean nativeWordSelection(int x, int y); 7899 // return NO_LEFTEDGE means failure. 7900 private static final int NO_LEFTEDGE = -1; 7901 private native int nativeGetBlockLeftEdge(int x, int y, float scale); 7902} 7903