WebView.java revision e26efa321c66716d58f3e338022caed8852af07e
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.webkit; 18 19import android.app.AlertDialog; 20import android.content.Context; 21import android.content.DialogInterface; 22import android.content.Intent; 23import android.content.DialogInterface.OnCancelListener; 24import android.database.DataSetObserver; 25import android.graphics.Bitmap; 26import android.graphics.Canvas; 27import android.graphics.Color; 28import android.graphics.Paint; 29import android.graphics.Picture; 30import android.graphics.Point; 31import android.graphics.Rect; 32import android.graphics.Region; 33import android.graphics.drawable.Drawable; 34import android.net.http.SslCertificate; 35import android.net.Uri; 36import android.os.Bundle; 37import android.os.Handler; 38import android.os.Message; 39import android.os.ServiceManager; 40import android.os.SystemClock; 41import android.provider.Checkin; 42import android.text.IClipboard; 43import android.text.Selection; 44import android.text.Spannable; 45import android.util.AttributeSet; 46import android.util.EventLog; 47import android.util.Log; 48import android.util.TypedValue; 49import android.view.Gravity; 50import android.view.KeyEvent; 51import android.view.LayoutInflater; 52import android.view.MotionEvent; 53import android.view.SoundEffectConstants; 54import android.view.VelocityTracker; 55import android.view.View; 56import android.view.ViewConfiguration; 57import android.view.ViewGroup; 58import android.view.ViewParent; 59import android.view.ViewTreeObserver; 60import android.view.animation.AlphaAnimation; 61import android.view.inputmethod.InputMethodManager; 62import android.webkit.WebTextView.AutoCompleteAdapter; 63import android.webkit.WebViewCore.EventHub; 64import android.widget.AbsoluteLayout; 65import android.widget.Adapter; 66import android.widget.AdapterView; 67import android.widget.ArrayAdapter; 68import android.widget.CheckedTextView; 69import android.widget.FrameLayout; 70import android.widget.LinearLayout; 71import android.widget.ListView; 72import android.widget.Scroller; 73import android.widget.Toast; 74import android.widget.ZoomButtonsController; 75import android.widget.ZoomControls; 76import android.widget.AdapterView.OnItemClickListener; 77 78import java.io.File; 79import java.io.FileInputStream; 80import java.io.FileNotFoundException; 81import java.io.FileOutputStream; 82import java.io.IOException; 83import java.net.URLDecoder; 84import java.util.ArrayList; 85import java.util.List; 86import java.util.Map; 87 88import junit.framework.Assert; 89 90/** 91 * <p>A View that displays web pages. This class is the basis upon which you 92 * can roll your own web browser or simply display some online content within your Activity. 93 * It uses the WebKit rendering engine to display 94 * web pages and includes methods to navigate forward and backward 95 * through a history, zoom in and out, perform text searches and more.</p> 96 * <p>To enable the built-in zoom, set 97 * {@link #getSettings() WebSettings}.{@link WebSettings#setBuiltInZoomControls(boolean)} 98 * (introduced in API version 3). 99 * <p>Note that, in order for your Activity to access the Internet and load web pages 100 * in a WebView, you must add the <var>INTERNET</var> permissions to your 101 * Android Manifest file:</p> 102 * <pre><uses-permission android:name="android.permission.INTERNET" /></pre> 103 * 104 * <p>This must be a child of the <code><manifest></code> element.</p> 105 * 106 * <h3>Basic usage</h3> 107 * 108 * <p>By default, a WebView provides no browser-like widgets, does not 109 * enable JavaScript and errors will be ignored. If your goal is only 110 * to display some HTML as a part of your UI, this is probably fine; 111 * the user won't need to interact with the web page beyond reading 112 * it, and the web page won't need to interact with the user. If you 113 * actually want a fully blown web browser, then you probably want to 114 * invoke the Browser application with your URL rather than show it 115 * with a WebView. See {@link android.content.Intent} for more information.</p> 116 * 117 * <pre class="prettyprint"> 118 * WebView webview = new WebView(this); 119 * setContentView(webview); 120 * 121 * // Simplest usage: note that an exception will NOT be thrown 122 * // if there is an error loading this page (see below). 123 * webview.loadUrl("http://slashdot.org/"); 124 * 125 * // Of course you can also load from any string: 126 * String summary = "<html><body>You scored <b>192</b> points.</body></html>"; 127 * webview.loadData(summary, "text/html", "utf-8"); 128 * // ... although note that there are restrictions on what this HTML can do. 129 * // See the JavaDocs for loadData and loadDataWithBaseUrl for more info. 130 * </pre> 131 * 132 * <p>A WebView has several customization points where you can add your 133 * own behavior. These are:</p> 134 * 135 * <ul> 136 * <li>Creating and setting a {@link android.webkit.WebChromeClient} subclass. 137 * This class is called when something that might impact a 138 * browser UI happens, for instance, progress updates and 139 * JavaScript alerts are sent here. 140 * </li> 141 * <li>Creating and setting a {@link android.webkit.WebViewClient} subclass. 142 * It will be called when things happen that impact the 143 * rendering of the content, eg, errors or form submissions. You 144 * can also intercept URL loading here.</li> 145 * <li>Via the {@link android.webkit.WebSettings} class, which contains 146 * miscellaneous configuration. </li> 147 * <li>With the {@link android.webkit.WebView#addJavascriptInterface} method. 148 * This lets you bind Java objects into the WebView so they can be 149 * controlled from the web pages JavaScript.</li> 150 * </ul> 151 * 152 * <p>Here's a more complicated example, showing error handling, 153 * settings, and progress notification:</p> 154 * 155 * <pre class="prettyprint"> 156 * // Let's display the progress in the activity title bar, like the 157 * // browser app does. 158 * getWindow().requestFeature(Window.FEATURE_PROGRESS); 159 * 160 * webview.getSettings().setJavaScriptEnabled(true); 161 * 162 * final Activity activity = this; 163 * webview.setWebChromeClient(new WebChromeClient() { 164 * public void onProgressChanged(WebView view, int progress) { 165 * // Activities and WebViews measure progress with different scales. 166 * // The progress meter will automatically disappear when we reach 100% 167 * activity.setProgress(progress * 1000); 168 * } 169 * }); 170 * webview.setWebViewClient(new WebViewClient() { 171 * public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { 172 * Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show(); 173 * } 174 * }); 175 * 176 * webview.loadUrl("http://slashdot.org/"); 177 * </pre> 178 * 179 * <h3>Cookie and window management</h3> 180 * 181 * <p>For obvious security reasons, your application has its own 182 * cache, cookie store etc - it does not share the Browser 183 * applications data. Cookies are managed on a separate thread, so 184 * operations like index building don't block the UI 185 * thread. Follow the instructions in {@link android.webkit.CookieSyncManager} 186 * if you want to use cookies in your application. 187 * </p> 188 * 189 * <p>By default, requests by the HTML to open new windows are 190 * ignored. This is true whether they be opened by JavaScript or by 191 * the target attribute on a link. You can customize your 192 * WebChromeClient to provide your own behaviour for opening multiple windows, 193 * and render them in whatever manner you want.</p> 194 * 195 * <p>Standard behavior for an Activity is to be destroyed and 196 * recreated when the devices orientation is changed. This will cause 197 * the WebView to reload the current page. If you don't want that, you 198 * can set your Activity to handle the orientation and keyboardHidden 199 * changes, and then just leave the WebView alone. It'll automatically 200 * re-orient itself as appropriate.</p> 201 */ 202public class WebView extends AbsoluteLayout 203 implements ViewTreeObserver.OnGlobalFocusChangeListener, 204 ViewGroup.OnHierarchyChangeListener { 205 206 // if AUTO_REDRAW_HACK is true, then the CALL key will toggle redrawing 207 // the screen all-the-time. Good for profiling our drawing code 208 static private final boolean AUTO_REDRAW_HACK = false; 209 // true means redraw the screen all-the-time. Only with AUTO_REDRAW_HACK 210 private boolean mAutoRedraw; 211 212 static final String LOGTAG = "webview"; 213 214 private static class ExtendedZoomControls extends FrameLayout { 215 public ExtendedZoomControls(Context context, AttributeSet attrs) { 216 super(context, attrs); 217 LayoutInflater inflater = (LayoutInflater) 218 context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 219 inflater.inflate(com.android.internal.R.layout.zoom_magnify, this, true); 220 mPlusMinusZoomControls = (ZoomControls) findViewById( 221 com.android.internal.R.id.zoomControls); 222 findViewById(com.android.internal.R.id.zoomMagnify).setVisibility( 223 View.GONE); 224 } 225 226 public void show(boolean showZoom, boolean canZoomOut) { 227 mPlusMinusZoomControls.setVisibility( 228 showZoom ? View.VISIBLE : View.GONE); 229 fade(View.VISIBLE, 0.0f, 1.0f); 230 } 231 232 public void hide() { 233 fade(View.GONE, 1.0f, 0.0f); 234 } 235 236 private void fade(int visibility, float startAlpha, float endAlpha) { 237 AlphaAnimation anim = new AlphaAnimation(startAlpha, endAlpha); 238 anim.setDuration(500); 239 startAnimation(anim); 240 setVisibility(visibility); 241 } 242 243 public boolean hasFocus() { 244 return mPlusMinusZoomControls.hasFocus(); 245 } 246 247 public void setOnZoomInClickListener(OnClickListener listener) { 248 mPlusMinusZoomControls.setOnZoomInClickListener(listener); 249 } 250 251 public void setOnZoomOutClickListener(OnClickListener listener) { 252 mPlusMinusZoomControls.setOnZoomOutClickListener(listener); 253 } 254 255 ZoomControls mPlusMinusZoomControls; 256 } 257 258 /** 259 * Transportation object for returning WebView across thread boundaries. 260 */ 261 public class WebViewTransport { 262 private WebView mWebview; 263 264 /** 265 * Set the WebView to the transportation object. 266 * @param webview The WebView to transport. 267 */ 268 public synchronized void setWebView(WebView webview) { 269 mWebview = webview; 270 } 271 272 /** 273 * Return the WebView object. 274 * @return WebView The transported WebView object. 275 */ 276 public synchronized WebView getWebView() { 277 return mWebview; 278 } 279 } 280 281 // A final CallbackProxy shared by WebViewCore and BrowserFrame. 282 private final CallbackProxy mCallbackProxy; 283 284 private final WebViewDatabase mDatabase; 285 286 // SSL certificate for the main top-level page (if secure) 287 private SslCertificate mCertificate; 288 289 // Native WebView pointer that is 0 until the native object has been 290 // created. 291 private int mNativeClass; 292 // This would be final but it needs to be set to null when the WebView is 293 // destroyed. 294 private WebViewCore mWebViewCore; 295 // Handler for dispatching UI messages. 296 /* package */ final Handler mPrivateHandler = new PrivateHandler(); 297 private WebTextView mWebTextView; 298 // Used to ignore changes to webkit text that arrives to the UI side after 299 // more key events. 300 private int mTextGeneration; 301 302 // Used by WebViewCore to create child views. 303 /* package */ final ViewManager mViewManager; 304 305 // Used to display in full screen mode 306 PluginFullScreenHolder mFullScreenHolder; 307 308 /** 309 * Position of the last touch event. 310 */ 311 private float mLastTouchX; 312 private float mLastTouchY; 313 314 /** 315 * Time of the last touch event. 316 */ 317 private long mLastTouchTime; 318 319 /** 320 * Time of the last time sending touch event to WebViewCore 321 */ 322 private long mLastSentTouchTime; 323 324 /** 325 * The minimum elapsed time before sending another ACTION_MOVE event to 326 * WebViewCore. This really should be tuned for each type of the devices. 327 * For example in Google Map api test case, it takes Dream device at least 328 * 150ms to do a full cycle in the WebViewCore by processing a touch event, 329 * triggering the layout and drawing the picture. While the same process 330 * takes 60+ms on the current high speed device. If we make 331 * TOUCH_SENT_INTERVAL too small, there will be multiple touch events sent 332 * to WebViewCore queue and the real layout and draw events will be pushed 333 * to further, which slows down the refresh rate. Choose 50 to favor the 334 * current high speed devices. For Dream like devices, 100 is a better 335 * choice. Maybe make this in the buildspec later. 336 */ 337 private static final int TOUCH_SENT_INTERVAL = 50; 338 339 /** 340 * Helper class to get velocity for fling 341 */ 342 VelocityTracker mVelocityTracker; 343 private int mMaximumFling; 344 private float mLastVelocity; 345 private float mLastVelX; 346 private float mLastVelY; 347 348 /** 349 * Touch mode 350 */ 351 private int mTouchMode = TOUCH_DONE_MODE; 352 private static final int TOUCH_INIT_MODE = 1; 353 private static final int TOUCH_DRAG_START_MODE = 2; 354 private static final int TOUCH_DRAG_MODE = 3; 355 private static final int TOUCH_SHORTPRESS_START_MODE = 4; 356 private static final int TOUCH_SHORTPRESS_MODE = 5; 357 private static final int TOUCH_DOUBLE_TAP_MODE = 6; 358 private static final int TOUCH_DONE_MODE = 7; 359 private static final int TOUCH_SELECT_MODE = 8; 360 361 // Whether to forward the touch events to WebCore 362 private boolean mForwardTouchEvents = false; 363 364 // Whether to prevent drag during touch. The initial value depends on 365 // mForwardTouchEvents. If WebCore wants touch events, we assume it will 366 // take control of touch events unless it says no for touch down event. 367 private static final int PREVENT_DRAG_NO = 0; 368 private static final int PREVENT_DRAG_MAYBE_YES = 1; 369 private static final int PREVENT_DRAG_YES = 2; 370 private int mPreventDrag = PREVENT_DRAG_NO; 371 372 // by default mPreventLongPress is false. If it is true, long press event 373 // will be handled by WebKit instead of UI. 374 private boolean mPreventLongPress = false; 375 // by default mPreventDoubleTap is false. If it is true, double tap event 376 // will be handled by WebKit instead of UI. 377 private boolean mPreventDoubleTap = false; 378 379 // this needs to be in sync with the logic in WebKit's 380 // EventHandler::handleTouchEvent() 381 private static final int TOUCH_PREVENT_DRAG = 0x1; 382 private static final int TOUCH_PREVENT_LONGPRESS = 0x2; 383 private static final int TOUCH_PREVENT_DOUBLETAP = 0x4; 384 385 // To keep track of whether the current drag was initiated by a WebTextView, 386 // so that we know not to hide the cursor 387 boolean mDragFromTextInput; 388 389 // Whether or not to draw the cursor ring. 390 private boolean mDrawCursorRing = true; 391 392 // true if onPause has been called (and not onResume) 393 private boolean mIsPaused; 394 395 /** 396 * Customizable constant 397 */ 398 // pre-computed square of ViewConfiguration.getScaledTouchSlop() 399 private int mTouchSlopSquare; 400 // pre-computed square of ViewConfiguration.getScaledDoubleTapSlop() 401 private int mDoubleTapSlopSquare; 402 // pre-computed density adjusted navigation slop 403 private int mNavSlop; 404 // This should be ViewConfiguration.getTapTimeout() 405 // But system time out is 100ms, which is too short for the browser. 406 // In the browser, if it switches out of tap too soon, jump tap won't work. 407 private static final int TAP_TIMEOUT = 200; 408 // This should be ViewConfiguration.getLongPressTimeout() 409 // But system time out is 500ms, which is too short for the browser. 410 // With a short timeout, it's difficult to treat trigger a short press. 411 private static final int LONG_PRESS_TIMEOUT = 1000; 412 // needed to avoid flinging after a pause of no movement 413 private static final int MIN_FLING_TIME = 250; 414 // draw unfiltered after drag is held without movement 415 private static final int MOTIONLESS_TIME = 100; 416 // The time that the Zoom Controls are visible before fading away 417 private static final long ZOOM_CONTROLS_TIMEOUT = 418 ViewConfiguration.getZoomControlsTimeout(); 419 // The amount of content to overlap between two screens when going through 420 // pages with the space bar, in pixels. 421 private static final int PAGE_SCROLL_OVERLAP = 24; 422 423 /** 424 * These prevent calling requestLayout if either dimension is fixed. This 425 * depends on the layout parameters and the measure specs. 426 */ 427 boolean mWidthCanMeasure; 428 boolean mHeightCanMeasure; 429 430 // Remember the last dimensions we sent to the native side so we can avoid 431 // sending the same dimensions more than once. 432 int mLastWidthSent; 433 int mLastHeightSent; 434 435 private int mContentWidth; // cache of value from WebViewCore 436 private int mContentHeight; // cache of value from WebViewCore 437 438 // Need to have the separate control for horizontal and vertical scrollbar 439 // style than the View's single scrollbar style 440 private boolean mOverlayHorizontalScrollbar = true; 441 private boolean mOverlayVerticalScrollbar = false; 442 443 // our standard speed. this way small distances will be traversed in less 444 // time than large distances, but we cap the duration, so that very large 445 // distances won't take too long to get there. 446 private static final int STD_SPEED = 480; // pixels per second 447 // time for the longest scroll animation 448 private static final int MAX_DURATION = 750; // milliseconds 449 private static final int SLIDE_TITLE_DURATION = 500; // milliseconds 450 private Scroller mScroller; 451 452 private boolean mWrapContent; 453 private static final int MOTIONLESS_FALSE = 0; 454 private static final int MOTIONLESS_PENDING = 1; 455 private static final int MOTIONLESS_TRUE = 2; 456 private int mHeldMotionless; 457 458 /** 459 * Private message ids 460 */ 461 private static final int REMEMBER_PASSWORD = 1; 462 private static final int NEVER_REMEMBER_PASSWORD = 2; 463 private static final int SWITCH_TO_SHORTPRESS = 3; 464 private static final int SWITCH_TO_LONGPRESS = 4; 465 private static final int RELEASE_SINGLE_TAP = 5; 466 private static final int REQUEST_FORM_DATA = 6; 467 private static final int RESUME_WEBCORE_UPDATE = 7; 468 private static final int DRAG_HELD_MOTIONLESS = 8; 469 private static final int AWAKEN_SCROLL_BARS = 9; 470 471 //! arg1=x, arg2=y 472 static final int SCROLL_TO_MSG_ID = 10; 473 static final int SCROLL_BY_MSG_ID = 11; 474 //! arg1=x, arg2=y 475 static final int SPAWN_SCROLL_TO_MSG_ID = 12; 476 //! arg1=x, arg2=y 477 static final int SYNC_SCROLL_TO_MSG_ID = 13; 478 static final int NEW_PICTURE_MSG_ID = 14; 479 static final int UPDATE_TEXT_ENTRY_MSG_ID = 15; 480 static final int WEBCORE_INITIALIZED_MSG_ID = 16; 481 static final int UPDATE_TEXTFIELD_TEXT_MSG_ID = 17; 482 static final int FIND_AGAIN = 18; 483 static final int MOVE_OUT_OF_PLUGIN = 19; 484 static final int CLEAR_TEXT_ENTRY = 20; 485 static final int UPDATE_TEXT_SELECTION_MSG_ID = 21; 486 static final int UPDATE_CLIPBOARD = 22; 487 static final int LONG_PRESS_CENTER = 23; 488 static final int PREVENT_TOUCH_ID = 24; 489 static final int WEBCORE_NEED_TOUCH_EVENTS = 25; 490 // obj=Rect in doc coordinates 491 static final int INVAL_RECT_MSG_ID = 26; 492 static final int REQUEST_KEYBOARD = 27; 493 static final int DO_MOTION_UP = 28; 494 static final int SHOW_FULLSCREEN = 29; 495 static final int HIDE_FULLSCREEN = 30; 496 static final int DOM_FOCUS_CHANGED = 31; 497 498 static final String[] HandlerDebugString = { 499 "REMEMBER_PASSWORD", // = 1; 500 "NEVER_REMEMBER_PASSWORD", // = 2; 501 "SWITCH_TO_SHORTPRESS", // = 3; 502 "SWITCH_TO_LONGPRESS", // = 4; 503 "RELEASE_SINGLE_TAP", // = 5; 504 "REQUEST_FORM_DATA", // = 6; 505 "RESUME_WEBCORE_UPDATE", // = 7; 506 "DRAG_HELD_MOTIONLESS", // = 8; 507 "AWAKEN_SCROLL_BARS", // = 9; 508 "SCROLL_TO_MSG_ID", // = 10; 509 "SCROLL_BY_MSG_ID", // = 11; 510 "SPAWN_SCROLL_TO_MSG_ID", // = 12; 511 "SYNC_SCROLL_TO_MSG_ID", // = 13; 512 "NEW_PICTURE_MSG_ID", // = 14; 513 "UPDATE_TEXT_ENTRY_MSG_ID", // = 15; 514 "WEBCORE_INITIALIZED_MSG_ID", // = 16; 515 "UPDATE_TEXTFIELD_TEXT_MSG_ID", // = 17; 516 "FIND_AGAIN", // = 18; 517 "MOVE_OUT_OF_PLUGIN", // = 19; 518 "CLEAR_TEXT_ENTRY", // = 20; 519 "UPDATE_TEXT_SELECTION_MSG_ID", // = 21; 520 "UPDATE_CLIPBOARD", // = 22; 521 "LONG_PRESS_CENTER", // = 23; 522 "PREVENT_TOUCH_ID", // = 24; 523 "WEBCORE_NEED_TOUCH_EVENTS", // = 25; 524 "INVAL_RECT_MSG_ID", // = 26; 525 "REQUEST_KEYBOARD", // = 27; 526 "DO_MOTION_UP", // = 28; 527 "SHOW_FULLSCREEN", // = 29; 528 "HIDE_FULLSCREEN", // = 30; 529 "DOM_FOCUS_CHANGED" // = 31; 530 }; 531 532 // If the site doesn't use the viewport meta tag to specify the viewport, 533 // use DEFAULT_VIEWPORT_WIDTH as the default viewport width 534 static final int DEFAULT_VIEWPORT_WIDTH = 800; 535 536 // normally we try to fit the content to the minimum preferred width 537 // calculated by the Webkit. To avoid the bad behavior when some site's 538 // minimum preferred width keeps growing when changing the viewport width or 539 // the minimum preferred width is huge, an upper limit is needed. 540 static int sMaxViewportWidth = DEFAULT_VIEWPORT_WIDTH; 541 542 // default scale limit. Depending on the display density 543 private static float DEFAULT_MAX_ZOOM_SCALE; 544 private static float DEFAULT_MIN_ZOOM_SCALE; 545 // scale limit, which can be set through viewport meta tag in the web page 546 private float mMaxZoomScale; 547 private float mMinZoomScale; 548 private boolean mMinZoomScaleFixed = true; 549 550 // initial scale in percent. 0 means using default. 551 private int mInitialScaleInPercent = 0; 552 553 // while in the zoom overview mode, the page's width is fully fit to the 554 // current window. The page is alive, in another words, you can click to 555 // follow the links. Double tap will toggle between zoom overview mode and 556 // the last zoom scale. 557 boolean mInZoomOverview = false; 558 559 // ideally mZoomOverviewWidth should be mContentWidth. But sites like espn, 560 // engadget always have wider mContentWidth no matter what viewport size is. 561 int mZoomOverviewWidth = DEFAULT_VIEWPORT_WIDTH; 562 float mLastScale; 563 564 // default scale. Depending on the display density. 565 static int DEFAULT_SCALE_PERCENT; 566 private float mDefaultScale; 567 568 // set to true temporarily while the zoom control is being dragged 569 private boolean mPreviewZoomOnly = false; 570 571 // computed scale and inverse, from mZoomWidth. 572 private float mActualScale; 573 private float mInvActualScale; 574 // if this is non-zero, it is used on drawing rather than mActualScale 575 private float mZoomScale; 576 private float mInvInitialZoomScale; 577 private float mInvFinalZoomScale; 578 private int mInitialScrollX; 579 private int mInitialScrollY; 580 private long mZoomStart; 581 private static final int ZOOM_ANIMATION_LENGTH = 500; 582 583 private boolean mUserScroll = false; 584 585 private int mSnapScrollMode = SNAP_NONE; 586 private static final int SNAP_NONE = 0; 587 private static final int SNAP_LOCK = 1; // not a separate state 588 private static final int SNAP_X = 2; // may be combined with SNAP_LOCK 589 private static final int SNAP_Y = 4; // may be combined with SNAP_LOCK 590 private boolean mSnapPositive; 591 592 // Used to match key downs and key ups 593 private boolean mGotKeyDown; 594 595 /* package */ static boolean mLogEvent = true; 596 private static final int EVENT_LOG_ZOOM_LEVEL_CHANGE = 70101; 597 private static final int EVENT_LOG_DOUBLE_TAP_DURATION = 70102; 598 599 // for event log 600 private long mLastTouchUpTime = 0; 601 602 /** 603 * URI scheme for telephone number 604 */ 605 public static final String SCHEME_TEL = "tel:"; 606 /** 607 * URI scheme for email address 608 */ 609 public static final String SCHEME_MAILTO = "mailto:"; 610 /** 611 * URI scheme for map address 612 */ 613 public static final String SCHEME_GEO = "geo:0,0?q="; 614 615 private int mBackgroundColor = Color.WHITE; 616 617 // Used to notify listeners of a new picture. 618 private PictureListener mPictureListener; 619 /** 620 * Interface to listen for new pictures as they change. 621 */ 622 public interface PictureListener { 623 /** 624 * Notify the listener that the picture has changed. 625 * @param view The WebView that owns the picture. 626 * @param picture The new picture. 627 */ 628 public void onNewPicture(WebView view, Picture picture); 629 } 630 631 // FIXME: Want to make this public, but need to change the API file. 632 public /*static*/ class HitTestResult { 633 /** 634 * Default HitTestResult, where the target is unknown 635 */ 636 public static final int UNKNOWN_TYPE = 0; 637 /** 638 * HitTestResult for hitting a HTML::a tag 639 */ 640 public static final int ANCHOR_TYPE = 1; 641 /** 642 * HitTestResult for hitting a phone number 643 */ 644 public static final int PHONE_TYPE = 2; 645 /** 646 * HitTestResult for hitting a map address 647 */ 648 public static final int GEO_TYPE = 3; 649 /** 650 * HitTestResult for hitting an email address 651 */ 652 public static final int EMAIL_TYPE = 4; 653 /** 654 * HitTestResult for hitting an HTML::img tag 655 */ 656 public static final int IMAGE_TYPE = 5; 657 /** 658 * HitTestResult for hitting a HTML::a tag which contains HTML::img 659 */ 660 public static final int IMAGE_ANCHOR_TYPE = 6; 661 /** 662 * HitTestResult for hitting a HTML::a tag with src=http 663 */ 664 public static final int SRC_ANCHOR_TYPE = 7; 665 /** 666 * HitTestResult for hitting a HTML::a tag with src=http + HTML::img 667 */ 668 public static final int SRC_IMAGE_ANCHOR_TYPE = 8; 669 /** 670 * HitTestResult for hitting an edit text area 671 */ 672 public static final int EDIT_TEXT_TYPE = 9; 673 674 private int mType; 675 private String mExtra; 676 677 HitTestResult() { 678 mType = UNKNOWN_TYPE; 679 } 680 681 private void setType(int type) { 682 mType = type; 683 } 684 685 private void setExtra(String extra) { 686 mExtra = extra; 687 } 688 689 public int getType() { 690 return mType; 691 } 692 693 public String getExtra() { 694 return mExtra; 695 } 696 } 697 698 // The View containing the zoom controls 699 private ExtendedZoomControls mZoomControls; 700 private Runnable mZoomControlRunnable; 701 702 private ZoomButtonsController mZoomButtonsController; 703 704 // These keep track of the center point of the zoom. They are used to 705 // determine the point around which we should zoom. 706 private float mZoomCenterX; 707 private float mZoomCenterY; 708 709 private ZoomButtonsController.OnZoomListener mZoomListener = 710 new ZoomButtonsController.OnZoomListener() { 711 712 public void onVisibilityChanged(boolean visible) { 713 if (visible) { 714 switchOutDrawHistory(); 715 // Bring back the hidden zoom controls. 716 mZoomButtonsController.getZoomControls().setVisibility( 717 View.VISIBLE); 718 updateZoomButtonsEnabled(); 719 } 720 } 721 722 public void onZoom(boolean zoomIn) { 723 if (zoomIn) { 724 zoomIn(); 725 } else { 726 zoomOut(); 727 } 728 729 updateZoomButtonsEnabled(); 730 } 731 }; 732 733 /** 734 * Construct a new WebView with a Context object. 735 * @param context A Context object used to access application assets. 736 */ 737 public WebView(Context context) { 738 this(context, null); 739 } 740 741 /** 742 * Construct a new WebView with layout parameters. 743 * @param context A Context object used to access application assets. 744 * @param attrs An AttributeSet passed to our parent. 745 */ 746 public WebView(Context context, AttributeSet attrs) { 747 this(context, attrs, com.android.internal.R.attr.webViewStyle); 748 } 749 750 /** 751 * Construct a new WebView with layout parameters and a default style. 752 * @param context A Context object used to access application assets. 753 * @param attrs An AttributeSet passed to our parent. 754 * @param defStyle The default style resource ID. 755 */ 756 public WebView(Context context, AttributeSet attrs, int defStyle) { 757 this(context, attrs, defStyle, null); 758 } 759 760 /** 761 * Construct a new WebView with layout parameters, a default style and a set 762 * of custom Javscript interfaces to be added to the WebView at initialization 763 * time. This guarantees that these interfaces will be available when the JS 764 * context is initialized. 765 * @param context A Context object used to access application assets. 766 * @param attrs An AttributeSet passed to our parent. 767 * @param defStyle The default style resource ID. 768 * @param javascriptInterfaces is a Map of intareface names, as keys, and 769 * object implementing those interfaces, as values. 770 * @hide pending API council approval. 771 */ 772 protected WebView(Context context, AttributeSet attrs, int defStyle, 773 Map<String, Object> javascriptInterfaces) { 774 super(context, attrs, defStyle); 775 init(); 776 777 mCallbackProxy = new CallbackProxy(context, this); 778 mViewManager = new ViewManager(this); 779 mWebViewCore = new WebViewCore(context, this, mCallbackProxy, javascriptInterfaces); 780 mDatabase = WebViewDatabase.getInstance(context); 781 mScroller = new Scroller(context); 782 783 mZoomButtonsController = new ZoomButtonsController(this); 784 mZoomButtonsController.setOnZoomListener(mZoomListener); 785 // ZoomButtonsController positions the buttons at the bottom, but in 786 // the middle. Change their layout parameters so they appear on the 787 // right. 788 View controls = mZoomButtonsController.getZoomControls(); 789 ViewGroup.LayoutParams params = controls.getLayoutParams(); 790 if (params instanceof FrameLayout.LayoutParams) { 791 FrameLayout.LayoutParams frameParams = (FrameLayout.LayoutParams) 792 params; 793 frameParams.gravity = Gravity.RIGHT; 794 } 795 } 796 797 private void updateZoomButtonsEnabled() { 798 boolean canZoomIn = mActualScale < mMaxZoomScale; 799 boolean canZoomOut = mActualScale > mMinZoomScale && !mInZoomOverview; 800 if (!canZoomIn && !canZoomOut) { 801 // Hide the zoom in and out buttons, as well as the fit to page 802 // button, if the page cannot zoom 803 mZoomButtonsController.getZoomControls().setVisibility(View.GONE); 804 } else { 805 // Set each one individually, as a page may be able to zoom in 806 // or out. 807 mZoomButtonsController.setZoomInEnabled(canZoomIn); 808 mZoomButtonsController.setZoomOutEnabled(canZoomOut); 809 } 810 } 811 812 private void init() { 813 setWillNotDraw(false); 814 setFocusable(true); 815 setFocusableInTouchMode(true); 816 setClickable(true); 817 setLongClickable(true); 818 819 final ViewConfiguration configuration = ViewConfiguration.get(getContext()); 820 int slop = configuration.getScaledTouchSlop(); 821 mTouchSlopSquare = slop * slop; 822 mMinLockSnapReverseDistance = slop; 823 slop = configuration.getScaledDoubleTapSlop(); 824 mDoubleTapSlopSquare = slop * slop; 825 final float density = getContext().getResources().getDisplayMetrics().density; 826 // use one line height, 16 based on our current default font, for how 827 // far we allow a touch be away from the edge of a link 828 mNavSlop = (int) (16 * density); 829 // density adjusted scale factors 830 DEFAULT_SCALE_PERCENT = (int) (100 * density); 831 mDefaultScale = density; 832 mActualScale = density; 833 mInvActualScale = 1 / density; 834 DEFAULT_MAX_ZOOM_SCALE = 4.0f * density; 835 DEFAULT_MIN_ZOOM_SCALE = 0.25f * density; 836 mMaxZoomScale = DEFAULT_MAX_ZOOM_SCALE; 837 mMinZoomScale = DEFAULT_MIN_ZOOM_SCALE; 838 mMaximumFling = configuration.getScaledMaximumFlingVelocity(); 839 } 840 841 /* package */void updateDefaultZoomDensity(int zoomDensity) { 842 final float density = getContext().getResources().getDisplayMetrics().density 843 * 100 / zoomDensity; 844 if (Math.abs(density - mDefaultScale) > 0.01) { 845 float scaleFactor = density / mDefaultScale; 846 // adjust the limits 847 mNavSlop = (int) (16 * density); 848 DEFAULT_SCALE_PERCENT = (int) (100 * density); 849 DEFAULT_MAX_ZOOM_SCALE = 4.0f * density; 850 DEFAULT_MIN_ZOOM_SCALE = 0.25f * density; 851 mDefaultScale = density; 852 mMaxZoomScale *= scaleFactor; 853 mMinZoomScale *= scaleFactor; 854 setNewZoomScale(mActualScale * scaleFactor, false); 855 } 856 } 857 858 /* package */ boolean onSavePassword(String schemePlusHost, String username, 859 String password, final Message resumeMsg) { 860 boolean rVal = false; 861 if (resumeMsg == null) { 862 // null resumeMsg implies saving password silently 863 mDatabase.setUsernamePassword(schemePlusHost, username, password); 864 } else { 865 final Message remember = mPrivateHandler.obtainMessage( 866 REMEMBER_PASSWORD); 867 remember.getData().putString("host", schemePlusHost); 868 remember.getData().putString("username", username); 869 remember.getData().putString("password", password); 870 remember.obj = resumeMsg; 871 872 final Message neverRemember = mPrivateHandler.obtainMessage( 873 NEVER_REMEMBER_PASSWORD); 874 neverRemember.getData().putString("host", schemePlusHost); 875 neverRemember.getData().putString("username", username); 876 neverRemember.getData().putString("password", password); 877 neverRemember.obj = resumeMsg; 878 879 new AlertDialog.Builder(getContext()) 880 .setTitle(com.android.internal.R.string.save_password_label) 881 .setMessage(com.android.internal.R.string.save_password_message) 882 .setPositiveButton(com.android.internal.R.string.save_password_notnow, 883 new DialogInterface.OnClickListener() { 884 public void onClick(DialogInterface dialog, int which) { 885 resumeMsg.sendToTarget(); 886 } 887 }) 888 .setNeutralButton(com.android.internal.R.string.save_password_remember, 889 new DialogInterface.OnClickListener() { 890 public void onClick(DialogInterface dialog, int which) { 891 remember.sendToTarget(); 892 } 893 }) 894 .setNegativeButton(com.android.internal.R.string.save_password_never, 895 new DialogInterface.OnClickListener() { 896 public void onClick(DialogInterface dialog, int which) { 897 neverRemember.sendToTarget(); 898 } 899 }) 900 .setOnCancelListener(new OnCancelListener() { 901 public void onCancel(DialogInterface dialog) { 902 resumeMsg.sendToTarget(); 903 } 904 }).show(); 905 // Return true so that WebViewCore will pause while the dialog is 906 // up. 907 rVal = true; 908 } 909 return rVal; 910 } 911 912 @Override 913 public void setScrollBarStyle(int style) { 914 if (style == View.SCROLLBARS_INSIDE_INSET 915 || style == View.SCROLLBARS_OUTSIDE_INSET) { 916 mOverlayHorizontalScrollbar = mOverlayVerticalScrollbar = false; 917 } else { 918 mOverlayHorizontalScrollbar = mOverlayVerticalScrollbar = true; 919 } 920 super.setScrollBarStyle(style); 921 } 922 923 /** 924 * Specify whether the horizontal scrollbar has overlay style. 925 * @param overlay TRUE if horizontal scrollbar should have overlay style. 926 */ 927 public void setHorizontalScrollbarOverlay(boolean overlay) { 928 mOverlayHorizontalScrollbar = overlay; 929 } 930 931 /** 932 * Specify whether the vertical scrollbar has overlay style. 933 * @param overlay TRUE if vertical scrollbar should have overlay style. 934 */ 935 public void setVerticalScrollbarOverlay(boolean overlay) { 936 mOverlayVerticalScrollbar = overlay; 937 } 938 939 /** 940 * Return whether horizontal scrollbar has overlay style 941 * @return TRUE if horizontal scrollbar has overlay style. 942 */ 943 public boolean overlayHorizontalScrollbar() { 944 return mOverlayHorizontalScrollbar; 945 } 946 947 /** 948 * Return whether vertical scrollbar has overlay style 949 * @return TRUE if vertical scrollbar has overlay style. 950 */ 951 public boolean overlayVerticalScrollbar() { 952 return mOverlayVerticalScrollbar; 953 } 954 955 /* 956 * Return the width of the view where the content of WebView should render 957 * to. 958 * Note: this can be called from WebCoreThread. 959 */ 960 /* package */ int getViewWidth() { 961 if (!isVerticalScrollBarEnabled() || mOverlayVerticalScrollbar) { 962 return getWidth(); 963 } else { 964 return getWidth() - getVerticalScrollbarWidth(); 965 } 966 } 967 968 /* 969 * returns the height of the titlebarview (if any). Does not care about 970 * scrolling 971 */ 972 private int getTitleHeight() { 973 return mTitleBar != null ? mTitleBar.getHeight() : 0; 974 } 975 976 /* 977 * Return the amount of the titlebarview (if any) that is visible 978 */ 979 private int getVisibleTitleHeight() { 980 return Math.max(getTitleHeight() - mScrollY, 0); 981 } 982 983 /* 984 * Return the height of the view where the content of WebView should render 985 * to. Note that this excludes mTitleBar, if there is one. 986 * Note: this can be called from WebCoreThread. 987 */ 988 /* package */ int getViewHeight() { 989 return getViewHeightWithTitle() - getVisibleTitleHeight(); 990 } 991 992 private int getViewHeightWithTitle() { 993 int height = getHeight(); 994 if (isHorizontalScrollBarEnabled() && !mOverlayHorizontalScrollbar) { 995 height -= getHorizontalScrollbarHeight(); 996 } 997 return height; 998 } 999 1000 /** 1001 * @return The SSL certificate for the main top-level page or null if 1002 * there is no certificate (the site is not secure). 1003 */ 1004 public SslCertificate getCertificate() { 1005 return mCertificate; 1006 } 1007 1008 /** 1009 * Sets the SSL certificate for the main top-level page. 1010 */ 1011 public void setCertificate(SslCertificate certificate) { 1012 // here, the certificate can be null (if the site is not secure) 1013 mCertificate = certificate; 1014 } 1015 1016 //------------------------------------------------------------------------- 1017 // Methods called by activity 1018 //------------------------------------------------------------------------- 1019 1020 /** 1021 * Save the username and password for a particular host in the WebView's 1022 * internal database. 1023 * @param host The host that required the credentials. 1024 * @param username The username for the given host. 1025 * @param password The password for the given host. 1026 */ 1027 public void savePassword(String host, String username, String password) { 1028 mDatabase.setUsernamePassword(host, username, password); 1029 } 1030 1031 /** 1032 * Set the HTTP authentication credentials for a given host and realm. 1033 * 1034 * @param host The host for the credentials. 1035 * @param realm The realm for the credentials. 1036 * @param username The username for the password. If it is null, it means 1037 * password can't be saved. 1038 * @param password The password 1039 */ 1040 public void setHttpAuthUsernamePassword(String host, String realm, 1041 String username, String password) { 1042 mDatabase.setHttpAuthUsernamePassword(host, realm, username, password); 1043 } 1044 1045 /** 1046 * Retrieve the HTTP authentication username and password for a given 1047 * host & realm pair 1048 * 1049 * @param host The host for which the credentials apply. 1050 * @param realm The realm for which the credentials apply. 1051 * @return String[] if found, String[0] is username, which can be null and 1052 * String[1] is password. Return null if it can't find anything. 1053 */ 1054 public String[] getHttpAuthUsernamePassword(String host, String realm) { 1055 return mDatabase.getHttpAuthUsernamePassword(host, realm); 1056 } 1057 1058 /** 1059 * Destroy the internal state of the WebView. This method should be called 1060 * after the WebView has been removed from the view system. No other 1061 * methods may be called on a WebView after destroy. 1062 */ 1063 public void destroy() { 1064 clearTextEntry(); 1065 if (mWebViewCore != null) { 1066 // Set the handlers to null before destroying WebViewCore so no 1067 // more messages will be posted. 1068 mCallbackProxy.setWebViewClient(null); 1069 mCallbackProxy.setWebChromeClient(null); 1070 // Tell WebViewCore to destroy itself 1071 WebViewCore webViewCore = mWebViewCore; 1072 mWebViewCore = null; // prevent using partial webViewCore 1073 webViewCore.destroy(); 1074 // Remove any pending messages that might not be serviced yet. 1075 mPrivateHandler.removeCallbacksAndMessages(null); 1076 mCallbackProxy.removeCallbacksAndMessages(null); 1077 // Wake up the WebCore thread just in case it is waiting for a 1078 // javascript dialog. 1079 synchronized (mCallbackProxy) { 1080 mCallbackProxy.notify(); 1081 } 1082 } 1083 if (mNativeClass != 0) { 1084 nativeDestroy(); 1085 mNativeClass = 0; 1086 } 1087 } 1088 1089 /** 1090 * Enables platform notifications of data state and proxy changes. 1091 */ 1092 public static void enablePlatformNotifications() { 1093 Network.enablePlatformNotifications(); 1094 } 1095 1096 /** 1097 * If platform notifications are enabled, this should be called 1098 * from the Activity's onPause() or onStop(). 1099 */ 1100 public static void disablePlatformNotifications() { 1101 Network.disablePlatformNotifications(); 1102 } 1103 1104 /** 1105 * Sets JavaScript engine flags. 1106 * 1107 * @param flags JS engine flags in a String 1108 * 1109 * @hide pending API solidification 1110 */ 1111 public void setJsFlags(String flags) { 1112 mWebViewCore.sendMessage(EventHub.SET_JS_FLAGS, flags); 1113 } 1114 1115 /** 1116 * Inform WebView of the network state. This is used to set 1117 * the javascript property window.navigator.isOnline and 1118 * generates the online/offline event as specified in HTML5, sec. 5.7.7 1119 * @param networkUp boolean indicating if network is available 1120 */ 1121 public void setNetworkAvailable(boolean networkUp) { 1122 mWebViewCore.sendMessage(EventHub.SET_NETWORK_STATE, 1123 networkUp ? 1 : 0, 0); 1124 } 1125 1126 /** 1127 * Save the state of this WebView used in 1128 * {@link android.app.Activity#onSaveInstanceState}. Please note that this 1129 * method no longer stores the display data for this WebView. The previous 1130 * behavior could potentially leak files if {@link #restoreState} was never 1131 * called. See {@link #savePicture} and {@link #restorePicture} for saving 1132 * and restoring the display data. 1133 * @param outState The Bundle to store the WebView state. 1134 * @return The same copy of the back/forward list used to save the state. If 1135 * saveState fails, the returned list will be null. 1136 * @see #savePicture 1137 * @see #restorePicture 1138 */ 1139 public WebBackForwardList saveState(Bundle outState) { 1140 if (outState == null) { 1141 return null; 1142 } 1143 // We grab a copy of the back/forward list because a client of WebView 1144 // may have invalidated the history list by calling clearHistory. 1145 WebBackForwardList list = copyBackForwardList(); 1146 final int currentIndex = list.getCurrentIndex(); 1147 final int size = list.getSize(); 1148 // We should fail saving the state if the list is empty or the index is 1149 // not in a valid range. 1150 if (currentIndex < 0 || currentIndex >= size || size == 0) { 1151 return null; 1152 } 1153 outState.putInt("index", currentIndex); 1154 // FIXME: This should just be a byte[][] instead of ArrayList but 1155 // Parcel.java does not have the code to handle multi-dimensional 1156 // arrays. 1157 ArrayList<byte[]> history = new ArrayList<byte[]>(size); 1158 for (int i = 0; i < size; i++) { 1159 WebHistoryItem item = list.getItemAtIndex(i); 1160 if (null == item) { 1161 // FIXME: this shouldn't happen 1162 // need to determine how item got set to null 1163 Log.w(LOGTAG, "saveState: Unexpected null history item."); 1164 return null; 1165 } 1166 byte[] data = item.getFlattenedData(); 1167 if (data == null) { 1168 // It would be very odd to not have any data for a given history 1169 // item. And we will fail to rebuild the history list without 1170 // flattened data. 1171 return null; 1172 } 1173 history.add(data); 1174 } 1175 outState.putSerializable("history", history); 1176 if (mCertificate != null) { 1177 outState.putBundle("certificate", 1178 SslCertificate.saveState(mCertificate)); 1179 } 1180 return list; 1181 } 1182 1183 /** 1184 * Save the current display data to the Bundle given. Used in conjunction 1185 * with {@link #saveState}. 1186 * @param b A Bundle to store the display data. 1187 * @param dest The file to store the serialized picture data. Will be 1188 * overwritten with this WebView's picture data. 1189 * @return True if the picture was successfully saved. 1190 */ 1191 public boolean savePicture(Bundle b, File dest) { 1192 if (dest == null || b == null) { 1193 return false; 1194 } 1195 final Picture p = capturePicture(); 1196 try { 1197 final FileOutputStream out = new FileOutputStream(dest); 1198 p.writeToStream(out); 1199 out.close(); 1200 } catch (FileNotFoundException e){ 1201 e.printStackTrace(); 1202 } catch (IOException e) { 1203 e.printStackTrace(); 1204 } catch (RuntimeException e) { 1205 e.printStackTrace(); 1206 } 1207 if (dest.length() > 0) { 1208 b.putInt("scrollX", mScrollX); 1209 b.putInt("scrollY", mScrollY); 1210 b.putFloat("scale", mActualScale); 1211 if (mInZoomOverview) { 1212 b.putFloat("lastScale", mLastScale); 1213 } 1214 return true; 1215 } 1216 return false; 1217 } 1218 1219 /** 1220 * Restore the display data that was save in {@link #savePicture}. Used in 1221 * conjunction with {@link #restoreState}. 1222 * @param b A Bundle containing the saved display data. 1223 * @param src The file where the picture data was stored. 1224 * @return True if the picture was successfully restored. 1225 */ 1226 public boolean restorePicture(Bundle b, File src) { 1227 if (src == null || b == null) { 1228 return false; 1229 } 1230 if (src.exists()) { 1231 Picture p = null; 1232 try { 1233 final FileInputStream in = new FileInputStream(src); 1234 p = Picture.createFromStream(in); 1235 in.close(); 1236 } catch (FileNotFoundException e){ 1237 e.printStackTrace(); 1238 } catch (RuntimeException e) { 1239 e.printStackTrace(); 1240 } catch (IOException e) { 1241 e.printStackTrace(); 1242 } 1243 if (p != null) { 1244 int sx = b.getInt("scrollX", 0); 1245 int sy = b.getInt("scrollY", 0); 1246 float scale = b.getFloat("scale", 1.0f); 1247 mDrawHistory = true; 1248 mHistoryPicture = p; 1249 mScrollX = sx; 1250 mScrollY = sy; 1251 mHistoryWidth = Math.round(p.getWidth() * scale); 1252 mHistoryHeight = Math.round(p.getHeight() * scale); 1253 // as getWidth() / getHeight() of the view are not 1254 // available yet, set up mActualScale, so that when 1255 // onSizeChanged() is called, the rest will be set 1256 // correctly 1257 mActualScale = scale; 1258 float lastScale = b.getFloat("lastScale", -1.0f); 1259 if (lastScale > 0) { 1260 mInZoomOverview = true; 1261 mLastScale = lastScale; 1262 } else { 1263 mInZoomOverview = false; 1264 } 1265 invalidate(); 1266 return true; 1267 } 1268 } 1269 return false; 1270 } 1271 1272 /** 1273 * Restore the state of this WebView from the given map used in 1274 * {@link android.app.Activity#onRestoreInstanceState}. This method should 1275 * be called to restore the state of the WebView before using the object. If 1276 * it is called after the WebView has had a chance to build state (load 1277 * pages, create a back/forward list, etc.) there may be undesirable 1278 * side-effects. Please note that this method no longer restores the 1279 * display data for this WebView. See {@link #savePicture} and {@link 1280 * #restorePicture} for saving and restoring the display data. 1281 * @param inState The incoming Bundle of state. 1282 * @return The restored back/forward list or null if restoreState failed. 1283 * @see #savePicture 1284 * @see #restorePicture 1285 */ 1286 public WebBackForwardList restoreState(Bundle inState) { 1287 WebBackForwardList returnList = null; 1288 if (inState == null) { 1289 return returnList; 1290 } 1291 if (inState.containsKey("index") && inState.containsKey("history")) { 1292 mCertificate = SslCertificate.restoreState( 1293 inState.getBundle("certificate")); 1294 1295 final WebBackForwardList list = mCallbackProxy.getBackForwardList(); 1296 final int index = inState.getInt("index"); 1297 // We can't use a clone of the list because we need to modify the 1298 // shared copy, so synchronize instead to prevent concurrent 1299 // modifications. 1300 synchronized (list) { 1301 final List<byte[]> history = 1302 (List<byte[]>) inState.getSerializable("history"); 1303 final int size = history.size(); 1304 // Check the index bounds so we don't crash in native code while 1305 // restoring the history index. 1306 if (index < 0 || index >= size) { 1307 return null; 1308 } 1309 for (int i = 0; i < size; i++) { 1310 byte[] data = history.remove(0); 1311 if (data == null) { 1312 // If we somehow have null data, we cannot reconstruct 1313 // the item and thus our history list cannot be rebuilt. 1314 return null; 1315 } 1316 WebHistoryItem item = new WebHistoryItem(data); 1317 list.addHistoryItem(item); 1318 } 1319 // Grab the most recent copy to return to the caller. 1320 returnList = copyBackForwardList(); 1321 // Update the copy to have the correct index. 1322 returnList.setCurrentIndex(index); 1323 } 1324 // Remove all pending messages because we are restoring previous 1325 // state. 1326 mWebViewCore.removeMessages(); 1327 // Send a restore state message. 1328 mWebViewCore.sendMessage(EventHub.RESTORE_STATE, index); 1329 } 1330 return returnList; 1331 } 1332 1333 /** 1334 * Load the given url. 1335 * @param url The url of the resource to load. 1336 */ 1337 public void loadUrl(String url) { 1338 if (url == null) { 1339 return; 1340 } 1341 switchOutDrawHistory(); 1342 mWebViewCore.sendMessage(EventHub.LOAD_URL, url); 1343 clearTextEntry(); 1344 } 1345 1346 /** 1347 * Load the url with postData using "POST" method into the WebView. If url 1348 * is not a network url, it will be loaded with {link 1349 * {@link #loadUrl(String)} instead. 1350 * 1351 * @param url The url of the resource to load. 1352 * @param postData The data will be passed to "POST" request. 1353 */ 1354 public void postUrl(String url, byte[] postData) { 1355 if (URLUtil.isNetworkUrl(url)) { 1356 switchOutDrawHistory(); 1357 WebViewCore.PostUrlData arg = new WebViewCore.PostUrlData(); 1358 arg.mUrl = url; 1359 arg.mPostData = postData; 1360 mWebViewCore.sendMessage(EventHub.POST_URL, arg); 1361 clearTextEntry(); 1362 } else { 1363 loadUrl(url); 1364 } 1365 } 1366 1367 /** 1368 * Load the given data into the WebView. This will load the data into 1369 * WebView using the data: scheme. Content loaded through this mechanism 1370 * does not have the ability to load content from the network. 1371 * @param data A String of data in the given encoding. 1372 * @param mimeType The MIMEType of the data. i.e. text/html, image/jpeg 1373 * @param encoding The encoding of the data. i.e. utf-8, base64 1374 */ 1375 public void loadData(String data, String mimeType, String encoding) { 1376 loadUrl("data:" + mimeType + ";" + encoding + "," + data); 1377 } 1378 1379 /** 1380 * Load the given data into the WebView, use the provided URL as the base 1381 * URL for the content. The base URL is the URL that represents the page 1382 * that is loaded through this interface. As such, it is used for the 1383 * history entry and to resolve any relative URLs. The failUrl is used if 1384 * browser fails to load the data provided. If it is empty or null, and the 1385 * load fails, then no history entry is created. 1386 * <p> 1387 * Note for post 1.0. Due to the change in the WebKit, the access to asset 1388 * files through "file:///android_asset/" for the sub resources is more 1389 * restricted. If you provide null or empty string as baseUrl, you won't be 1390 * able to access asset files. If the baseUrl is anything other than 1391 * http(s)/ftp(s)/about/javascript as scheme, you can access asset files for 1392 * sub resources. 1393 * 1394 * @param baseUrl Url to resolve relative paths with, if null defaults to 1395 * "about:blank" 1396 * @param data A String of data in the given encoding. 1397 * @param mimeType The MIMEType of the data. i.e. text/html. If null, 1398 * defaults to "text/html" 1399 * @param encoding The encoding of the data. i.e. utf-8, us-ascii 1400 * @param failUrl URL to use if the content fails to load or null. 1401 */ 1402 public void loadDataWithBaseURL(String baseUrl, String data, 1403 String mimeType, String encoding, String failUrl) { 1404 1405 if (baseUrl != null && baseUrl.toLowerCase().startsWith("data:")) { 1406 loadData(data, mimeType, encoding); 1407 return; 1408 } 1409 switchOutDrawHistory(); 1410 WebViewCore.BaseUrlData arg = new WebViewCore.BaseUrlData(); 1411 arg.mBaseUrl = baseUrl; 1412 arg.mData = data; 1413 arg.mMimeType = mimeType; 1414 arg.mEncoding = encoding; 1415 arg.mFailUrl = failUrl; 1416 mWebViewCore.sendMessage(EventHub.LOAD_DATA, arg); 1417 clearTextEntry(); 1418 } 1419 1420 /** 1421 * Stop the current load. 1422 */ 1423 public void stopLoading() { 1424 // TODO: should we clear all the messages in the queue before sending 1425 // STOP_LOADING? 1426 switchOutDrawHistory(); 1427 mWebViewCore.sendMessage(EventHub.STOP_LOADING); 1428 } 1429 1430 /** 1431 * Reload the current url. 1432 */ 1433 public void reload() { 1434 clearTextEntry(); 1435 switchOutDrawHistory(); 1436 mWebViewCore.sendMessage(EventHub.RELOAD); 1437 } 1438 1439 /** 1440 * Return true if this WebView has a back history item. 1441 * @return True iff this WebView has a back history item. 1442 */ 1443 public boolean canGoBack() { 1444 WebBackForwardList l = mCallbackProxy.getBackForwardList(); 1445 synchronized (l) { 1446 if (l.getClearPending()) { 1447 return false; 1448 } else { 1449 return l.getCurrentIndex() > 0; 1450 } 1451 } 1452 } 1453 1454 /** 1455 * Go back in the history of this WebView. 1456 */ 1457 public void goBack() { 1458 goBackOrForward(-1); 1459 } 1460 1461 /** 1462 * Return true if this WebView has a forward history item. 1463 * @return True iff this Webview has a forward history item. 1464 */ 1465 public boolean canGoForward() { 1466 WebBackForwardList l = mCallbackProxy.getBackForwardList(); 1467 synchronized (l) { 1468 if (l.getClearPending()) { 1469 return false; 1470 } else { 1471 return l.getCurrentIndex() < l.getSize() - 1; 1472 } 1473 } 1474 } 1475 1476 /** 1477 * Go forward in the history of this WebView. 1478 */ 1479 public void goForward() { 1480 goBackOrForward(1); 1481 } 1482 1483 /** 1484 * Return true if the page can go back or forward the given 1485 * number of steps. 1486 * @param steps The negative or positive number of steps to move the 1487 * history. 1488 */ 1489 public boolean canGoBackOrForward(int steps) { 1490 WebBackForwardList l = mCallbackProxy.getBackForwardList(); 1491 synchronized (l) { 1492 if (l.getClearPending()) { 1493 return false; 1494 } else { 1495 int newIndex = l.getCurrentIndex() + steps; 1496 return newIndex >= 0 && newIndex < l.getSize(); 1497 } 1498 } 1499 } 1500 1501 /** 1502 * Go to the history item that is the number of steps away from 1503 * the current item. Steps is negative if backward and positive 1504 * if forward. 1505 * @param steps The number of steps to take back or forward in the back 1506 * forward list. 1507 */ 1508 public void goBackOrForward(int steps) { 1509 goBackOrForward(steps, false); 1510 } 1511 1512 private void goBackOrForward(int steps, boolean ignoreSnapshot) { 1513 // every time we go back or forward, we want to reset the 1514 // WebView certificate: 1515 // if the new site is secure, we will reload it and get a 1516 // new certificate set; 1517 // if the new site is not secure, the certificate must be 1518 // null, and that will be the case 1519 mCertificate = null; 1520 if (steps != 0) { 1521 clearTextEntry(); 1522 mWebViewCore.sendMessage(EventHub.GO_BACK_FORWARD, steps, 1523 ignoreSnapshot ? 1 : 0); 1524 } 1525 } 1526 1527 private boolean extendScroll(int y) { 1528 int finalY = mScroller.getFinalY(); 1529 int newY = pinLocY(finalY + y); 1530 if (newY == finalY) return false; 1531 mScroller.setFinalY(newY); 1532 mScroller.extendDuration(computeDuration(0, y)); 1533 return true; 1534 } 1535 1536 /** 1537 * Scroll the contents of the view up by half the view size 1538 * @param top true to jump to the top of the page 1539 * @return true if the page was scrolled 1540 */ 1541 public boolean pageUp(boolean top) { 1542 if (mNativeClass == 0) { 1543 return false; 1544 } 1545 nativeClearCursor(); // start next trackball movement from page edge 1546 if (top) { 1547 // go to the top of the document 1548 return pinScrollTo(mScrollX, 0, true, 0); 1549 } 1550 // Page up 1551 int h = getHeight(); 1552 int y; 1553 if (h > 2 * PAGE_SCROLL_OVERLAP) { 1554 y = -h + PAGE_SCROLL_OVERLAP; 1555 } else { 1556 y = -h / 2; 1557 } 1558 mUserScroll = true; 1559 return mScroller.isFinished() ? pinScrollBy(0, y, true, 0) 1560 : extendScroll(y); 1561 } 1562 1563 /** 1564 * Scroll the contents of the view down by half the page size 1565 * @param bottom true to jump to bottom of page 1566 * @return true if the page was scrolled 1567 */ 1568 public boolean pageDown(boolean bottom) { 1569 if (mNativeClass == 0) { 1570 return false; 1571 } 1572 nativeClearCursor(); // start next trackball movement from page edge 1573 if (bottom) { 1574 return pinScrollTo(mScrollX, computeVerticalScrollRange(), true, 0); 1575 } 1576 // Page down. 1577 int h = getHeight(); 1578 int y; 1579 if (h > 2 * PAGE_SCROLL_OVERLAP) { 1580 y = h - PAGE_SCROLL_OVERLAP; 1581 } else { 1582 y = h / 2; 1583 } 1584 mUserScroll = true; 1585 return mScroller.isFinished() ? pinScrollBy(0, y, true, 0) 1586 : extendScroll(y); 1587 } 1588 1589 /** 1590 * Clear the view so that onDraw() will draw nothing but white background, 1591 * and onMeasure() will return 0 if MeasureSpec is not MeasureSpec.EXACTLY 1592 */ 1593 public void clearView() { 1594 mContentWidth = 0; 1595 mContentHeight = 0; 1596 mWebViewCore.sendMessage(EventHub.CLEAR_CONTENT); 1597 } 1598 1599 /** 1600 * Return a new picture that captures the current display of the webview. 1601 * This is a copy of the display, and will be unaffected if the webview 1602 * later loads a different URL. 1603 * 1604 * @return a picture containing the current contents of the view. Note this 1605 * picture is of the entire document, and is not restricted to the 1606 * bounds of the view. 1607 */ 1608 public Picture capturePicture() { 1609 if (null == mWebViewCore) return null; // check for out of memory tab 1610 return mWebViewCore.copyContentPicture(); 1611 } 1612 1613 /** 1614 * Return true if the browser is displaying a TextView for text input. 1615 */ 1616 private boolean inEditingMode() { 1617 return mWebTextView != null && mWebTextView.getParent() != null 1618 && mWebTextView.hasFocus(); 1619 } 1620 1621 private void clearTextEntry() { 1622 if (inEditingMode()) { 1623 mWebTextView.remove(); 1624 } 1625 } 1626 1627 /** 1628 * Return the current scale of the WebView 1629 * @return The current scale. 1630 */ 1631 public float getScale() { 1632 return mActualScale; 1633 } 1634 1635 /** 1636 * Set the initial scale for the WebView. 0 means default. If 1637 * {@link WebSettings#getUseWideViewPort()} is true, it zooms out all the 1638 * way. Otherwise it starts with 100%. If initial scale is greater than 0, 1639 * WebView starts will this value as initial scale. 1640 * 1641 * @param scaleInPercent The initial scale in percent. 1642 */ 1643 public void setInitialScale(int scaleInPercent) { 1644 mInitialScaleInPercent = scaleInPercent; 1645 } 1646 1647 /** 1648 * Invoke the graphical zoom picker widget for this WebView. This will 1649 * result in the zoom widget appearing on the screen to control the zoom 1650 * level of this WebView. 1651 */ 1652 public void invokeZoomPicker() { 1653 if (!getSettings().supportZoom()) { 1654 Log.w(LOGTAG, "This WebView doesn't support zoom."); 1655 return; 1656 } 1657 clearTextEntry(); 1658 if (getSettings().getBuiltInZoomControls()) { 1659 mZoomButtonsController.setVisible(true); 1660 } else { 1661 mPrivateHandler.removeCallbacks(mZoomControlRunnable); 1662 mPrivateHandler.postDelayed(mZoomControlRunnable, 1663 ZOOM_CONTROLS_TIMEOUT); 1664 } 1665 } 1666 1667 /** 1668 * Return a HitTestResult based on the current cursor node. If a HTML::a tag 1669 * is found and the anchor has a non-javascript url, the HitTestResult type 1670 * is set to SRC_ANCHOR_TYPE and the url is set in the "extra" field. If the 1671 * anchor does not have a url or if it is a javascript url, the type will 1672 * be UNKNOWN_TYPE and the url has to be retrieved through 1673 * {@link #requestFocusNodeHref} asynchronously. If a HTML::img tag is 1674 * found, the HitTestResult type is set to IMAGE_TYPE and the url is set in 1675 * the "extra" field. A type of 1676 * SRC_IMAGE_ANCHOR_TYPE indicates an anchor with a url that has an image as 1677 * a child node. If a phone number is found, the HitTestResult type is set 1678 * to PHONE_TYPE and the phone number is set in the "extra" field of 1679 * HitTestResult. If a map address is found, the HitTestResult type is set 1680 * to GEO_TYPE and the address is set in the "extra" field of HitTestResult. 1681 * If an email address is found, the HitTestResult type is set to EMAIL_TYPE 1682 * and the email is set in the "extra" field of HitTestResult. Otherwise, 1683 * HitTestResult type is set to UNKNOWN_TYPE. 1684 */ 1685 public HitTestResult getHitTestResult() { 1686 if (mNativeClass == 0) { 1687 return null; 1688 } 1689 1690 HitTestResult result = new HitTestResult(); 1691 if (nativeHasCursorNode()) { 1692 if (nativeCursorIsTextInput()) { 1693 result.setType(HitTestResult.EDIT_TEXT_TYPE); 1694 } else { 1695 String text = nativeCursorText(); 1696 if (text != null) { 1697 if (text.startsWith(SCHEME_TEL)) { 1698 result.setType(HitTestResult.PHONE_TYPE); 1699 result.setExtra(text.substring(SCHEME_TEL.length())); 1700 } else if (text.startsWith(SCHEME_MAILTO)) { 1701 result.setType(HitTestResult.EMAIL_TYPE); 1702 result.setExtra(text.substring(SCHEME_MAILTO.length())); 1703 } else if (text.startsWith(SCHEME_GEO)) { 1704 result.setType(HitTestResult.GEO_TYPE); 1705 result.setExtra(URLDecoder.decode(text 1706 .substring(SCHEME_GEO.length()))); 1707 } else if (nativeCursorIsAnchor()) { 1708 result.setType(HitTestResult.SRC_ANCHOR_TYPE); 1709 result.setExtra(text); 1710 } 1711 } 1712 } 1713 } 1714 int type = result.getType(); 1715 if (type == HitTestResult.UNKNOWN_TYPE 1716 || type == HitTestResult.SRC_ANCHOR_TYPE) { 1717 // Now check to see if it is an image. 1718 int contentX = viewToContentX((int) mLastTouchX + mScrollX); 1719 int contentY = viewToContentY((int) mLastTouchY + mScrollY); 1720 String text = nativeImageURI(contentX, contentY); 1721 if (text != null) { 1722 result.setType(type == HitTestResult.UNKNOWN_TYPE ? 1723 HitTestResult.IMAGE_TYPE : 1724 HitTestResult.SRC_IMAGE_ANCHOR_TYPE); 1725 result.setExtra(text); 1726 } 1727 } 1728 return result; 1729 } 1730 1731 // Called by JNI when the DOM has changed the focus. Clear the focus so 1732 // that new keys will go to the newly focused field 1733 private void domChangedFocus() { 1734 if (inEditingMode()) { 1735 mPrivateHandler.obtainMessage(DOM_FOCUS_CHANGED).sendToTarget(); 1736 } 1737 } 1738 /** 1739 * Request the href of an anchor element due to getFocusNodePath returning 1740 * "href." If hrefMsg is null, this method returns immediately and does not 1741 * dispatch hrefMsg to its target. 1742 * 1743 * @param hrefMsg This message will be dispatched with the result of the 1744 * request as the data member with "url" as key. The result can 1745 * be null. 1746 */ 1747 // FIXME: API change required to change the name of this function. We now 1748 // look at the cursor node, and not the focus node. Also, what is 1749 // getFocusNodePath? 1750 public void requestFocusNodeHref(Message hrefMsg) { 1751 if (hrefMsg == null || mNativeClass == 0) { 1752 return; 1753 } 1754 if (nativeCursorIsAnchor()) { 1755 mWebViewCore.sendMessage(EventHub.REQUEST_CURSOR_HREF, 1756 nativeCursorFramePointer(), nativeCursorNodePointer(), 1757 hrefMsg); 1758 } 1759 } 1760 1761 /** 1762 * Request the url of the image last touched by the user. msg will be sent 1763 * to its target with a String representing the url as its object. 1764 * 1765 * @param msg This message will be dispatched with the result of the request 1766 * as the data member with "url" as key. The result can be null. 1767 */ 1768 public void requestImageRef(Message msg) { 1769 if (0 == mNativeClass) return; // client isn't initialized 1770 int contentX = viewToContentX((int) mLastTouchX + mScrollX); 1771 int contentY = viewToContentY((int) mLastTouchY + mScrollY); 1772 String ref = nativeImageURI(contentX, contentY); 1773 Bundle data = msg.getData(); 1774 data.putString("url", ref); 1775 msg.setData(data); 1776 msg.sendToTarget(); 1777 } 1778 1779 private static int pinLoc(int x, int viewMax, int docMax) { 1780// Log.d(LOGTAG, "-- pinLoc " + x + " " + viewMax + " " + docMax); 1781 if (docMax < viewMax) { // the doc has room on the sides for "blank" 1782 // pin the short document to the top/left of the screen 1783 x = 0; 1784// Log.d(LOGTAG, "--- center " + x); 1785 } else if (x < 0) { 1786 x = 0; 1787// Log.d(LOGTAG, "--- zero"); 1788 } else if (x + viewMax > docMax) { 1789 x = docMax - viewMax; 1790// Log.d(LOGTAG, "--- pin " + x); 1791 } 1792 return x; 1793 } 1794 1795 // Expects x in view coordinates 1796 private int pinLocX(int x) { 1797 return pinLoc(x, getViewWidth(), computeHorizontalScrollRange()); 1798 } 1799 1800 // Expects y in view coordinates 1801 private int pinLocY(int y) { 1802 int titleH = getTitleHeight(); 1803 // if the titlebar is still visible, just pin against 0 1804 if (y <= titleH) { 1805 return Math.max(y, 0); 1806 } 1807 // convert to 0-based coordinate (subtract the title height) 1808 // pin(), and then add the title height back in 1809 return pinLoc(y - titleH, getViewHeight(), 1810 computeVerticalScrollRange()) + titleH; 1811 } 1812 1813 /** 1814 * A title bar which is embedded in this WebView, and scrolls along with it 1815 * vertically, but not horizontally. 1816 */ 1817 private View mTitleBar; 1818 1819 /** 1820 * Since we draw the title bar ourselves, we removed the shadow from the 1821 * browser's activity. We do want a shadow at the bottom of the title bar, 1822 * or at the top of the screen if the title bar is not visible. This 1823 * drawable serves that purpose. 1824 */ 1825 private Drawable mTitleShadow; 1826 1827 /** 1828 * Add or remove a title bar to be embedded into the WebView, and scroll 1829 * along with it vertically, while remaining in view horizontally. Pass 1830 * null to remove the title bar from the WebView, and return to drawing 1831 * the WebView normally without translating to account for the title bar. 1832 * @hide 1833 */ 1834 public void setEmbeddedTitleBar(View v) { 1835 if (mTitleBar == v) return; 1836 if (mTitleBar != null) { 1837 removeView(mTitleBar); 1838 } 1839 if (null != v) { 1840 addView(v, new AbsoluteLayout.LayoutParams( 1841 ViewGroup.LayoutParams.FILL_PARENT, 1842 ViewGroup.LayoutParams.WRAP_CONTENT, 0, 0)); 1843 if (mTitleShadow == null) { 1844 mTitleShadow = (Drawable) mContext.getResources().getDrawable( 1845 com.android.internal.R.drawable.title_bar_shadow); 1846 } 1847 } 1848 mTitleBar = v; 1849 } 1850 1851 /** 1852 * Given a distance in view space, convert it to content space. Note: this 1853 * does not reflect translation, just scaling, so this should not be called 1854 * with coordinates, but should be called for dimensions like width or 1855 * height. 1856 */ 1857 private int viewToContentDimension(int d) { 1858 return Math.round(d * mInvActualScale); 1859 } 1860 1861 /** 1862 * Given an x coordinate in view space, convert it to content space. Also 1863 * may be used for absolute heights (such as for the WebTextView's 1864 * textSize, which is unaffected by the height of the title bar). 1865 */ 1866 /*package*/ int viewToContentX(int x) { 1867 return viewToContentDimension(x); 1868 } 1869 1870 /** 1871 * Given a y coordinate in view space, convert it to content space. 1872 * Takes into account the height of the title bar if there is one 1873 * embedded into the WebView. 1874 */ 1875 /*package*/ int viewToContentY(int y) { 1876 return viewToContentDimension(y - getTitleHeight()); 1877 } 1878 1879 /** 1880 * Given a distance in content space, convert it to view space. Note: this 1881 * does not reflect translation, just scaling, so this should not be called 1882 * with coordinates, but should be called for dimensions like width or 1883 * height. 1884 */ 1885 /*package*/ int contentToViewDimension(int d) { 1886 return Math.round(d * mActualScale); 1887 } 1888 1889 /** 1890 * Given an x coordinate in content space, convert it to view 1891 * space. 1892 */ 1893 /*package*/ int contentToViewX(int x) { 1894 return contentToViewDimension(x); 1895 } 1896 1897 /** 1898 * Given a y coordinate in content space, convert it to view 1899 * space. Takes into account the height of the title bar. 1900 */ 1901 /*package*/ int contentToViewY(int y) { 1902 return contentToViewDimension(y) + getTitleHeight(); 1903 } 1904 1905 private Rect contentToViewRect(Rect x) { 1906 return new Rect(contentToViewX(x.left), contentToViewY(x.top), 1907 contentToViewX(x.right), contentToViewY(x.bottom)); 1908 } 1909 1910 /* To invalidate a rectangle in content coordinates, we need to transform 1911 the rect into view coordinates, so we can then call invalidate(...). 1912 1913 Normally, we would just call contentToView[XY](...), which eventually 1914 calls Math.round(coordinate * mActualScale). However, for invalidates, 1915 we need to account for the slop that occurs with antialiasing. To 1916 address that, we are a little more liberal in the size of the rect that 1917 we invalidate. 1918 1919 This liberal calculation calls floor() for the top/left, and ceil() for 1920 the bottom/right coordinates. This catches the possible extra pixels of 1921 antialiasing that we might have missed with just round(). 1922 */ 1923 1924 // Called by JNI to invalidate the View, given rectangle coordinates in 1925 // content space 1926 private void viewInvalidate(int l, int t, int r, int b) { 1927 final float scale = mActualScale; 1928 final int dy = getTitleHeight(); 1929 invalidate((int)Math.floor(l * scale), 1930 (int)Math.floor(t * scale) + dy, 1931 (int)Math.ceil(r * scale), 1932 (int)Math.ceil(b * scale) + dy); 1933 } 1934 1935 // Called by JNI to invalidate the View after a delay, given rectangle 1936 // coordinates in content space 1937 private void viewInvalidateDelayed(long delay, int l, int t, int r, int b) { 1938 final float scale = mActualScale; 1939 final int dy = getTitleHeight(); 1940 postInvalidateDelayed(delay, 1941 (int)Math.floor(l * scale), 1942 (int)Math.floor(t * scale) + dy, 1943 (int)Math.ceil(r * scale), 1944 (int)Math.ceil(b * scale) + dy); 1945 } 1946 1947 private void invalidateContentRect(Rect r) { 1948 viewInvalidate(r.left, r.top, r.right, r.bottom); 1949 } 1950 1951 // stop the scroll animation, and don't let a subsequent fling add 1952 // to the existing velocity 1953 private void abortAnimation() { 1954 mScroller.abortAnimation(); 1955 mLastVelocity = 0; 1956 } 1957 1958 /* call from webcoreview.draw(), so we're still executing in the UI thread 1959 */ 1960 private void recordNewContentSize(int w, int h, boolean updateLayout) { 1961 1962 // premature data from webkit, ignore 1963 if ((w | h) == 0) { 1964 return; 1965 } 1966 1967 // don't abort a scroll animation if we didn't change anything 1968 if (mContentWidth != w || mContentHeight != h) { 1969 // record new dimensions 1970 mContentWidth = w; 1971 mContentHeight = h; 1972 // If history Picture is drawn, don't update scroll. They will be 1973 // updated when we get out of that mode. 1974 if (!mDrawHistory) { 1975 // repin our scroll, taking into account the new content size 1976 int oldX = mScrollX; 1977 int oldY = mScrollY; 1978 mScrollX = pinLocX(mScrollX); 1979 mScrollY = pinLocY(mScrollY); 1980 if (oldX != mScrollX || oldY != mScrollY) { 1981 sendOurVisibleRect(); 1982 } 1983 if (!mScroller.isFinished()) { 1984 // We are in the middle of a scroll. Repin the final scroll 1985 // position. 1986 mScroller.setFinalX(pinLocX(mScroller.getFinalX())); 1987 mScroller.setFinalY(pinLocY(mScroller.getFinalY())); 1988 } 1989 } 1990 } 1991 contentSizeChanged(updateLayout); 1992 } 1993 1994 private void setNewZoomScale(float scale, boolean force) { 1995 if (scale < mMinZoomScale) { 1996 scale = mMinZoomScale; 1997 } else if (scale > mMaxZoomScale) { 1998 scale = mMaxZoomScale; 1999 } 2000 if (scale != mActualScale || force) { 2001 if (mDrawHistory) { 2002 // If history Picture is drawn, don't update scroll. They will 2003 // be updated when we get out of that mode. 2004 if (scale != mActualScale && !mPreviewZoomOnly) { 2005 mCallbackProxy.onScaleChanged(mActualScale, scale); 2006 } 2007 mActualScale = scale; 2008 mInvActualScale = 1 / scale; 2009 if (!mPreviewZoomOnly) { 2010 sendViewSizeZoom(); 2011 } 2012 } else { 2013 // update our scroll so we don't appear to jump 2014 // i.e. keep the center of the doc in the center of the view 2015 2016 int oldX = mScrollX; 2017 int oldY = mScrollY; 2018 float ratio = scale * mInvActualScale; // old inverse 2019 float sx = ratio * oldX + (ratio - 1) * mZoomCenterX; 2020 float sy = ratio * oldY + (ratio - 1) 2021 * (mZoomCenterY - getTitleHeight()); 2022 2023 // now update our new scale and inverse 2024 if (scale != mActualScale && !mPreviewZoomOnly) { 2025 mCallbackProxy.onScaleChanged(mActualScale, scale); 2026 } 2027 mActualScale = scale; 2028 mInvActualScale = 1 / scale; 2029 2030 // Scale all the child views 2031 mViewManager.scaleAll(); 2032 2033 // as we don't have animation for scaling, don't do animation 2034 // for scrolling, as it causes weird intermediate state 2035 // pinScrollTo(Math.round(sx), Math.round(sy)); 2036 mScrollX = pinLocX(Math.round(sx)); 2037 mScrollY = pinLocY(Math.round(sy)); 2038 2039 if (!mPreviewZoomOnly) { 2040 sendViewSizeZoom(); 2041 sendOurVisibleRect(); 2042 } 2043 } 2044 } 2045 } 2046 2047 // Used to avoid sending many visible rect messages. 2048 private Rect mLastVisibleRectSent; 2049 private Rect mLastGlobalRect; 2050 2051 private Rect sendOurVisibleRect() { 2052 Rect rect = new Rect(); 2053 calcOurContentVisibleRect(rect); 2054 // Rect.equals() checks for null input. 2055 if (!rect.equals(mLastVisibleRectSent)) { 2056 Point pos = new Point(rect.left, rect.top); 2057 mWebViewCore.sendMessage(EventHub.SET_SCROLL_OFFSET, 2058 nativeMoveGeneration(), 0, pos); 2059 mLastVisibleRectSent = rect; 2060 } 2061 Rect globalRect = new Rect(); 2062 if (getGlobalVisibleRect(globalRect) 2063 && !globalRect.equals(mLastGlobalRect)) { 2064 if (DebugFlags.WEB_VIEW) { 2065 Log.v(LOGTAG, "sendOurVisibleRect=(" + globalRect.left + "," 2066 + globalRect.top + ",r=" + globalRect.right + ",b=" 2067 + globalRect.bottom); 2068 } 2069 // TODO: the global offset is only used by windowRect() 2070 // in ChromeClientAndroid ; other clients such as touch 2071 // and mouse events could return view + screen relative points. 2072 mWebViewCore.sendMessage(EventHub.SET_GLOBAL_BOUNDS, globalRect); 2073 mLastGlobalRect = globalRect; 2074 } 2075 return rect; 2076 } 2077 2078 // Sets r to be the visible rectangle of our webview in view coordinates 2079 private void calcOurVisibleRect(Rect r) { 2080 Point p = new Point(); 2081 getGlobalVisibleRect(r, p); 2082 r.offset(-p.x, -p.y); 2083 if (mFindIsUp) { 2084 r.bottom -= mFindHeight; 2085 } 2086 } 2087 2088 // Sets r to be our visible rectangle in content coordinates 2089 private void calcOurContentVisibleRect(Rect r) { 2090 calcOurVisibleRect(r); 2091 r.left = viewToContentX(r.left); 2092 // viewToContentY will remove the total height of the title bar. Add 2093 // the visible height back in to account for the fact that if the title 2094 // bar is partially visible, the part of the visible rect which is 2095 // displaying our content is displaced by that amount. 2096 r.top = viewToContentY(r.top + getVisibleTitleHeight()); 2097 r.right = viewToContentX(r.right); 2098 r.bottom = viewToContentY(r.bottom); 2099 } 2100 2101 static class ViewSizeData { 2102 int mWidth; 2103 int mHeight; 2104 int mTextWrapWidth; 2105 float mScale; 2106 boolean mIgnoreHeight; 2107 } 2108 2109 /** 2110 * Compute unzoomed width and height, and if they differ from the last 2111 * values we sent, send them to webkit (to be used has new viewport) 2112 * 2113 * @return true if new values were sent 2114 */ 2115 private boolean sendViewSizeZoom() { 2116 int viewWidth = getViewWidth(); 2117 int newWidth = Math.round(viewWidth * mInvActualScale); 2118 int newHeight = Math.round(getViewHeight() * mInvActualScale); 2119 /* 2120 * Because the native side may have already done a layout before the 2121 * View system was able to measure us, we have to send a height of 0 to 2122 * remove excess whitespace when we grow our width. This will trigger a 2123 * layout and a change in content size. This content size change will 2124 * mean that contentSizeChanged will either call this method directly or 2125 * indirectly from onSizeChanged. 2126 */ 2127 if (newWidth > mLastWidthSent && mWrapContent) { 2128 newHeight = 0; 2129 } 2130 // Avoid sending another message if the dimensions have not changed. 2131 if (newWidth != mLastWidthSent || newHeight != mLastHeightSent) { 2132 ViewSizeData data = new ViewSizeData(); 2133 data.mWidth = newWidth; 2134 data.mHeight = newHeight; 2135 // while in zoom overview mode, the text are wrapped to the screen 2136 // width matching mLastScale. So that we don't trigger re-flow while 2137 // toggling between overview mode and normal mode. 2138 data.mTextWrapWidth = mInZoomOverview ? Math.round(viewWidth 2139 / mLastScale) : newWidth; 2140 data.mScale = mActualScale; 2141 data.mIgnoreHeight = mZoomScale != 0 && !mHeightCanMeasure; 2142 mWebViewCore.sendMessage(EventHub.VIEW_SIZE_CHANGED, data); 2143 mLastWidthSent = newWidth; 2144 mLastHeightSent = newHeight; 2145 return true; 2146 } 2147 return false; 2148 } 2149 2150 @Override 2151 protected int computeHorizontalScrollRange() { 2152 if (mDrawHistory) { 2153 return mHistoryWidth; 2154 } else { 2155 // to avoid rounding error caused unnecessary scrollbar, use floor 2156 return (int) Math.floor(mContentWidth * mActualScale); 2157 } 2158 } 2159 2160 @Override 2161 protected int computeVerticalScrollRange() { 2162 if (mDrawHistory) { 2163 return mHistoryHeight; 2164 } else { 2165 // to avoid rounding error caused unnecessary scrollbar, use floor 2166 return (int) Math.floor(mContentHeight * mActualScale); 2167 } 2168 } 2169 2170 @Override 2171 protected int computeVerticalScrollOffset() { 2172 return Math.max(mScrollY - getTitleHeight(), 0); 2173 } 2174 2175 @Override 2176 protected int computeVerticalScrollExtent() { 2177 return getViewHeight(); 2178 } 2179 2180 /** @hide */ 2181 @Override 2182 protected void onDrawVerticalScrollBar(Canvas canvas, 2183 Drawable scrollBar, 2184 int l, int t, int r, int b) { 2185 scrollBar.setBounds(l, t + getVisibleTitleHeight(), r, b); 2186 scrollBar.draw(canvas); 2187 } 2188 2189 /** 2190 * Get the url for the current page. This is not always the same as the url 2191 * passed to WebViewClient.onPageStarted because although the load for 2192 * that url has begun, the current page may not have changed. 2193 * @return The url for the current page. 2194 */ 2195 public String getUrl() { 2196 WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem(); 2197 return h != null ? h.getUrl() : null; 2198 } 2199 2200 /** 2201 * Get the original url for the current page. This is not always the same 2202 * as the url passed to WebViewClient.onPageStarted because although the 2203 * load for that url has begun, the current page may not have changed. 2204 * Also, there may have been redirects resulting in a different url to that 2205 * originally requested. 2206 * @return The url that was originally requested for the current page. 2207 */ 2208 public String getOriginalUrl() { 2209 WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem(); 2210 return h != null ? h.getOriginalUrl() : null; 2211 } 2212 2213 /** 2214 * Get the title for the current page. This is the title of the current page 2215 * until WebViewClient.onReceivedTitle is called. 2216 * @return The title for the current page. 2217 */ 2218 public String getTitle() { 2219 WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem(); 2220 return h != null ? h.getTitle() : null; 2221 } 2222 2223 /** 2224 * Get the favicon for the current page. This is the favicon of the current 2225 * page until WebViewClient.onReceivedIcon is called. 2226 * @return The favicon for the current page. 2227 */ 2228 public Bitmap getFavicon() { 2229 WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem(); 2230 return h != null ? h.getFavicon() : null; 2231 } 2232 2233 /** 2234 * Get the touch icon url for the apple-touch-icon <link> element. 2235 * @hide 2236 */ 2237 public String getTouchIconUrl() { 2238 WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem(); 2239 return h != null ? h.getTouchIconUrl() : null; 2240 } 2241 2242 /** 2243 * Get the progress for the current page. 2244 * @return The progress for the current page between 0 and 100. 2245 */ 2246 public int getProgress() { 2247 return mCallbackProxy.getProgress(); 2248 } 2249 2250 /** 2251 * @return the height of the HTML content. 2252 */ 2253 public int getContentHeight() { 2254 return mContentHeight; 2255 } 2256 2257 /** 2258 * @return the width of the HTML content. 2259 * @hide 2260 */ 2261 public int getContentWidth() { 2262 return mContentWidth; 2263 } 2264 2265 /** 2266 * Pause all layout, parsing, and javascript timers for all webviews. This 2267 * is a global requests, not restricted to just this webview. This can be 2268 * useful if the application has been paused. 2269 */ 2270 public void pauseTimers() { 2271 mWebViewCore.sendMessage(EventHub.PAUSE_TIMERS); 2272 } 2273 2274 /** 2275 * Resume all layout, parsing, and javascript timers for all webviews. 2276 * This will resume dispatching all timers. 2277 */ 2278 public void resumeTimers() { 2279 mWebViewCore.sendMessage(EventHub.RESUME_TIMERS); 2280 } 2281 2282 /** 2283 * Call this to pause any extra processing associated with this view and 2284 * its associated DOM/plugins/javascript/etc. For example, if the view is 2285 * taken offscreen, this could be called to reduce unnecessary CPU and/or 2286 * network traffic. When the view is again "active", call onResume(). 2287 * 2288 * Note that this differs from pauseTimers(), which affects all views/DOMs 2289 * @hide 2290 */ 2291 public void onPause() { 2292 if (!mIsPaused) { 2293 mIsPaused = true; 2294 mWebViewCore.sendMessage(EventHub.ON_PAUSE); 2295 } 2296 } 2297 2298 /** 2299 * Call this to balanace a previous call to onPause() 2300 * @hide 2301 */ 2302 public void onResume() { 2303 if (mIsPaused) { 2304 mIsPaused = false; 2305 mWebViewCore.sendMessage(EventHub.ON_RESUME); 2306 } 2307 } 2308 2309 /** 2310 * Returns true if the view is paused, meaning onPause() was called. Calling 2311 * onResume() sets the paused state back to false. 2312 * @hide 2313 */ 2314 public boolean isPaused() { 2315 return mIsPaused; 2316 } 2317 2318 /** 2319 * Call this to inform the view that memory is low so that it can 2320 * free any available memory. 2321 */ 2322 public void freeMemory() { 2323 mWebViewCore.sendMessage(EventHub.FREE_MEMORY); 2324 } 2325 2326 /** 2327 * Clear the resource cache. Note that the cache is per-application, so 2328 * this will clear the cache for all WebViews used. 2329 * 2330 * @param includeDiskFiles If false, only the RAM cache is cleared. 2331 */ 2332 public void clearCache(boolean includeDiskFiles) { 2333 // Note: this really needs to be a static method as it clears cache for all 2334 // WebView. But we need mWebViewCore to send message to WebCore thread, so 2335 // we can't make this static. 2336 mWebViewCore.sendMessage(EventHub.CLEAR_CACHE, 2337 includeDiskFiles ? 1 : 0, 0); 2338 } 2339 2340 /** 2341 * Make sure that clearing the form data removes the adapter from the 2342 * currently focused textfield if there is one. 2343 */ 2344 public void clearFormData() { 2345 if (inEditingMode()) { 2346 AutoCompleteAdapter adapter = null; 2347 mWebTextView.setAdapterCustom(adapter); 2348 } 2349 } 2350 2351 /** 2352 * Tell the WebView to clear its internal back/forward list. 2353 */ 2354 public void clearHistory() { 2355 mCallbackProxy.getBackForwardList().setClearPending(); 2356 mWebViewCore.sendMessage(EventHub.CLEAR_HISTORY); 2357 } 2358 2359 /** 2360 * Clear the SSL preferences table stored in response to proceeding with SSL 2361 * certificate errors. 2362 */ 2363 public void clearSslPreferences() { 2364 mWebViewCore.sendMessage(EventHub.CLEAR_SSL_PREF_TABLE); 2365 } 2366 2367 /** 2368 * Return the WebBackForwardList for this WebView. This contains the 2369 * back/forward list for use in querying each item in the history stack. 2370 * This is a copy of the private WebBackForwardList so it contains only a 2371 * snapshot of the current state. Multiple calls to this method may return 2372 * different objects. The object returned from this method will not be 2373 * updated to reflect any new state. 2374 */ 2375 public WebBackForwardList copyBackForwardList() { 2376 return mCallbackProxy.getBackForwardList().clone(); 2377 } 2378 2379 /* 2380 * Highlight and scroll to the next occurance of String in findAll. 2381 * Wraps the page infinitely, and scrolls. Must be called after 2382 * calling findAll. 2383 * 2384 * @param forward Direction to search. 2385 */ 2386 public void findNext(boolean forward) { 2387 if (0 == mNativeClass) return; // client isn't initialized 2388 nativeFindNext(forward); 2389 } 2390 2391 /* 2392 * Find all instances of find on the page and highlight them. 2393 * @param find String to find. 2394 * @return int The number of occurances of the String "find" 2395 * that were found. 2396 */ 2397 public int findAll(String find) { 2398 if (0 == mNativeClass) return 0; // client isn't initialized 2399 if (mFindIsUp == false) { 2400 recordNewContentSize(mContentWidth, mContentHeight + mFindHeight, 2401 false); 2402 mFindIsUp = true; 2403 } 2404 int result = nativeFindAll(find.toLowerCase(), find.toUpperCase()); 2405 invalidate(); 2406 mLastFind = find; 2407 return result; 2408 } 2409 2410 // Used to know whether the find dialog is open. Affects whether 2411 // or not we draw the highlights for matches. 2412 private boolean mFindIsUp; 2413 private int mFindHeight; 2414 // Keep track of the last string sent, so we can search again after an 2415 // orientation change or the dismissal of the soft keyboard. 2416 private String mLastFind; 2417 2418 /** 2419 * Return the first substring consisting of the address of a physical 2420 * location. Currently, only addresses in the United States are detected, 2421 * and consist of: 2422 * - a house number 2423 * - a street name 2424 * - a street type (Road, Circle, etc), either spelled out or abbreviated 2425 * - a city name 2426 * - a state or territory, either spelled out or two-letter abbr. 2427 * - an optional 5 digit or 9 digit zip code. 2428 * 2429 * All names must be correctly capitalized, and the zip code, if present, 2430 * must be valid for the state. The street type must be a standard USPS 2431 * spelling or abbreviation. The state or territory must also be spelled 2432 * or abbreviated using USPS standards. The house number may not exceed 2433 * five digits. 2434 * @param addr The string to search for addresses. 2435 * 2436 * @return the address, or if no address is found, return null. 2437 */ 2438 public static String findAddress(String addr) { 2439 return findAddress(addr, false); 2440 } 2441 2442 /** 2443 * @hide 2444 * Return the first substring consisting of the address of a physical 2445 * location. Currently, only addresses in the United States are detected, 2446 * and consist of: 2447 * - a house number 2448 * - a street name 2449 * - a street type (Road, Circle, etc), either spelled out or abbreviated 2450 * - a city name 2451 * - a state or territory, either spelled out or two-letter abbr. 2452 * - an optional 5 digit or 9 digit zip code. 2453 * 2454 * Names are optionally capitalized, and the zip code, if present, 2455 * must be valid for the state. The street type must be a standard USPS 2456 * spelling or abbreviation. The state or territory must also be spelled 2457 * or abbreviated using USPS standards. The house number may not exceed 2458 * five digits. 2459 * @param addr The string to search for addresses. 2460 * @param caseInsensitive addr Set to true to make search ignore case. 2461 * 2462 * @return the address, or if no address is found, return null. 2463 */ 2464 public static String findAddress(String addr, boolean caseInsensitive) { 2465 return WebViewCore.nativeFindAddress(addr, caseInsensitive); 2466 } 2467 2468 /* 2469 * Clear the highlighting surrounding text matches created by findAll. 2470 */ 2471 public void clearMatches() { 2472 if (mNativeClass == 0) 2473 return; 2474 if (mFindIsUp) { 2475 recordNewContentSize(mContentWidth, mContentHeight - mFindHeight, 2476 false); 2477 mFindIsUp = false; 2478 } 2479 nativeSetFindIsUp(); 2480 // Now that the dialog has been removed, ensure that we scroll to a 2481 // location that is not beyond the end of the page. 2482 pinScrollTo(mScrollX, mScrollY, false, 0); 2483 invalidate(); 2484 } 2485 2486 /** 2487 * @hide 2488 */ 2489 public void setFindDialogHeight(int height) { 2490 if (DebugFlags.WEB_VIEW) { 2491 Log.v(LOGTAG, "setFindDialogHeight height=" + height); 2492 } 2493 mFindHeight = height; 2494 } 2495 2496 /** 2497 * Query the document to see if it contains any image references. The 2498 * message object will be dispatched with arg1 being set to 1 if images 2499 * were found and 0 if the document does not reference any images. 2500 * @param response The message that will be dispatched with the result. 2501 */ 2502 public void documentHasImages(Message response) { 2503 if (response == null) { 2504 return; 2505 } 2506 mWebViewCore.sendMessage(EventHub.DOC_HAS_IMAGES, response); 2507 } 2508 2509 @Override 2510 public void computeScroll() { 2511 if (mScroller.computeScrollOffset()) { 2512 int oldX = mScrollX; 2513 int oldY = mScrollY; 2514 mScrollX = mScroller.getCurrX(); 2515 mScrollY = mScroller.getCurrY(); 2516 postInvalidate(); // So we draw again 2517 if (oldX != mScrollX || oldY != mScrollY) { 2518 // as onScrollChanged() is not called, sendOurVisibleRect() 2519 // needs to be call explicitly 2520 sendOurVisibleRect(); 2521 } 2522 } else { 2523 super.computeScroll(); 2524 } 2525 } 2526 2527 private static int computeDuration(int dx, int dy) { 2528 int distance = Math.max(Math.abs(dx), Math.abs(dy)); 2529 int duration = distance * 1000 / STD_SPEED; 2530 return Math.min(duration, MAX_DURATION); 2531 } 2532 2533 // helper to pin the scrollBy parameters (already in view coordinates) 2534 // returns true if the scroll was changed 2535 private boolean pinScrollBy(int dx, int dy, boolean animate, int animationDuration) { 2536 return pinScrollTo(mScrollX + dx, mScrollY + dy, animate, animationDuration); 2537 } 2538 // helper to pin the scrollTo parameters (already in view coordinates) 2539 // returns true if the scroll was changed 2540 private boolean pinScrollTo(int x, int y, boolean animate, int animationDuration) { 2541 x = pinLocX(x); 2542 y = pinLocY(y); 2543 int dx = x - mScrollX; 2544 int dy = y - mScrollY; 2545 2546 if ((dx | dy) == 0) { 2547 return false; 2548 } 2549 if (animate) { 2550 // Log.d(LOGTAG, "startScroll: " + dx + " " + dy); 2551 mScroller.startScroll(mScrollX, mScrollY, dx, dy, 2552 animationDuration > 0 ? animationDuration : computeDuration(dx, dy)); 2553 awakenScrollBars(mScroller.getDuration()); 2554 invalidate(); 2555 } else { 2556 abortAnimation(); // just in case 2557 scrollTo(x, y); 2558 } 2559 return true; 2560 } 2561 2562 // Scale from content to view coordinates, and pin. 2563 // Also called by jni webview.cpp 2564 private boolean setContentScrollBy(int cx, int cy, boolean animate) { 2565 if (mDrawHistory) { 2566 // disallow WebView to change the scroll position as History Picture 2567 // is used in the view system. 2568 // TODO: as we switchOutDrawHistory when trackball or navigation 2569 // keys are hit, this should be safe. Right? 2570 return false; 2571 } 2572 cx = contentToViewDimension(cx); 2573 cy = contentToViewDimension(cy); 2574 if (mHeightCanMeasure) { 2575 // move our visible rect according to scroll request 2576 if (cy != 0) { 2577 Rect tempRect = new Rect(); 2578 calcOurVisibleRect(tempRect); 2579 tempRect.offset(cx, cy); 2580 requestRectangleOnScreen(tempRect); 2581 } 2582 // FIXME: We scroll horizontally no matter what because currently 2583 // ScrollView and ListView will not scroll horizontally. 2584 // FIXME: Why do we only scroll horizontally if there is no 2585 // vertical scroll? 2586// Log.d(LOGTAG, "setContentScrollBy cy=" + cy); 2587 return cy == 0 && cx != 0 && pinScrollBy(cx, 0, animate, 0); 2588 } else { 2589 return pinScrollBy(cx, cy, animate, 0); 2590 } 2591 } 2592 2593 /** 2594 * Called by CallbackProxy when the page finishes loading. 2595 * @param url The URL of the page which has finished loading. 2596 */ 2597 /* package */ void onPageFinished(String url) { 2598 if (mPageThatNeedsToSlideTitleBarOffScreen != null) { 2599 // If the user is now on a different page, or has scrolled the page 2600 // past the point where the title bar is offscreen, ignore the 2601 // scroll request. 2602 if (mPageThatNeedsToSlideTitleBarOffScreen.equals(url) 2603 && mScrollX == 0 && mScrollY == 0) { 2604 pinScrollTo(0, mYDistanceToSlideTitleOffScreen, true, 2605 SLIDE_TITLE_DURATION); 2606 } 2607 mPageThatNeedsToSlideTitleBarOffScreen = null; 2608 } 2609 } 2610 2611 /** 2612 * The URL of a page that sent a message to scroll the title bar off screen. 2613 * 2614 * Many mobile sites tell the page to scroll to (0,1) in order to scroll the 2615 * title bar off the screen. Sometimes, the scroll position is set before 2616 * the page finishes loading. Rather than scrolling while the page is still 2617 * loading, keep track of the URL and new scroll position so we can perform 2618 * the scroll once the page finishes loading. 2619 */ 2620 private String mPageThatNeedsToSlideTitleBarOffScreen; 2621 2622 /** 2623 * The destination Y scroll position to be used when the page finishes 2624 * loading. See mPageThatNeedsToSlideTitleBarOffScreen. 2625 */ 2626 private int mYDistanceToSlideTitleOffScreen; 2627 2628 // scale from content to view coordinates, and pin 2629 // return true if pin caused the final x/y different than the request cx/cy, 2630 // and a future scroll may reach the request cx/cy after our size has 2631 // changed 2632 // return false if the view scroll to the exact position as it is requested, 2633 // where negative numbers are taken to mean 0 2634 private boolean setContentScrollTo(int cx, int cy) { 2635 if (mDrawHistory) { 2636 // disallow WebView to change the scroll position as History Picture 2637 // is used in the view system. 2638 // One known case where this is called is that WebCore tries to 2639 // restore the scroll position. As history Picture already uses the 2640 // saved scroll position, it is ok to skip this. 2641 return false; 2642 } 2643 int vx; 2644 int vy; 2645 if ((cx | cy) == 0) { 2646 // If the page is being scrolled to (0,0), do not add in the title 2647 // bar's height, and simply scroll to (0,0). (The only other work 2648 // in contentToView_ is to multiply, so this would not change 0.) 2649 vx = 0; 2650 vy = 0; 2651 } else { 2652 vx = contentToViewX(cx); 2653 vy = contentToViewY(cy); 2654 } 2655// Log.d(LOGTAG, "content scrollTo [" + cx + " " + cy + "] view=[" + 2656// vx + " " + vy + "]"); 2657 // Some mobile sites attempt to scroll the title bar off the page by 2658 // scrolling to (0,1). If we are at the top left corner of the 2659 // page, assume this is an attempt to scroll off the title bar, and 2660 // animate the title bar off screen slowly enough that the user can see 2661 // it. 2662 if (cx == 0 && cy == 1 && mScrollX == 0 && mScrollY == 0 2663 && mTitleBar != null) { 2664 // FIXME: 100 should be defined somewhere as our max progress. 2665 if (getProgress() < 100) { 2666 // Wait to scroll the title bar off screen until the page has 2667 // finished loading. Keep track of the URL and the destination 2668 // Y position 2669 mPageThatNeedsToSlideTitleBarOffScreen = getUrl(); 2670 mYDistanceToSlideTitleOffScreen = vy; 2671 } else { 2672 pinScrollTo(vx, vy, true, SLIDE_TITLE_DURATION); 2673 } 2674 // Since we are animating, we have not yet reached the desired 2675 // scroll position. Do not return true to request another attempt 2676 return false; 2677 } 2678 pinScrollTo(vx, vy, false, 0); 2679 // If the request was to scroll to a negative coordinate, treat it as if 2680 // it was a request to scroll to 0 2681 if ((mScrollX != vx && cx >= 0) || (mScrollY != vy && cy >= 0)) { 2682 return true; 2683 } else { 2684 return false; 2685 } 2686 } 2687 2688 // scale from content to view coordinates, and pin 2689 private void spawnContentScrollTo(int cx, int cy) { 2690 if (mDrawHistory) { 2691 // disallow WebView to change the scroll position as History Picture 2692 // is used in the view system. 2693 return; 2694 } 2695 int vx = contentToViewX(cx); 2696 int vy = contentToViewY(cy); 2697 pinScrollTo(vx, vy, true, 0); 2698 } 2699 2700 /** 2701 * These are from webkit, and are in content coordinate system (unzoomed) 2702 */ 2703 private void contentSizeChanged(boolean updateLayout) { 2704 // suppress 0,0 since we usually see real dimensions soon after 2705 // this avoids drawing the prev content in a funny place. If we find a 2706 // way to consolidate these notifications, this check may become 2707 // obsolete 2708 if ((mContentWidth | mContentHeight) == 0) { 2709 return; 2710 } 2711 2712 if (mHeightCanMeasure) { 2713 if (getMeasuredHeight() != contentToViewDimension(mContentHeight) 2714 || updateLayout) { 2715 requestLayout(); 2716 } 2717 } else if (mWidthCanMeasure) { 2718 if (getMeasuredWidth() != contentToViewDimension(mContentWidth) 2719 || updateLayout) { 2720 requestLayout(); 2721 } 2722 } else { 2723 // If we don't request a layout, try to send our view size to the 2724 // native side to ensure that WebCore has the correct dimensions. 2725 sendViewSizeZoom(); 2726 } 2727 } 2728 2729 /** 2730 * Set the WebViewClient that will receive various notifications and 2731 * requests. This will replace the current handler. 2732 * @param client An implementation of WebViewClient. 2733 */ 2734 public void setWebViewClient(WebViewClient client) { 2735 mCallbackProxy.setWebViewClient(client); 2736 } 2737 2738 /** 2739 * Gets the WebViewClient 2740 * @return the current WebViewClient instance. 2741 * 2742 *@hide pending API council approval. 2743 */ 2744 public WebViewClient getWebViewClient() { 2745 return mCallbackProxy.getWebViewClient(); 2746 } 2747 2748 /** 2749 * Register the interface to be used when content can not be handled by 2750 * the rendering engine, and should be downloaded instead. This will replace 2751 * the current handler. 2752 * @param listener An implementation of DownloadListener. 2753 */ 2754 public void setDownloadListener(DownloadListener listener) { 2755 mCallbackProxy.setDownloadListener(listener); 2756 } 2757 2758 /** 2759 * Set the chrome handler. This is an implementation of WebChromeClient for 2760 * use in handling Javascript dialogs, favicons, titles, and the progress. 2761 * This will replace the current handler. 2762 * @param client An implementation of WebChromeClient. 2763 */ 2764 public void setWebChromeClient(WebChromeClient client) { 2765 mCallbackProxy.setWebChromeClient(client); 2766 } 2767 2768 /** 2769 * Gets the chrome handler. 2770 * @return the current WebChromeClient instance. 2771 * 2772 * @hide API council approval. 2773 */ 2774 public WebChromeClient getWebChromeClient() { 2775 return mCallbackProxy.getWebChromeClient(); 2776 } 2777 2778 /** 2779 * Set the Picture listener. This is an interface used to receive 2780 * notifications of a new Picture. 2781 * @param listener An implementation of WebView.PictureListener. 2782 */ 2783 public void setPictureListener(PictureListener listener) { 2784 mPictureListener = listener; 2785 } 2786 2787 /** 2788 * {@hide} 2789 */ 2790 /* FIXME: Debug only! Remove for SDK! */ 2791 public void externalRepresentation(Message callback) { 2792 mWebViewCore.sendMessage(EventHub.REQUEST_EXT_REPRESENTATION, callback); 2793 } 2794 2795 /** 2796 * {@hide} 2797 */ 2798 /* FIXME: Debug only! Remove for SDK! */ 2799 public void documentAsText(Message callback) { 2800 mWebViewCore.sendMessage(EventHub.REQUEST_DOC_AS_TEXT, callback); 2801 } 2802 2803 /** 2804 * Use this function to bind an object to Javascript so that the 2805 * methods can be accessed from Javascript. 2806 * <p><strong>IMPORTANT:</strong> 2807 * <ul> 2808 * <li> Using addJavascriptInterface() allows JavaScript to control your 2809 * application. This can be a very useful feature or a dangerous security 2810 * issue. When the HTML in the WebView is untrustworthy (for example, part 2811 * or all of the HTML is provided by some person or process), then an 2812 * attacker could inject HTML that will execute your code and possibly any 2813 * code of the attacker's choosing.<br> 2814 * Do not use addJavascriptInterface() unless all of the HTML in this 2815 * WebView was written by you.</li> 2816 * <li> The Java object that is bound runs in another thread and not in 2817 * the thread that it was constructed in.</li> 2818 * </ul></p> 2819 * @param obj The class instance to bind to Javascript 2820 * @param interfaceName The name to used to expose the class in Javascript 2821 */ 2822 public void addJavascriptInterface(Object obj, String interfaceName) { 2823 WebViewCore.JSInterfaceData arg = new WebViewCore.JSInterfaceData(); 2824 arg.mObject = obj; 2825 arg.mInterfaceName = interfaceName; 2826 mWebViewCore.sendMessage(EventHub.ADD_JS_INTERFACE, arg); 2827 } 2828 2829 /** 2830 * Return the WebSettings object used to control the settings for this 2831 * WebView. 2832 * @return A WebSettings object that can be used to control this WebView's 2833 * settings. 2834 */ 2835 public WebSettings getSettings() { 2836 return mWebViewCore.getSettings(); 2837 } 2838 2839 /** 2840 * Return the list of currently loaded plugins. 2841 * @return The list of currently loaded plugins. 2842 * 2843 * @deprecated This was used for Gears, which has been deprecated. 2844 */ 2845 @Deprecated 2846 public static synchronized PluginList getPluginList() { 2847 return new PluginList(); 2848 } 2849 2850 /** 2851 * @deprecated This was used for Gears, which has been deprecated. 2852 */ 2853 @Deprecated 2854 public void refreshPlugins(boolean reloadOpenPages) { } 2855 2856 //------------------------------------------------------------------------- 2857 // Override View methods 2858 //------------------------------------------------------------------------- 2859 2860 @Override 2861 protected void finalize() throws Throwable { 2862 try { 2863 destroy(); 2864 } finally { 2865 super.finalize(); 2866 } 2867 } 2868 2869 @Override 2870 protected boolean drawChild(Canvas canvas, View child, long drawingTime) { 2871 if (child == mTitleBar) { 2872 // When drawing the title bar, move it horizontally to always show 2873 // at the top of the WebView. 2874 mTitleBar.offsetLeftAndRight(mScrollX - mTitleBar.getLeft()); 2875 } 2876 return super.drawChild(canvas, child, drawingTime); 2877 } 2878 2879 private void drawContent(Canvas canvas) { 2880 // Update the buttons in the picture, so when we draw the picture 2881 // to the screen, they are in the correct state. 2882 // Tell the native side if user is a) touching the screen, 2883 // b) pressing the trackball down, or c) pressing the enter key 2884 // If the cursor is on a button, we need to draw it in the pressed 2885 // state. 2886 // If mNativeClass is 0, we should not reach here, so we do not 2887 // need to check it again. 2888 nativeRecordButtons(hasFocus() && hasWindowFocus(), 2889 mTouchMode == TOUCH_SHORTPRESS_START_MODE 2890 || mTrackballDown || mGotCenterDown, false); 2891 drawCoreAndCursorRing(canvas, mBackgroundColor, mDrawCursorRing); 2892 } 2893 2894 @Override 2895 protected void onDraw(Canvas canvas) { 2896 // if mNativeClass is 0, the WebView has been destroyed. Do nothing. 2897 if (mNativeClass == 0) { 2898 return; 2899 } 2900 2901 int saveCount = canvas.save(); 2902 if (mTitleBar != null) { 2903 canvas.translate(0, (int) mTitleBar.getHeight()); 2904 } 2905 if (mDragTrackerHandler == null || !mDragTrackerHandler.draw(canvas)) { 2906 drawContent(canvas); 2907 } 2908 canvas.restoreToCount(saveCount); 2909 2910 // Now draw the shadow. 2911 if (mTitleBar != null) { 2912 int y = mScrollY + getVisibleTitleHeight(); 2913 int height = (int) (5f * getContext().getResources() 2914 .getDisplayMetrics().density); 2915 mTitleShadow.setBounds(mScrollX, y, mScrollX + getWidth(), 2916 y + height); 2917 mTitleShadow.draw(canvas); 2918 } 2919 if (AUTO_REDRAW_HACK && mAutoRedraw) { 2920 invalidate(); 2921 } 2922 } 2923 2924 @Override 2925 public void setLayoutParams(ViewGroup.LayoutParams params) { 2926 if (params.height == LayoutParams.WRAP_CONTENT) { 2927 mWrapContent = true; 2928 } 2929 super.setLayoutParams(params); 2930 } 2931 2932 @Override 2933 public boolean performLongClick() { 2934 if (mNativeClass != 0 && nativeCursorIsTextInput()) { 2935 // Send the click so that the textfield is in focus 2936 centerKeyPressOnTextField(); 2937 rebuildWebTextView(); 2938 } 2939 if (inEditingMode()) { 2940 return mWebTextView.performLongClick(); 2941 } else { 2942 return super.performLongClick(); 2943 } 2944 } 2945 2946 boolean inAnimateZoom() { 2947 return mZoomScale != 0; 2948 } 2949 2950 /** 2951 * Need to adjust the WebTextView after a change in zoom, since mActualScale 2952 * has changed. This is especially important for password fields, which are 2953 * drawn by the WebTextView, since it conveys more information than what 2954 * webkit draws. Thus we need to reposition it to show in the correct 2955 * place. 2956 */ 2957 private boolean mNeedToAdjustWebTextView; 2958 2959 private boolean didUpdateTextViewBounds(boolean allowIntersect) { 2960 Rect contentBounds = nativeFocusCandidateNodeBounds(); 2961 Rect vBox = contentToViewRect(contentBounds); 2962 Rect visibleRect = new Rect(); 2963 calcOurVisibleRect(visibleRect); 2964 // The IME may have shown, resulting in the textfield being offscreen. 2965 // If so, the textfield will be scrolled on screen, so treat it as 2966 // though it is on screen. If it is on screen, place the WebTextView in 2967 // its new place, accounting for our new scroll/zoom values. 2968 InputMethodManager imm = InputMethodManager.peekInstance(); 2969 if ((imm != null && imm.isActive(mWebTextView)) 2970 || (allowIntersect ? Rect.intersects(visibleRect, vBox) 2971 : visibleRect.contains(vBox))) { 2972 mWebTextView.setRect(vBox.left, vBox.top, vBox.width(), 2973 vBox.height()); 2974 mWebTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, 2975 contentToViewDimension( 2976 nativeFocusCandidateTextSize())); 2977 return true; 2978 } else { 2979 // The textfield is now off screen. The user probably 2980 // was not zooming to see the textfield better. Remove 2981 // the WebTextView. If the user types a key, and the 2982 // textfield is still in focus, we will reconstruct 2983 // the WebTextView and scroll it back on screen. 2984 mWebTextView.remove(); 2985 return false; 2986 } 2987 } 2988 2989 private void drawCoreAndCursorRing(Canvas canvas, int color, 2990 boolean drawCursorRing) { 2991 if (mDrawHistory) { 2992 canvas.scale(mActualScale, mActualScale); 2993 canvas.drawPicture(mHistoryPicture); 2994 return; 2995 } 2996 2997 boolean animateZoom = mZoomScale != 0; 2998 boolean animateScroll = (!mScroller.isFinished() 2999 || mVelocityTracker != null) 3000 && (mTouchMode != TOUCH_DRAG_MODE || 3001 mHeldMotionless != MOTIONLESS_TRUE); 3002 if (mTouchMode == TOUCH_DRAG_MODE) { 3003 if (mHeldMotionless == MOTIONLESS_PENDING) { 3004 mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS); 3005 mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS); 3006 mHeldMotionless = MOTIONLESS_FALSE; 3007 } 3008 if (mHeldMotionless == MOTIONLESS_FALSE) { 3009 mPrivateHandler.sendMessageDelayed(mPrivateHandler 3010 .obtainMessage(DRAG_HELD_MOTIONLESS), MOTIONLESS_TIME); 3011 mHeldMotionless = MOTIONLESS_PENDING; 3012 } 3013 } 3014 if (animateZoom) { 3015 float zoomScale; 3016 int interval = (int) (SystemClock.uptimeMillis() - mZoomStart); 3017 if (interval < ZOOM_ANIMATION_LENGTH) { 3018 float ratio = (float) interval / ZOOM_ANIMATION_LENGTH; 3019 zoomScale = 1.0f / (mInvInitialZoomScale 3020 + (mInvFinalZoomScale - mInvInitialZoomScale) * ratio); 3021 invalidate(); 3022 } else { 3023 zoomScale = mZoomScale; 3024 // set mZoomScale to be 0 as we have done animation 3025 mZoomScale = 0; 3026 // call invalidate() again to draw with the final filters 3027 invalidate(); 3028 if (mNeedToAdjustWebTextView) { 3029 mNeedToAdjustWebTextView = false; 3030 if (didUpdateTextViewBounds(false) 3031 && nativeFocusCandidateIsPassword()) { 3032 // If it is a password field, start drawing the 3033 // WebTextView once again. 3034 mWebTextView.setInPassword(true); 3035 } 3036 } 3037 } 3038 // calculate the intermediate scroll position. As we need to use 3039 // zoomScale, we can't use pinLocX/Y directly. Copy the logic here. 3040 float scale = zoomScale * mInvInitialZoomScale; 3041 int tx = Math.round(scale * (mInitialScrollX + mZoomCenterX) 3042 - mZoomCenterX); 3043 tx = -pinLoc(tx, getViewWidth(), Math.round(mContentWidth 3044 * zoomScale)) + mScrollX; 3045 int titleHeight = getTitleHeight(); 3046 int ty = Math.round(scale 3047 * (mInitialScrollY + mZoomCenterY - titleHeight) 3048 - (mZoomCenterY - titleHeight)); 3049 ty = -(ty <= titleHeight ? Math.max(ty, 0) : pinLoc(ty 3050 - titleHeight, getViewHeight(), Math.round(mContentHeight 3051 * zoomScale)) + titleHeight) + mScrollY; 3052 canvas.translate(tx, ty); 3053 canvas.scale(zoomScale, zoomScale); 3054 if (inEditingMode() && !mNeedToAdjustWebTextView 3055 && mZoomScale != 0) { 3056 // The WebTextView is up. Keep track of this so we can adjust 3057 // its size and placement when we finish zooming 3058 mNeedToAdjustWebTextView = true; 3059 // If it is in password mode, turn it off so it does not draw 3060 // misplaced. 3061 if (nativeFocusCandidateIsPassword()) { 3062 mWebTextView.setInPassword(false); 3063 } 3064 } 3065 } else { 3066 canvas.scale(mActualScale, mActualScale); 3067 } 3068 3069 mWebViewCore.drawContentPicture(canvas, color, animateZoom, 3070 animateScroll); 3071 3072 if (mNativeClass == 0) return; 3073 if (mShiftIsPressed && !animateZoom) { 3074 if (mTouchSelection || mExtendSelection) { 3075 nativeDrawSelectionRegion(canvas); 3076 } 3077 if (!mTouchSelection) { 3078 nativeDrawSelectionPointer(canvas, mInvActualScale, mSelectX, 3079 mSelectY - getTitleHeight(), mExtendSelection); 3080 } 3081 } else if (drawCursorRing) { 3082 if (mTouchMode == TOUCH_SHORTPRESS_START_MODE) { 3083 mTouchMode = TOUCH_SHORTPRESS_MODE; 3084 HitTestResult hitTest = getHitTestResult(); 3085 if (mPreventLongPress || (hitTest != null && 3086 hitTest.mType != HitTestResult.UNKNOWN_TYPE)) { 3087 mPrivateHandler.sendMessageDelayed(mPrivateHandler 3088 .obtainMessage(SWITCH_TO_LONGPRESS), 3089 LONG_PRESS_TIMEOUT); 3090 } 3091 } 3092 nativeDrawCursorRing(canvas); 3093 } 3094 // When the FindDialog is up, only draw the matches if we are not in 3095 // the process of scrolling them into view. 3096 if (mFindIsUp && !animateScroll) { 3097 nativeDrawMatches(canvas); 3098 } 3099 if (mFocusSizeChanged) { 3100 mFocusSizeChanged = false; 3101 // If we are zooming, this will get handled above, when the zoom 3102 // finishes. We also do not need to do this unless the WebTextView 3103 // is showing. 3104 if (!animateZoom && inEditingMode()) { 3105 didUpdateTextViewBounds(true); 3106 } 3107 } 3108 } 3109 3110 // draw history 3111 private boolean mDrawHistory = false; 3112 private Picture mHistoryPicture = null; 3113 private int mHistoryWidth = 0; 3114 private int mHistoryHeight = 0; 3115 3116 // Only check the flag, can be called from WebCore thread 3117 boolean drawHistory() { 3118 return mDrawHistory; 3119 } 3120 3121 // Should only be called in UI thread 3122 void switchOutDrawHistory() { 3123 if (null == mWebViewCore) return; // CallbackProxy may trigger this 3124 if (mDrawHistory && mWebViewCore.pictureReady()) { 3125 mDrawHistory = false; 3126 invalidate(); 3127 int oldScrollX = mScrollX; 3128 int oldScrollY = mScrollY; 3129 mScrollX = pinLocX(mScrollX); 3130 mScrollY = pinLocY(mScrollY); 3131 if (oldScrollX != mScrollX || oldScrollY != mScrollY) { 3132 mUserScroll = false; 3133 mWebViewCore.sendMessage(EventHub.SYNC_SCROLL, oldScrollX, 3134 oldScrollY); 3135 } 3136 sendOurVisibleRect(); 3137 } 3138 } 3139 3140 WebViewCore.CursorData cursorData() { 3141 WebViewCore.CursorData result = new WebViewCore.CursorData(); 3142 result.mMoveGeneration = nativeMoveGeneration(); 3143 result.mFrame = nativeCursorFramePointer(); 3144 Point position = nativeCursorPosition(); 3145 result.mX = position.x; 3146 result.mY = position.y; 3147 return result; 3148 } 3149 3150 /** 3151 * Delete text from start to end in the focused textfield. If there is no 3152 * focus, or if start == end, silently fail. If start and end are out of 3153 * order, swap them. 3154 * @param start Beginning of selection to delete. 3155 * @param end End of selection to delete. 3156 */ 3157 /* package */ void deleteSelection(int start, int end) { 3158 mTextGeneration++; 3159 WebViewCore.TextSelectionData data 3160 = new WebViewCore.TextSelectionData(start, end); 3161 mWebViewCore.sendMessage(EventHub.DELETE_SELECTION, mTextGeneration, 0, 3162 data); 3163 } 3164 3165 /** 3166 * Set the selection to (start, end) in the focused textfield. If start and 3167 * end are out of order, swap them. 3168 * @param start Beginning of selection. 3169 * @param end End of selection. 3170 */ 3171 /* package */ void setSelection(int start, int end) { 3172 mWebViewCore.sendMessage(EventHub.SET_SELECTION, start, end); 3173 } 3174 3175 // Called by JNI when a touch event puts a textfield into focus. 3176 private void displaySoftKeyboard(boolean isTextView) { 3177 InputMethodManager imm = (InputMethodManager) 3178 getContext().getSystemService(Context.INPUT_METHOD_SERVICE); 3179 3180 if (isTextView) { 3181 if (mWebTextView == null) return; 3182 3183 imm.showSoftInput(mWebTextView, 0); 3184 if (mInZoomOverview) { 3185 // if in zoom overview mode, call doDoubleTap() to bring it back 3186 // to normal mode so that user can enter text. 3187 doDoubleTap(); 3188 } 3189 } 3190 else { // used by plugins 3191 imm.showSoftInput(this, 0); 3192 } 3193 } 3194 3195 // Called by WebKit to instruct the UI to hide the keyboard 3196 private void hideSoftKeyboard() { 3197 InputMethodManager imm = (InputMethodManager) 3198 getContext().getSystemService(Context.INPUT_METHOD_SERVICE); 3199 3200 imm.hideSoftInputFromWindow(this.getWindowToken(), 0); 3201 } 3202 3203 /* 3204 * This method checks the current focus and cursor and potentially rebuilds 3205 * mWebTextView to have the appropriate properties, such as password, 3206 * multiline, and what text it contains. It also removes it if necessary. 3207 */ 3208 /* package */ void rebuildWebTextView() { 3209 // If the WebView does not have focus, do nothing until it gains focus. 3210 if (!hasFocus() && (null == mWebTextView || !mWebTextView.hasFocus())) { 3211 return; 3212 } 3213 boolean alreadyThere = inEditingMode(); 3214 // inEditingMode can only return true if mWebTextView is non-null, 3215 // so we can safely call remove() if (alreadyThere) 3216 if (0 == mNativeClass || !nativeFocusCandidateIsTextInput()) { 3217 if (alreadyThere) { 3218 mWebTextView.remove(); 3219 } 3220 return; 3221 } 3222 // At this point, we know we have found an input field, so go ahead 3223 // and create the WebTextView if necessary. 3224 if (mWebTextView == null) { 3225 mWebTextView = new WebTextView(mContext, WebView.this); 3226 // Initialize our generation number. 3227 mTextGeneration = 0; 3228 } 3229 mWebTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, 3230 contentToViewDimension(nativeFocusCandidateTextSize())); 3231 Rect visibleRect = new Rect(); 3232 calcOurContentVisibleRect(visibleRect); 3233 // Note that sendOurVisibleRect calls viewToContent, so the coordinates 3234 // should be in content coordinates. 3235 Rect bounds = nativeFocusCandidateNodeBounds(); 3236 Rect vBox = contentToViewRect(bounds); 3237 mWebTextView.setRect(vBox.left, vBox.top, vBox.width(), vBox.height()); 3238 if (!Rect.intersects(bounds, visibleRect)) { 3239 mWebTextView.bringIntoView(); 3240 } 3241 String text = nativeFocusCandidateText(); 3242 int nodePointer = nativeFocusCandidatePointer(); 3243 if (alreadyThere && mWebTextView.isSameTextField(nodePointer)) { 3244 // It is possible that we have the same textfield, but it has moved, 3245 // i.e. In the case of opening/closing the screen. 3246 // In that case, we need to set the dimensions, but not the other 3247 // aspects. 3248 // If the text has been changed by webkit, update it. However, if 3249 // there has been more UI text input, ignore it. We will receive 3250 // another update when that text is recognized. 3251 if (text != null && !text.equals(mWebTextView.getText().toString()) 3252 && nativeTextGeneration() == mTextGeneration) { 3253 mWebTextView.setTextAndKeepSelection(text); 3254 } 3255 } else { 3256 mWebTextView.setGravity(nativeFocusCandidateIsRtlText() ? 3257 Gravity.RIGHT : Gravity.NO_GRAVITY); 3258 // This needs to be called before setType, which may call 3259 // requestFormData, and it needs to have the correct nodePointer. 3260 mWebTextView.setNodePointer(nodePointer); 3261 mWebTextView.setType(nativeFocusCandidateType()); 3262 if (null == text) { 3263 if (DebugFlags.WEB_VIEW) { 3264 Log.v(LOGTAG, "rebuildWebTextView null == text"); 3265 } 3266 text = ""; 3267 } 3268 mWebTextView.setTextAndKeepSelection(text); 3269 } 3270 mWebTextView.requestFocus(); 3271 } 3272 3273 /** 3274 * Called by WebTextView to find saved form data associated with the 3275 * textfield 3276 * @param name Name of the textfield. 3277 * @param nodePointer Pointer to the node of the textfield, so it can be 3278 * compared to the currently focused textfield when the data is 3279 * retrieved. 3280 */ 3281 /* package */ void requestFormData(String name, int nodePointer) { 3282 if (mWebViewCore.getSettings().getSaveFormData()) { 3283 Message update = mPrivateHandler.obtainMessage(REQUEST_FORM_DATA); 3284 update.arg1 = nodePointer; 3285 RequestFormData updater = new RequestFormData(name, getUrl(), 3286 update); 3287 Thread t = new Thread(updater); 3288 t.start(); 3289 } 3290 } 3291 3292 /* 3293 * This class requests an Adapter for the WebTextView which shows past 3294 * entries stored in the database. It is a Runnable so that it can be done 3295 * in its own thread, without slowing down the UI. 3296 */ 3297 private class RequestFormData implements Runnable { 3298 private String mName; 3299 private String mUrl; 3300 private Message mUpdateMessage; 3301 3302 public RequestFormData(String name, String url, Message msg) { 3303 mName = name; 3304 mUrl = url; 3305 mUpdateMessage = msg; 3306 } 3307 3308 public void run() { 3309 ArrayList<String> pastEntries = mDatabase.getFormData(mUrl, mName); 3310 if (pastEntries.size() > 0) { 3311 AutoCompleteAdapter adapter = new 3312 AutoCompleteAdapter(mContext, pastEntries); 3313 mUpdateMessage.obj = adapter; 3314 mUpdateMessage.sendToTarget(); 3315 } 3316 } 3317 } 3318 3319 /** 3320 * Dump the display tree to "/sdcard/displayTree.txt" 3321 * 3322 * @hide debug only 3323 */ 3324 public void dumpDisplayTree() { 3325 nativeDumpDisplayTree(getUrl()); 3326 } 3327 3328 /** 3329 * Dump the dom tree to adb shell if "toFile" is False, otherwise dump it to 3330 * "/sdcard/domTree.txt" 3331 * 3332 * @hide debug only 3333 */ 3334 public void dumpDomTree(boolean toFile) { 3335 mWebViewCore.sendMessage(EventHub.DUMP_DOMTREE, toFile ? 1 : 0, 0); 3336 } 3337 3338 /** 3339 * Dump the render tree to adb shell if "toFile" is False, otherwise dump it 3340 * to "/sdcard/renderTree.txt" 3341 * 3342 * @hide debug only 3343 */ 3344 public void dumpRenderTree(boolean toFile) { 3345 mWebViewCore.sendMessage(EventHub.DUMP_RENDERTREE, toFile ? 1 : 0, 0); 3346 } 3347 3348 // This is used to determine long press with the center key. Does not 3349 // affect long press with the trackball/touch. 3350 private boolean mGotCenterDown = false; 3351 3352 @Override 3353 public boolean onKeyDown(int keyCode, KeyEvent event) { 3354 if (DebugFlags.WEB_VIEW) { 3355 Log.v(LOGTAG, "keyDown at " + System.currentTimeMillis() 3356 + ", " + event + ", unicode=" + event.getUnicodeChar()); 3357 } 3358 3359 if (mNativeClass == 0) { 3360 return false; 3361 } 3362 3363 // do this hack up front, so it always works, regardless of touch-mode 3364 if (AUTO_REDRAW_HACK && (keyCode == KeyEvent.KEYCODE_CALL)) { 3365 mAutoRedraw = !mAutoRedraw; 3366 if (mAutoRedraw) { 3367 invalidate(); 3368 } 3369 return true; 3370 } 3371 3372 // Bubble up the key event if 3373 // 1. it is a system key; or 3374 // 2. the host application wants to handle it; 3375 if (event.isSystem() 3376 || mCallbackProxy.uiOverrideKeyEvent(event)) { 3377 return false; 3378 } 3379 3380 if (mShiftIsPressed == false && nativeCursorWantsKeyEvents() == false 3381 && (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT 3382 || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT)) { 3383 setUpSelectXY(); 3384 } 3385 3386 if (keyCode >= KeyEvent.KEYCODE_DPAD_UP 3387 && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) { 3388 // always handle the navigation keys in the UI thread 3389 switchOutDrawHistory(); 3390 if (mShiftIsPressed) { 3391 int xRate = keyCode == KeyEvent.KEYCODE_DPAD_LEFT 3392 ? -1 : keyCode == KeyEvent.KEYCODE_DPAD_RIGHT ? 1 : 0; 3393 int yRate = keyCode == KeyEvent.KEYCODE_DPAD_UP ? 3394 -1 : keyCode == KeyEvent.KEYCODE_DPAD_DOWN ? 1 : 0; 3395 int multiplier = event.getRepeatCount() + 1; 3396 moveSelection(xRate * multiplier, yRate * multiplier); 3397 return true; 3398 } 3399 if (navHandledKey(keyCode, 1, false, event.getEventTime(), false)) { 3400 playSoundEffect(keyCodeToSoundsEffect(keyCode)); 3401 return true; 3402 } 3403 // Bubble up the key event as WebView doesn't handle it 3404 return false; 3405 } 3406 3407 if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { 3408 switchOutDrawHistory(); 3409 if (event.getRepeatCount() == 0) { 3410 if (mShiftIsPressed) { 3411 return true; // discard press if copy in progress 3412 } 3413 mGotCenterDown = true; 3414 mPrivateHandler.sendMessageDelayed(mPrivateHandler 3415 .obtainMessage(LONG_PRESS_CENTER), LONG_PRESS_TIMEOUT); 3416 // Already checked mNativeClass, so we do not need to check it 3417 // again. 3418 nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true); 3419 return true; 3420 } 3421 // Bubble up the key event as WebView doesn't handle it 3422 return false; 3423 } 3424 3425 if (keyCode != KeyEvent.KEYCODE_SHIFT_LEFT 3426 && keyCode != KeyEvent.KEYCODE_SHIFT_RIGHT) { 3427 // turn off copy select if a shift-key combo is pressed 3428 mExtendSelection = mShiftIsPressed = false; 3429 if (mTouchMode == TOUCH_SELECT_MODE) { 3430 mTouchMode = TOUCH_INIT_MODE; 3431 } 3432 } 3433 3434 if (getSettings().getNavDump()) { 3435 switch (keyCode) { 3436 case KeyEvent.KEYCODE_4: 3437 dumpDisplayTree(); 3438 break; 3439 case KeyEvent.KEYCODE_5: 3440 case KeyEvent.KEYCODE_6: 3441 dumpDomTree(keyCode == KeyEvent.KEYCODE_5); 3442 break; 3443 case KeyEvent.KEYCODE_7: 3444 case KeyEvent.KEYCODE_8: 3445 dumpRenderTree(keyCode == KeyEvent.KEYCODE_7); 3446 break; 3447 case KeyEvent.KEYCODE_9: 3448 nativeInstrumentReport(); 3449 return true; 3450 } 3451 } 3452 3453 if (nativeCursorIsTextInput()) { 3454 // This message will put the node in focus, for the DOM's notion 3455 // of focus, and make the focuscontroller active 3456 mWebViewCore.sendMessage(EventHub.CLICK, nativeCursorFramePointer(), 3457 nativeCursorNodePointer()); 3458 // This will bring up the WebTextView and put it in focus, for 3459 // our view system's notion of focus 3460 rebuildWebTextView(); 3461 // Now we need to pass the event to it 3462 if (inEditingMode()) { 3463 mWebTextView.setDefaultSelection(); 3464 return mWebTextView.dispatchKeyEvent(event); 3465 } 3466 } else if (nativeHasFocusNode()) { 3467 // In this case, the cursor is not on a text input, but the focus 3468 // might be. Check it, and if so, hand over to the WebTextView. 3469 rebuildWebTextView(); 3470 if (inEditingMode()) { 3471 return mWebTextView.dispatchKeyEvent(event); 3472 } 3473 } 3474 3475 // TODO: should we pass all the keys to DOM or check the meta tag 3476 if (nativeCursorWantsKeyEvents() || true) { 3477 // pass the key to DOM 3478 mWebViewCore.sendMessage(EventHub.KEY_DOWN, event); 3479 // return true as DOM handles the key 3480 return true; 3481 } 3482 3483 // Bubble up the key event as WebView doesn't handle it 3484 return false; 3485 } 3486 3487 @Override 3488 public boolean onKeyUp(int keyCode, KeyEvent event) { 3489 if (DebugFlags.WEB_VIEW) { 3490 Log.v(LOGTAG, "keyUp at " + System.currentTimeMillis() 3491 + ", " + event + ", unicode=" + event.getUnicodeChar()); 3492 } 3493 3494 if (mNativeClass == 0) { 3495 return false; 3496 } 3497 3498 // special CALL handling when cursor node's href is "tel:XXX" 3499 if (keyCode == KeyEvent.KEYCODE_CALL && nativeHasCursorNode()) { 3500 String text = nativeCursorText(); 3501 if (!nativeCursorIsTextInput() && text != null 3502 && text.startsWith(SCHEME_TEL)) { 3503 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(text)); 3504 getContext().startActivity(intent); 3505 return true; 3506 } 3507 } 3508 3509 // Bubble up the key event if 3510 // 1. it is a system key; or 3511 // 2. the host application wants to handle it; 3512 if (event.isSystem() || mCallbackProxy.uiOverrideKeyEvent(event)) { 3513 return false; 3514 } 3515 3516 if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT 3517 || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT) { 3518 if (commitCopy()) { 3519 return true; 3520 } 3521 } 3522 3523 if (keyCode >= KeyEvent.KEYCODE_DPAD_UP 3524 && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) { 3525 // always handle the navigation keys in the UI thread 3526 // Bubble up the key event as WebView doesn't handle it 3527 return false; 3528 } 3529 3530 if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { 3531 // remove the long press message first 3532 mPrivateHandler.removeMessages(LONG_PRESS_CENTER); 3533 mGotCenterDown = false; 3534 3535 if (mShiftIsPressed) { 3536 if (mExtendSelection) { 3537 commitCopy(); 3538 } else { 3539 mExtendSelection = true; 3540 invalidate(); // draw the i-beam instead of the arrow 3541 } 3542 return true; // discard press if copy in progress 3543 } 3544 3545 // perform the single click 3546 Rect visibleRect = sendOurVisibleRect(); 3547 // Note that sendOurVisibleRect calls viewToContent, so the 3548 // coordinates should be in content coordinates. 3549 if (!nativeCursorIntersects(visibleRect)) { 3550 return false; 3551 } 3552 WebViewCore.CursorData data = cursorData(); 3553 mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE, data); 3554 playSoundEffect(SoundEffectConstants.CLICK); 3555 if (nativeCursorIsTextInput()) { 3556 rebuildWebTextView(); 3557 centerKeyPressOnTextField(); 3558 if (inEditingMode()) { 3559 mWebTextView.setDefaultSelection(); 3560 } 3561 return true; 3562 } 3563 nativeSetFollowedLink(true); 3564 if (!mCallbackProxy.uiOverrideUrlLoading(nativeCursorText())) { 3565 mWebViewCore.sendMessage(EventHub.CLICK, data.mFrame, 3566 nativeCursorNodePointer()); 3567 } 3568 return true; 3569 } 3570 3571 // TODO: should we pass all the keys to DOM or check the meta tag 3572 if (nativeCursorWantsKeyEvents() || true) { 3573 // pass the key to DOM 3574 mWebViewCore.sendMessage(EventHub.KEY_UP, event); 3575 // return true as DOM handles the key 3576 return true; 3577 } 3578 3579 // Bubble up the key event as WebView doesn't handle it 3580 return false; 3581 } 3582 3583 private void setUpSelectXY() { 3584 mExtendSelection = false; 3585 mShiftIsPressed = true; 3586 if (nativeHasCursorNode()) { 3587 Rect rect = nativeCursorNodeBounds(); 3588 mSelectX = contentToViewX(rect.left); 3589 mSelectY = contentToViewY(rect.top); 3590 } else if (mLastTouchY > getVisibleTitleHeight()) { 3591 mSelectX = mScrollX + (int) mLastTouchX; 3592 mSelectY = mScrollY + (int) mLastTouchY; 3593 } else { 3594 mSelectX = mScrollX + getViewWidth() / 2; 3595 mSelectY = mScrollY + getViewHeightWithTitle() / 2; 3596 } 3597 nativeHideCursor(); 3598 } 3599 3600 /** 3601 * @hide 3602 */ 3603 public void emulateShiftHeld() { 3604 if (0 == mNativeClass) return; // client isn't initialized 3605 setUpSelectXY(); 3606 } 3607 3608 private boolean commitCopy() { 3609 boolean copiedSomething = false; 3610 if (mExtendSelection) { 3611 // copy region so core operates on copy without touching orig. 3612 Region selection = new Region(nativeGetSelection()); 3613 if (selection.isEmpty() == false) { 3614 Toast.makeText(mContext 3615 , com.android.internal.R.string.text_copied 3616 , Toast.LENGTH_SHORT).show(); 3617 mWebViewCore.sendMessage(EventHub.GET_SELECTION, selection); 3618 copiedSomething = true; 3619 } 3620 mExtendSelection = false; 3621 } 3622 mShiftIsPressed = false; 3623 invalidate(); // remove selection region and pointer 3624 if (mTouchMode == TOUCH_SELECT_MODE) { 3625 mTouchMode = TOUCH_INIT_MODE; 3626 } 3627 return copiedSomething; 3628 } 3629 3630 @Override 3631 protected void onAttachedToWindow() { 3632 super.onAttachedToWindow(); 3633 if (hasWindowFocus()) onWindowFocusChanged(true); 3634 } 3635 3636 @Override 3637 protected void onDetachedFromWindow() { 3638 clearTextEntry(); 3639 super.onDetachedFromWindow(); 3640 // Clean up the zoom controller 3641 mZoomButtonsController.setVisible(false); 3642 } 3643 3644 /** 3645 * @deprecated WebView no longer needs to implement 3646 * ViewGroup.OnHierarchyChangeListener. This method does nothing now. 3647 */ 3648 @Deprecated 3649 public void onChildViewAdded(View parent, View child) {} 3650 3651 /** 3652 * @deprecated WebView no longer needs to implement 3653 * ViewGroup.OnHierarchyChangeListener. This method does nothing now. 3654 */ 3655 @Deprecated 3656 public void onChildViewRemoved(View p, View child) {} 3657 3658 /** 3659 * @deprecated WebView should not have implemented 3660 * ViewTreeObserver.OnGlobalFocusChangeListener. This method 3661 * does nothing now. 3662 */ 3663 @Deprecated 3664 public void onGlobalFocusChanged(View oldFocus, View newFocus) { 3665 } 3666 3667 // To avoid drawing the cursor ring, and remove the TextView when our window 3668 // loses focus. 3669 @Override 3670 public void onWindowFocusChanged(boolean hasWindowFocus) { 3671 if (hasWindowFocus) { 3672 if (hasFocus()) { 3673 // If our window regained focus, and we have focus, then begin 3674 // drawing the cursor ring 3675 mDrawCursorRing = true; 3676 if (mNativeClass != 0) { 3677 nativeRecordButtons(true, false, true); 3678 if (inEditingMode()) { 3679 mWebViewCore.sendMessage(EventHub.SET_ACTIVE, 1, 0); 3680 } 3681 } 3682 } else { 3683 // If our window gained focus, but we do not have it, do not 3684 // draw the cursor ring. 3685 mDrawCursorRing = false; 3686 // We do not call nativeRecordButtons here because we assume 3687 // that when we lost focus, or window focus, it got called with 3688 // false for the first parameter 3689 } 3690 } else { 3691 if (getSettings().getBuiltInZoomControls() && !mZoomButtonsController.isVisible()) { 3692 /* 3693 * The zoom controls come in their own window, so our window 3694 * loses focus. Our policy is to not draw the cursor ring if 3695 * our window is not focused, but this is an exception since 3696 * the user can still navigate the web page with the zoom 3697 * controls showing. 3698 */ 3699 // If our window has lost focus, stop drawing the cursor ring 3700 mDrawCursorRing = false; 3701 } 3702 mGotKeyDown = false; 3703 mShiftIsPressed = false; 3704 if (mNativeClass != 0) { 3705 nativeRecordButtons(false, false, true); 3706 } 3707 setFocusControllerInactive(); 3708 } 3709 invalidate(); 3710 super.onWindowFocusChanged(hasWindowFocus); 3711 } 3712 3713 /* 3714 * Pass a message to WebCore Thread, telling the WebCore::Page's 3715 * FocusController to be "inactive" so that it will 3716 * not draw the blinking cursor. It gets set to "active" to draw the cursor 3717 * in WebViewCore.cpp, when the WebCore thread receives key events/clicks. 3718 */ 3719 /* package */ void setFocusControllerInactive() { 3720 // Do not need to also check whether mWebViewCore is null, because 3721 // mNativeClass is only set if mWebViewCore is non null 3722 if (mNativeClass == 0) return; 3723 mWebViewCore.sendMessage(EventHub.SET_ACTIVE, 0, 0); 3724 } 3725 3726 @Override 3727 protected void onFocusChanged(boolean focused, int direction, 3728 Rect previouslyFocusedRect) { 3729 if (DebugFlags.WEB_VIEW) { 3730 Log.v(LOGTAG, "MT focusChanged " + focused + ", " + direction); 3731 } 3732 if (focused) { 3733 // When we regain focus, if we have window focus, resume drawing 3734 // the cursor ring 3735 if (hasWindowFocus()) { 3736 mDrawCursorRing = true; 3737 if (mNativeClass != 0) { 3738 nativeRecordButtons(true, false, true); 3739 } 3740 //} else { 3741 // The WebView has gained focus while we do not have 3742 // windowfocus. When our window lost focus, we should have 3743 // called nativeRecordButtons(false...) 3744 } 3745 } else { 3746 // When we lost focus, unless focus went to the TextView (which is 3747 // true if we are in editing mode), stop drawing the cursor ring. 3748 if (!inEditingMode()) { 3749 mDrawCursorRing = false; 3750 if (mNativeClass != 0) { 3751 nativeRecordButtons(false, false, true); 3752 } 3753 setFocusControllerInactive(); 3754 } 3755 mGotKeyDown = false; 3756 } 3757 3758 super.onFocusChanged(focused, direction, previouslyFocusedRect); 3759 } 3760 3761 /** 3762 * @hide 3763 */ 3764 @Override 3765 protected boolean setFrame(int left, int top, int right, int bottom) { 3766 boolean changed = super.setFrame(left, top, right, bottom); 3767 if (!changed && mHeightCanMeasure) { 3768 // When mHeightCanMeasure is true, we will set mLastHeightSent to 0 3769 // in WebViewCore after we get the first layout. We do call 3770 // requestLayout() when we get contentSizeChanged(). But the View 3771 // system won't call onSizeChanged if the dimension is not changed. 3772 // In this case, we need to call sendViewSizeZoom() explicitly to 3773 // notify the WebKit about the new dimensions. 3774 sendViewSizeZoom(); 3775 } 3776 return changed; 3777 } 3778 3779 @Override 3780 protected void onSizeChanged(int w, int h, int ow, int oh) { 3781 super.onSizeChanged(w, h, ow, oh); 3782 // Center zooming to the center of the screen. 3783 if (mZoomScale == 0) { // unless we're already zooming 3784 mZoomCenterX = getViewWidth() * .5f; 3785 mZoomCenterY = getViewHeight() * .5f; 3786 } 3787 3788 // adjust the max viewport width depending on the view dimensions. This 3789 // is to ensure the scaling is not going insane. So do not shrink it if 3790 // the view size is temporarily smaller, e.g. when soft keyboard is up. 3791 int newMaxViewportWidth = (int) (Math.max(w, h) / DEFAULT_MIN_ZOOM_SCALE); 3792 if (newMaxViewportWidth > sMaxViewportWidth) { 3793 sMaxViewportWidth = newMaxViewportWidth; 3794 } 3795 3796 // update mMinZoomScale if the minimum zoom scale is not fixed 3797 if (!mMinZoomScaleFixed) { 3798 // when change from narrow screen to wide screen, the new viewWidth 3799 // can be wider than the old content width. We limit the minimum 3800 // scale to 1.0f. The proper minimum scale will be calculated when 3801 // the new picture shows up. 3802 mMinZoomScale = Math.min(1.0f, (float) getViewWidth() 3803 / (mDrawHistory ? mHistoryPicture.getWidth() 3804 : mZoomOverviewWidth)); 3805 if (mInitialScaleInPercent > 0) { 3806 // limit the minZoomScale to the initialScale if it is set 3807 float initialScale = mInitialScaleInPercent / 100.0f; 3808 if (mMinZoomScale > initialScale) { 3809 mMinZoomScale = initialScale; 3810 } 3811 } 3812 } 3813 3814 // onSizeChanged() is called during WebView layout. And any 3815 // requestLayout() is blocked during layout. As setNewZoomScale() will 3816 // call its child View to reposition itself through ViewManager's 3817 // scaleAll(), we need to post a Runnable to ensure requestLayout(). 3818 post(new Runnable() { 3819 public void run() { 3820 // we always force, in case our height changed, in which case we 3821 // still want to send the notification over to webkit 3822 setNewZoomScale(mActualScale, true); 3823 } 3824 }); 3825 } 3826 3827 @Override 3828 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 3829 super.onScrollChanged(l, t, oldl, oldt); 3830 3831 sendOurVisibleRect(); 3832 } 3833 3834 3835 @Override 3836 public boolean dispatchKeyEvent(KeyEvent event) { 3837 boolean dispatch = true; 3838 3839 if (!inEditingMode()) { 3840 if (event.getAction() == KeyEvent.ACTION_DOWN) { 3841 mGotKeyDown = true; 3842 } else { 3843 if (!mGotKeyDown) { 3844 /* 3845 * We got a key up for which we were not the recipient of 3846 * the original key down. Don't give it to the view. 3847 */ 3848 dispatch = false; 3849 } 3850 mGotKeyDown = false; 3851 } 3852 } 3853 3854 if (dispatch) { 3855 return super.dispatchKeyEvent(event); 3856 } else { 3857 // We didn't dispatch, so let something else handle the key 3858 return false; 3859 } 3860 } 3861 3862 // Here are the snap align logic: 3863 // 1. If it starts nearly horizontally or vertically, snap align; 3864 // 2. If there is a dramitic direction change, let it go; 3865 // 3. If there is a same direction back and forth, lock it. 3866 3867 // adjustable parameters 3868 private int mMinLockSnapReverseDistance; 3869 private static final float MAX_SLOPE_FOR_DIAG = 1.5f; 3870 private static final int MIN_BREAK_SNAP_CROSS_DISTANCE = 80; 3871 3872 private static int sign(float x) { 3873 return x > 0 ? 1 : (x < 0 ? -1 : 0); 3874 } 3875 3876 // if the page can scroll <= this value, we won't allow the drag tracker 3877 // to have any effect. 3878 private static final int MIN_SCROLL_AMOUNT_TO_DISABLE_DRAG_TRACKER = 4; 3879 3880 private class DragTrackerHandler { 3881 private final DragTracker mProxy; 3882 private final float mStartY, mStartX; 3883 private final float mMinDY, mMinDX; 3884 private final float mMaxDY, mMaxDX; 3885 private float mCurrStretchY, mCurrStretchX; 3886 private int mSX, mSY; 3887 3888 public DragTrackerHandler(float x, float y, DragTracker proxy) { 3889 mProxy = proxy; 3890 3891 int docBottom = computeVerticalScrollRange() + getTitleHeight(); 3892 int viewTop = getScrollY(); 3893 int viewBottom = viewTop + getHeight(); 3894 3895 mStartY = y; 3896 mMinDY = -viewTop; 3897 mMaxDY = docBottom - viewBottom; 3898 3899 if (DebugFlags.DRAG_TRACKER) { 3900 Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, " dragtracker y= " + y + 3901 " up/down= " + mMinDY + " " + mMaxDY); 3902 } 3903 3904 int docRight = computeHorizontalScrollRange(); 3905 int viewLeft = getScrollX(); 3906 int viewRight = viewLeft + getWidth(); 3907 mStartX = x; 3908 mMinDX = -viewLeft; 3909 mMaxDX = docRight - viewRight; 3910 3911 mProxy.onStartDrag(x, y); 3912 3913 // ensure we buildBitmap at least once 3914 mSX = -99999; 3915 } 3916 3917 private float computeStretch(float delta, float min, float max) { 3918 float stretch = 0; 3919 if (max - min > MIN_SCROLL_AMOUNT_TO_DISABLE_DRAG_TRACKER) { 3920 if (delta < min) { 3921 stretch = delta - min; 3922 } else if (delta > max) { 3923 stretch = delta - max; 3924 } 3925 } 3926 return stretch; 3927 } 3928 3929 public void dragTo(float x, float y) { 3930 float sy = computeStretch(mStartY - y, mMinDY, mMaxDY); 3931 float sx = computeStretch(mStartX - x, mMinDX, mMaxDX); 3932 3933 if (mCurrStretchX != sx || mCurrStretchY != sy) { 3934 mCurrStretchX = sx; 3935 mCurrStretchY = sy; 3936 if (DebugFlags.DRAG_TRACKER) { 3937 Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, "---- stretch " + sx + 3938 " " + sy); 3939 } 3940 if (mProxy.onStretchChange(sx, sy)) { 3941 invalidate(); 3942 } 3943 } 3944 } 3945 3946 public void stopDrag() { 3947 if (DebugFlags.DRAG_TRACKER) { 3948 Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, "----- stopDrag"); 3949 } 3950 mProxy.onStopDrag(); 3951 } 3952 3953 private int hiddenHeightOfTitleBar() { 3954 return getTitleHeight() - getVisibleTitleHeight(); 3955 } 3956 3957 // need a way to know if 565 or 8888 is the right config for 3958 // capturing the display and giving it to the drag proxy 3959 private Bitmap.Config offscreenBitmapConfig() { 3960 // hard code 565 for now 3961 return Bitmap.Config.RGB_565; 3962 } 3963 3964 /* If the tracker draws, then this returns true, otherwise it will 3965 return false, and draw nothing. 3966 */ 3967 public boolean draw(Canvas canvas) { 3968 if (mCurrStretchX != 0 || mCurrStretchY != 0) { 3969 int sx = getScrollX(); 3970 int sy = getScrollY() - hiddenHeightOfTitleBar(); 3971 3972 if (mSX != sx || mSY != sy) { 3973 buildBitmap(sx, sy); 3974 mSX = sx; 3975 mSY = sy; 3976 } 3977 3978 int count = canvas.save(Canvas.MATRIX_SAVE_FLAG); 3979 canvas.translate(sx, sy); 3980 mProxy.onDraw(canvas); 3981 canvas.restoreToCount(count); 3982 return true; 3983 } 3984 if (DebugFlags.DRAG_TRACKER) { 3985 Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, " -- draw false " + 3986 mCurrStretchX + " " + mCurrStretchY); 3987 } 3988 return false; 3989 } 3990 3991 private void buildBitmap(int sx, int sy) { 3992 int w = getWidth(); 3993 int h = getViewHeight(); 3994 Bitmap bm = Bitmap.createBitmap(w, h, offscreenBitmapConfig()); 3995 Canvas canvas = new Canvas(bm); 3996 canvas.translate(-sx, -sy); 3997 drawContent(canvas); 3998 3999 if (DebugFlags.DRAG_TRACKER) { 4000 Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, "--- buildBitmap " + sx + 4001 " " + sy + " " + w + " " + h); 4002 } 4003 mProxy.onBitmapChange(bm); 4004 } 4005 } 4006 4007 /** @hide */ 4008 public static class DragTracker { 4009 public void onStartDrag(float x, float y) {} 4010 public boolean onStretchChange(float sx, float sy) { 4011 // return true to have us inval the view 4012 return false; 4013 } 4014 public void onStopDrag() {} 4015 public void onBitmapChange(Bitmap bm) {} 4016 public void onDraw(Canvas canvas) {} 4017 } 4018 4019 /** @hide */ 4020 public DragTracker getDragTracker() { 4021 return mDragTracker; 4022 } 4023 4024 /** @hide */ 4025 public void setDragTracker(DragTracker tracker) { 4026 mDragTracker = tracker; 4027 } 4028 4029 private DragTracker mDragTracker; 4030 private DragTrackerHandler mDragTrackerHandler; 4031 4032 @Override 4033 public boolean onTouchEvent(MotionEvent ev) { 4034 if (mNativeClass == 0 || !isClickable() || !isLongClickable()) { 4035 return false; 4036 } 4037 4038 if (DebugFlags.WEB_VIEW) { 4039 Log.v(LOGTAG, ev + " at " + ev.getEventTime() + " mTouchMode=" 4040 + mTouchMode); 4041 } 4042 4043 int action = ev.getAction(); 4044 float x = ev.getX(); 4045 float y = ev.getY(); 4046 long eventTime = ev.getEventTime(); 4047 4048 // Due to the touch screen edge effect, a touch closer to the edge 4049 // always snapped to the edge. As getViewWidth() can be different from 4050 // getWidth() due to the scrollbar, adjusting the point to match 4051 // getViewWidth(). Same applied to the height. 4052 if (x > getViewWidth() - 1) { 4053 x = getViewWidth() - 1; 4054 } 4055 if (y > getViewHeightWithTitle() - 1) { 4056 y = getViewHeightWithTitle() - 1; 4057 } 4058 4059 // pass the touch events from UI thread to WebCore thread 4060 if (mForwardTouchEvents && (action != MotionEvent.ACTION_MOVE 4061 || eventTime - mLastSentTouchTime > TOUCH_SENT_INTERVAL)) { 4062 WebViewCore.TouchEventData ted = new WebViewCore.TouchEventData(); 4063 ted.mAction = action; 4064 ted.mX = viewToContentX((int) x + mScrollX); 4065 ted.mY = viewToContentY((int) y + mScrollY); 4066 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 4067 mLastSentTouchTime = eventTime; 4068 } 4069 4070 float fDeltaX = mLastTouchX - x; 4071 float fDeltaY = mLastTouchY - y; 4072 int deltaX = (int) fDeltaX; 4073 int deltaY = (int) fDeltaY; 4074 4075 switch (action) { 4076 case MotionEvent.ACTION_DOWN: { 4077 mPreventDrag = PREVENT_DRAG_NO; 4078 if (!mScroller.isFinished()) { 4079 // stop the current scroll animation, but if this is 4080 // the start of a fling, allow it to add to the current 4081 // fling's velocity 4082 mScroller.abortAnimation(); 4083 mTouchMode = TOUCH_DRAG_START_MODE; 4084 mPrivateHandler.removeMessages(RESUME_WEBCORE_UPDATE); 4085 } else if (mShiftIsPressed) { 4086 mSelectX = mScrollX + (int) x; 4087 mSelectY = mScrollY + (int) y; 4088 mTouchMode = TOUCH_SELECT_MODE; 4089 if (DebugFlags.WEB_VIEW) { 4090 Log.v(LOGTAG, "select=" + mSelectX + "," + mSelectY); 4091 } 4092 nativeMoveSelection(viewToContentX(mSelectX), 4093 viewToContentY(mSelectY), false); 4094 mTouchSelection = mExtendSelection = true; 4095 invalidate(); // draw the i-beam instead of the arrow 4096 } else if (mPrivateHandler.hasMessages(RELEASE_SINGLE_TAP)) { 4097 mPrivateHandler.removeMessages(RELEASE_SINGLE_TAP); 4098 if (deltaX * deltaX + deltaY * deltaY < mDoubleTapSlopSquare) { 4099 mTouchMode = TOUCH_DOUBLE_TAP_MODE; 4100 } else { 4101 // commit the short press action for the previous tap 4102 doShortPress(); 4103 // continue, mTouchMode should be still TOUCH_INIT_MODE 4104 } 4105 } else { 4106 mTouchMode = TOUCH_INIT_MODE; 4107 mPreventDrag = mForwardTouchEvents ? PREVENT_DRAG_MAYBE_YES 4108 : PREVENT_DRAG_NO; 4109 mPreventLongPress = false; 4110 mPreventDoubleTap = false; 4111 mWebViewCore.sendMessage( 4112 EventHub.UPDATE_FRAME_CACHE_IF_LOADING); 4113 if (mLogEvent && eventTime - mLastTouchUpTime < 1000) { 4114 EventLog.writeEvent(EVENT_LOG_DOUBLE_TAP_DURATION, 4115 (eventTime - mLastTouchUpTime), eventTime); 4116 } 4117 } 4118 // Trigger the link 4119 if (mTouchMode == TOUCH_INIT_MODE 4120 || mTouchMode == TOUCH_DOUBLE_TAP_MODE) { 4121 mPrivateHandler.sendMessageDelayed(mPrivateHandler 4122 .obtainMessage(SWITCH_TO_SHORTPRESS), TAP_TIMEOUT); 4123 } 4124 // Remember where the motion event started 4125 mLastTouchX = x; 4126 mLastTouchY = y; 4127 mLastTouchTime = eventTime; 4128 mVelocityTracker = VelocityTracker.obtain(); 4129 mSnapScrollMode = SNAP_NONE; 4130 if (mDragTracker != null) { 4131 mDragTrackerHandler = new DragTrackerHandler(x, y, 4132 mDragTracker); 4133 } 4134 break; 4135 } 4136 case MotionEvent.ACTION_MOVE: { 4137 if (mTouchMode == TOUCH_DONE_MODE) { 4138 // no dragging during scroll zoom animation 4139 break; 4140 } 4141 mVelocityTracker.addMovement(ev); 4142 4143 if (mTouchMode != TOUCH_DRAG_MODE) { 4144 if (mTouchMode == TOUCH_SELECT_MODE) { 4145 mSelectX = mScrollX + (int) x; 4146 mSelectY = mScrollY + (int) y; 4147 if (DebugFlags.WEB_VIEW) { 4148 Log.v(LOGTAG, "xtend=" + mSelectX + "," + mSelectY); 4149 } 4150 nativeMoveSelection(viewToContentX(mSelectX), 4151 viewToContentY(mSelectY), true); 4152 invalidate(); 4153 break; 4154 } 4155 if ((deltaX * deltaX + deltaY * deltaY) < mTouchSlopSquare) { 4156 break; 4157 } 4158 if (mPreventDrag == PREVENT_DRAG_MAYBE_YES) { 4159 // track mLastTouchTime as we may need to do fling at 4160 // ACTION_UP 4161 mLastTouchTime = eventTime; 4162 break; 4163 } 4164 if (mTouchMode == TOUCH_SHORTPRESS_MODE 4165 || mTouchMode == TOUCH_SHORTPRESS_START_MODE) { 4166 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 4167 } else if (mTouchMode == TOUCH_INIT_MODE 4168 || mTouchMode == TOUCH_DOUBLE_TAP_MODE) { 4169 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 4170 } 4171 if (mFullScreenHolder != null) { 4172 // in full screen mode, the WebView can't be panned. 4173 mTouchMode = TOUCH_DONE_MODE; 4174 break; 4175 } 4176 4177 // if it starts nearly horizontal or vertical, enforce it 4178 int ax = Math.abs(deltaX); 4179 int ay = Math.abs(deltaY); 4180 if (ax > MAX_SLOPE_FOR_DIAG * ay) { 4181 mSnapScrollMode = SNAP_X; 4182 mSnapPositive = deltaX > 0; 4183 } else if (ay > MAX_SLOPE_FOR_DIAG * ax) { 4184 mSnapScrollMode = SNAP_Y; 4185 mSnapPositive = deltaY > 0; 4186 } 4187 4188 mTouchMode = TOUCH_DRAG_MODE; 4189 mLastTouchX = x; 4190 mLastTouchY = y; 4191 fDeltaX = 0.0f; 4192 fDeltaY = 0.0f; 4193 deltaX = 0; 4194 deltaY = 0; 4195 4196 WebViewCore.pauseUpdate(mWebViewCore); 4197 if (!mDragFromTextInput) { 4198 nativeHideCursor(); 4199 } 4200 WebSettings settings = getSettings(); 4201 if (settings.supportZoom() 4202 && settings.getBuiltInZoomControls() 4203 && !mZoomButtonsController.isVisible() 4204 && mMinZoomScale < mMaxZoomScale) { 4205 mZoomButtonsController.setVisible(true); 4206 int count = settings.getDoubleTapToastCount(); 4207 if (mInZoomOverview && count > 0) { 4208 settings.setDoubleTapToastCount(--count); 4209 Toast.makeText(mContext, 4210 com.android.internal.R.string.double_tap_toast, 4211 Toast.LENGTH_LONG).show(); 4212 } 4213 } 4214 } 4215 4216 // do pan 4217 int newScrollX = pinLocX(mScrollX + deltaX); 4218 int newDeltaX = newScrollX - mScrollX; 4219 if (deltaX != newDeltaX) { 4220 deltaX = newDeltaX; 4221 fDeltaX = (float) newDeltaX; 4222 } 4223 int newScrollY = pinLocY(mScrollY + deltaY); 4224 int newDeltaY = newScrollY - mScrollY; 4225 if (deltaY != newDeltaY) { 4226 deltaY = newDeltaY; 4227 fDeltaY = (float) newDeltaY; 4228 } 4229 boolean done = false; 4230 boolean keepScrollBarsVisible = false; 4231 if (Math.abs(fDeltaX) < 1.0f && Math.abs(fDeltaY) < 1.0f) { 4232 keepScrollBarsVisible = done = true; 4233 } else { 4234 if (mSnapScrollMode == SNAP_X || mSnapScrollMode == SNAP_Y) { 4235 int ax = Math.abs(deltaX); 4236 int ay = Math.abs(deltaY); 4237 if (mSnapScrollMode == SNAP_X) { 4238 // radical change means getting out of snap mode 4239 if (ay > MAX_SLOPE_FOR_DIAG * ax 4240 && ay > MIN_BREAK_SNAP_CROSS_DISTANCE) { 4241 mSnapScrollMode = SNAP_NONE; 4242 } 4243 // reverse direction means lock in the snap mode 4244 if (ax > MAX_SLOPE_FOR_DIAG * ay && 4245 (mSnapPositive 4246 ? deltaX < -mMinLockSnapReverseDistance 4247 : deltaX > mMinLockSnapReverseDistance)) { 4248 mSnapScrollMode |= SNAP_LOCK; 4249 } 4250 } else { 4251 // radical change means getting out of snap mode 4252 if (ax > MAX_SLOPE_FOR_DIAG * ay 4253 && ax > MIN_BREAK_SNAP_CROSS_DISTANCE) { 4254 mSnapScrollMode = SNAP_NONE; 4255 } 4256 // reverse direction means lock in the snap mode 4257 if (ay > MAX_SLOPE_FOR_DIAG * ax && 4258 (mSnapPositive 4259 ? deltaY < -mMinLockSnapReverseDistance 4260 : deltaY > mMinLockSnapReverseDistance)) { 4261 mSnapScrollMode |= SNAP_LOCK; 4262 } 4263 } 4264 } 4265 if (mSnapScrollMode != SNAP_NONE) { 4266 if ((mSnapScrollMode & SNAP_X) == SNAP_X) { 4267 deltaY = 0; 4268 } else { 4269 deltaX = 0; 4270 } 4271 } 4272 if ((deltaX | deltaY) != 0) { 4273 scrollBy(deltaX, deltaY); 4274 if (deltaX != 0) { 4275 mLastTouchX = x; 4276 } 4277 if (deltaY != 0) { 4278 mLastTouchY = y; 4279 } 4280 mHeldMotionless = MOTIONLESS_FALSE; 4281 } else { 4282 // keep the scrollbar on the screen even there is no 4283 // scroll 4284 keepScrollBarsVisible = true; 4285 } 4286 mLastTouchTime = eventTime; 4287 mUserScroll = true; 4288 } 4289 4290 if (!getSettings().getBuiltInZoomControls()) { 4291 boolean showPlusMinus = mMinZoomScale < mMaxZoomScale; 4292 if (mZoomControls != null && showPlusMinus) { 4293 if (mZoomControls.getVisibility() == View.VISIBLE) { 4294 mPrivateHandler.removeCallbacks(mZoomControlRunnable); 4295 } else { 4296 mZoomControls.show(showPlusMinus, false); 4297 } 4298 mPrivateHandler.postDelayed(mZoomControlRunnable, 4299 ZOOM_CONTROLS_TIMEOUT); 4300 } 4301 } 4302 4303 if (mDragTrackerHandler != null) { 4304 mDragTrackerHandler.dragTo(x, y); 4305 } 4306 4307 if (keepScrollBarsVisible) { 4308 if (mHeldMotionless != MOTIONLESS_TRUE) { 4309 mHeldMotionless = MOTIONLESS_TRUE; 4310 invalidate(); 4311 } 4312 // keep the scrollbar on the screen even there is no scroll 4313 awakenScrollBars(ViewConfiguration.getScrollDefaultDelay(), 4314 false); 4315 // return false to indicate that we can't pan out of the 4316 // view space 4317 return !done; 4318 } 4319 break; 4320 } 4321 case MotionEvent.ACTION_UP: { 4322 if (mDragTrackerHandler != null) { 4323 mDragTrackerHandler.stopDrag(); 4324 mDragTrackerHandler = null; 4325 } 4326 mLastTouchUpTime = eventTime; 4327 switch (mTouchMode) { 4328 case TOUCH_DOUBLE_TAP_MODE: // double tap 4329 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 4330 mTouchMode = TOUCH_DONE_MODE; 4331 if (mPreventDoubleTap) { 4332 WebViewCore.TouchEventData ted 4333 = new WebViewCore.TouchEventData(); 4334 ted.mAction = WebViewCore.ACTION_DOUBLETAP; 4335 ted.mX = viewToContentX((int) x + mScrollX); 4336 ted.mY = viewToContentY((int) y + mScrollY); 4337 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 4338 } else if (mFullScreenHolder == null) { 4339 doDoubleTap(); 4340 } 4341 break; 4342 case TOUCH_SELECT_MODE: 4343 commitCopy(); 4344 mTouchSelection = false; 4345 break; 4346 case TOUCH_INIT_MODE: // tap 4347 case TOUCH_SHORTPRESS_START_MODE: 4348 case TOUCH_SHORTPRESS_MODE: 4349 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 4350 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 4351 if ((deltaX * deltaX + deltaY * deltaY) > mTouchSlopSquare) { 4352 Log.w(LOGTAG, "Miss a drag as we are waiting for" + 4353 " WebCore's response for touch down."); 4354 if (mFullScreenHolder == null 4355 && (computeHorizontalScrollExtent() < computeHorizontalScrollRange() 4356 || computeVerticalScrollExtent() < computeVerticalScrollRange())) { 4357 // we will not rewrite drag code here, but we 4358 // will try fling if it applies. 4359 WebViewCore.pauseUpdate(mWebViewCore); 4360 // fall through to TOUCH_DRAG_MODE 4361 } else { 4362 break; 4363 } 4364 } else { 4365 if (mPreventDrag == PREVENT_DRAG_MAYBE_YES) { 4366 // if mPreventDrag is not confirmed, treat it as 4367 // no so that it won't block tap or double tap. 4368 mPreventDrag = PREVENT_DRAG_NO; 4369 mPreventLongPress = false; 4370 mPreventDoubleTap = false; 4371 } 4372 if (mPreventDrag == PREVENT_DRAG_NO) { 4373 if (mTouchMode == TOUCH_INIT_MODE) { 4374 mPrivateHandler.sendMessageDelayed( 4375 mPrivateHandler.obtainMessage( 4376 RELEASE_SINGLE_TAP), 4377 ViewConfiguration.getDoubleTapTimeout()); 4378 } else { 4379 mTouchMode = TOUCH_DONE_MODE; 4380 doShortPress(); 4381 } 4382 } 4383 break; 4384 } 4385 case TOUCH_DRAG_MODE: 4386 mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS); 4387 mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS); 4388 mHeldMotionless = MOTIONLESS_TRUE; 4389 // redraw in high-quality, as we're done dragging 4390 invalidate(); 4391 // if the user waits a while w/o moving before the 4392 // up, we don't want to do a fling 4393 if (eventTime - mLastTouchTime <= MIN_FLING_TIME) { 4394 mVelocityTracker.addMovement(ev); 4395 doFling(); 4396 break; 4397 } 4398 mLastVelocity = 0; 4399 WebViewCore.resumeUpdate(mWebViewCore); 4400 break; 4401 case TOUCH_DRAG_START_MODE: 4402 case TOUCH_DONE_MODE: 4403 // do nothing 4404 break; 4405 } 4406 // we also use mVelocityTracker == null to tell us that we are 4407 // not "moving around", so we can take the slower/prettier 4408 // mode in the drawing code 4409 if (mVelocityTracker != null) { 4410 mVelocityTracker.recycle(); 4411 mVelocityTracker = null; 4412 } 4413 break; 4414 } 4415 case MotionEvent.ACTION_CANCEL: { 4416 if (mDragTrackerHandler != null) { 4417 mDragTrackerHandler.stopDrag(); 4418 mDragTrackerHandler = null; 4419 } 4420 // we also use mVelocityTracker == null to tell us that we are 4421 // not "moving around", so we can take the slower/prettier 4422 // mode in the drawing code 4423 if (mVelocityTracker != null) { 4424 mVelocityTracker.recycle(); 4425 mVelocityTracker = null; 4426 } 4427 if (mTouchMode == TOUCH_DRAG_MODE) { 4428 WebViewCore.resumeUpdate(mWebViewCore); 4429 } 4430 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 4431 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 4432 mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS); 4433 mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS); 4434 mHeldMotionless = MOTIONLESS_TRUE; 4435 mTouchMode = TOUCH_DONE_MODE; 4436 nativeHideCursor(); 4437 break; 4438 } 4439 } 4440 return true; 4441 } 4442 4443 private long mTrackballFirstTime = 0; 4444 private long mTrackballLastTime = 0; 4445 private float mTrackballRemainsX = 0.0f; 4446 private float mTrackballRemainsY = 0.0f; 4447 private int mTrackballXMove = 0; 4448 private int mTrackballYMove = 0; 4449 private boolean mExtendSelection = false; 4450 private boolean mTouchSelection = false; 4451 private static final int TRACKBALL_KEY_TIMEOUT = 1000; 4452 private static final int TRACKBALL_TIMEOUT = 200; 4453 private static final int TRACKBALL_WAIT = 100; 4454 private static final int TRACKBALL_SCALE = 400; 4455 private static final int TRACKBALL_SCROLL_COUNT = 5; 4456 private static final int TRACKBALL_MOVE_COUNT = 10; 4457 private static final int TRACKBALL_MULTIPLIER = 3; 4458 private static final int SELECT_CURSOR_OFFSET = 16; 4459 private int mSelectX = 0; 4460 private int mSelectY = 0; 4461 private boolean mFocusSizeChanged = false; 4462 private boolean mShiftIsPressed = false; 4463 private boolean mTrackballDown = false; 4464 private long mTrackballUpTime = 0; 4465 private long mLastCursorTime = 0; 4466 private Rect mLastCursorBounds; 4467 4468 // Set by default; BrowserActivity clears to interpret trackball data 4469 // directly for movement. Currently, the framework only passes 4470 // arrow key events, not trackball events, from one child to the next 4471 private boolean mMapTrackballToArrowKeys = true; 4472 4473 public void setMapTrackballToArrowKeys(boolean setMap) { 4474 mMapTrackballToArrowKeys = setMap; 4475 } 4476 4477 void resetTrackballTime() { 4478 mTrackballLastTime = 0; 4479 } 4480 4481 @Override 4482 public boolean onTrackballEvent(MotionEvent ev) { 4483 long time = ev.getEventTime(); 4484 if ((ev.getMetaState() & KeyEvent.META_ALT_ON) != 0) { 4485 if (ev.getY() > 0) pageDown(true); 4486 if (ev.getY() < 0) pageUp(true); 4487 return true; 4488 } 4489 if (ev.getAction() == MotionEvent.ACTION_DOWN) { 4490 if (mShiftIsPressed) { 4491 return true; // discard press if copy in progress 4492 } 4493 mTrackballDown = true; 4494 if (mNativeClass == 0) { 4495 return false; 4496 } 4497 nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true); 4498 if (time - mLastCursorTime <= TRACKBALL_TIMEOUT 4499 && !mLastCursorBounds.equals(nativeGetCursorRingBounds())) { 4500 nativeSelectBestAt(mLastCursorBounds); 4501 } 4502 if (DebugFlags.WEB_VIEW) { 4503 Log.v(LOGTAG, "onTrackballEvent down ev=" + ev 4504 + " time=" + time 4505 + " mLastCursorTime=" + mLastCursorTime); 4506 } 4507 if (isInTouchMode()) requestFocusFromTouch(); 4508 return false; // let common code in onKeyDown at it 4509 } 4510 if (ev.getAction() == MotionEvent.ACTION_UP) { 4511 // LONG_PRESS_CENTER is set in common onKeyDown 4512 mPrivateHandler.removeMessages(LONG_PRESS_CENTER); 4513 mTrackballDown = false; 4514 mTrackballUpTime = time; 4515 if (mShiftIsPressed) { 4516 if (mExtendSelection) { 4517 commitCopy(); 4518 } else { 4519 mExtendSelection = true; 4520 invalidate(); // draw the i-beam instead of the arrow 4521 } 4522 return true; // discard press if copy in progress 4523 } 4524 if (DebugFlags.WEB_VIEW) { 4525 Log.v(LOGTAG, "onTrackballEvent up ev=" + ev 4526 + " time=" + time 4527 ); 4528 } 4529 return false; // let common code in onKeyUp at it 4530 } 4531 if (mMapTrackballToArrowKeys && mShiftIsPressed == false) { 4532 if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent gmail quit"); 4533 return false; 4534 } 4535 if (mTrackballDown) { 4536 if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent down quit"); 4537 return true; // discard move if trackball is down 4538 } 4539 if (time - mTrackballUpTime < TRACKBALL_TIMEOUT) { 4540 if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent up timeout quit"); 4541 return true; 4542 } 4543 // TODO: alternatively we can do panning as touch does 4544 switchOutDrawHistory(); 4545 if (time - mTrackballLastTime > TRACKBALL_TIMEOUT) { 4546 if (DebugFlags.WEB_VIEW) { 4547 Log.v(LOGTAG, "onTrackballEvent time=" 4548 + time + " last=" + mTrackballLastTime); 4549 } 4550 mTrackballFirstTime = time; 4551 mTrackballXMove = mTrackballYMove = 0; 4552 } 4553 mTrackballLastTime = time; 4554 if (DebugFlags.WEB_VIEW) { 4555 Log.v(LOGTAG, "onTrackballEvent ev=" + ev + " time=" + time); 4556 } 4557 mTrackballRemainsX += ev.getX(); 4558 mTrackballRemainsY += ev.getY(); 4559 doTrackball(time); 4560 return true; 4561 } 4562 4563 void moveSelection(float xRate, float yRate) { 4564 if (mNativeClass == 0) 4565 return; 4566 int width = getViewWidth(); 4567 int height = getViewHeight(); 4568 mSelectX += xRate; 4569 mSelectY += yRate; 4570 int maxX = width + mScrollX; 4571 int maxY = height + mScrollY; 4572 mSelectX = Math.min(maxX, Math.max(mScrollX - SELECT_CURSOR_OFFSET 4573 , mSelectX)); 4574 mSelectY = Math.min(maxY, Math.max(mScrollY - SELECT_CURSOR_OFFSET 4575 , mSelectY)); 4576 if (DebugFlags.WEB_VIEW) { 4577 Log.v(LOGTAG, "moveSelection" 4578 + " mSelectX=" + mSelectX 4579 + " mSelectY=" + mSelectY 4580 + " mScrollX=" + mScrollX 4581 + " mScrollY=" + mScrollY 4582 + " xRate=" + xRate 4583 + " yRate=" + yRate 4584 ); 4585 } 4586 nativeMoveSelection(viewToContentX(mSelectX), 4587 viewToContentY(mSelectY), mExtendSelection); 4588 int scrollX = mSelectX < mScrollX ? -SELECT_CURSOR_OFFSET 4589 : mSelectX > maxX - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET 4590 : 0; 4591 int scrollY = mSelectY < mScrollY ? -SELECT_CURSOR_OFFSET 4592 : mSelectY > maxY - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET 4593 : 0; 4594 pinScrollBy(scrollX, scrollY, true, 0); 4595 Rect select = new Rect(mSelectX, mSelectY, mSelectX + 1, mSelectY + 1); 4596 requestRectangleOnScreen(select); 4597 invalidate(); 4598 } 4599 4600 private int scaleTrackballX(float xRate, int width) { 4601 int xMove = (int) (xRate / TRACKBALL_SCALE * width); 4602 int nextXMove = xMove; 4603 if (xMove > 0) { 4604 if (xMove > mTrackballXMove) { 4605 xMove -= mTrackballXMove; 4606 } 4607 } else if (xMove < mTrackballXMove) { 4608 xMove -= mTrackballXMove; 4609 } 4610 mTrackballXMove = nextXMove; 4611 return xMove; 4612 } 4613 4614 private int scaleTrackballY(float yRate, int height) { 4615 int yMove = (int) (yRate / TRACKBALL_SCALE * height); 4616 int nextYMove = yMove; 4617 if (yMove > 0) { 4618 if (yMove > mTrackballYMove) { 4619 yMove -= mTrackballYMove; 4620 } 4621 } else if (yMove < mTrackballYMove) { 4622 yMove -= mTrackballYMove; 4623 } 4624 mTrackballYMove = nextYMove; 4625 return yMove; 4626 } 4627 4628 private int keyCodeToSoundsEffect(int keyCode) { 4629 switch(keyCode) { 4630 case KeyEvent.KEYCODE_DPAD_UP: 4631 return SoundEffectConstants.NAVIGATION_UP; 4632 case KeyEvent.KEYCODE_DPAD_RIGHT: 4633 return SoundEffectConstants.NAVIGATION_RIGHT; 4634 case KeyEvent.KEYCODE_DPAD_DOWN: 4635 return SoundEffectConstants.NAVIGATION_DOWN; 4636 case KeyEvent.KEYCODE_DPAD_LEFT: 4637 return SoundEffectConstants.NAVIGATION_LEFT; 4638 } 4639 throw new IllegalArgumentException("keyCode must be one of " + 4640 "{KEYCODE_DPAD_UP, KEYCODE_DPAD_RIGHT, KEYCODE_DPAD_DOWN, " + 4641 "KEYCODE_DPAD_LEFT}."); 4642 } 4643 4644 private void doTrackball(long time) { 4645 int elapsed = (int) (mTrackballLastTime - mTrackballFirstTime); 4646 if (elapsed == 0) { 4647 elapsed = TRACKBALL_TIMEOUT; 4648 } 4649 float xRate = mTrackballRemainsX * 1000 / elapsed; 4650 float yRate = mTrackballRemainsY * 1000 / elapsed; 4651 int viewWidth = getViewWidth(); 4652 int viewHeight = getViewHeight(); 4653 if (mShiftIsPressed) { 4654 moveSelection(scaleTrackballX(xRate, viewWidth), 4655 scaleTrackballY(yRate, viewHeight)); 4656 mTrackballRemainsX = mTrackballRemainsY = 0; 4657 return; 4658 } 4659 float ax = Math.abs(xRate); 4660 float ay = Math.abs(yRate); 4661 float maxA = Math.max(ax, ay); 4662 if (DebugFlags.WEB_VIEW) { 4663 Log.v(LOGTAG, "doTrackball elapsed=" + elapsed 4664 + " xRate=" + xRate 4665 + " yRate=" + yRate 4666 + " mTrackballRemainsX=" + mTrackballRemainsX 4667 + " mTrackballRemainsY=" + mTrackballRemainsY); 4668 } 4669 int width = mContentWidth - viewWidth; 4670 int height = mContentHeight - viewHeight; 4671 if (width < 0) width = 0; 4672 if (height < 0) height = 0; 4673 ax = Math.abs(mTrackballRemainsX * TRACKBALL_MULTIPLIER); 4674 ay = Math.abs(mTrackballRemainsY * TRACKBALL_MULTIPLIER); 4675 maxA = Math.max(ax, ay); 4676 int count = Math.max(0, (int) maxA); 4677 int oldScrollX = mScrollX; 4678 int oldScrollY = mScrollY; 4679 if (count > 0) { 4680 int selectKeyCode = ax < ay ? mTrackballRemainsY < 0 ? 4681 KeyEvent.KEYCODE_DPAD_UP : KeyEvent.KEYCODE_DPAD_DOWN : 4682 mTrackballRemainsX < 0 ? KeyEvent.KEYCODE_DPAD_LEFT : 4683 KeyEvent.KEYCODE_DPAD_RIGHT; 4684 count = Math.min(count, TRACKBALL_MOVE_COUNT); 4685 if (DebugFlags.WEB_VIEW) { 4686 Log.v(LOGTAG, "doTrackball keyCode=" + selectKeyCode 4687 + " count=" + count 4688 + " mTrackballRemainsX=" + mTrackballRemainsX 4689 + " mTrackballRemainsY=" + mTrackballRemainsY); 4690 } 4691 if (navHandledKey(selectKeyCode, count, false, time, false)) { 4692 playSoundEffect(keyCodeToSoundsEffect(selectKeyCode)); 4693 } 4694 mTrackballRemainsX = mTrackballRemainsY = 0; 4695 } 4696 if (count >= TRACKBALL_SCROLL_COUNT) { 4697 int xMove = scaleTrackballX(xRate, width); 4698 int yMove = scaleTrackballY(yRate, height); 4699 if (DebugFlags.WEB_VIEW) { 4700 Log.v(LOGTAG, "doTrackball pinScrollBy" 4701 + " count=" + count 4702 + " xMove=" + xMove + " yMove=" + yMove 4703 + " mScrollX-oldScrollX=" + (mScrollX-oldScrollX) 4704 + " mScrollY-oldScrollY=" + (mScrollY-oldScrollY) 4705 ); 4706 } 4707 if (Math.abs(mScrollX - oldScrollX) > Math.abs(xMove)) { 4708 xMove = 0; 4709 } 4710 if (Math.abs(mScrollY - oldScrollY) > Math.abs(yMove)) { 4711 yMove = 0; 4712 } 4713 if (xMove != 0 || yMove != 0) { 4714 pinScrollBy(xMove, yMove, true, 0); 4715 } 4716 mUserScroll = true; 4717 } 4718 } 4719 4720 private int computeMaxScrollY() { 4721 int maxContentH = computeVerticalScrollRange() + getTitleHeight(); 4722 return Math.max(maxContentH - getViewHeightWithTitle(), getTitleHeight()); 4723 } 4724 4725 public void flingScroll(int vx, int vy) { 4726 int maxX = Math.max(computeHorizontalScrollRange() - getViewWidth(), 0); 4727 int maxY = computeMaxScrollY(); 4728 4729 mScroller.fling(mScrollX, mScrollY, vx, vy, 0, maxX, 0, maxY); 4730 invalidate(); 4731 } 4732 4733 private void doFling() { 4734 if (mVelocityTracker == null) { 4735 return; 4736 } 4737 int maxX = Math.max(computeHorizontalScrollRange() - getViewWidth(), 0); 4738 int maxY = computeMaxScrollY(); 4739 4740 mVelocityTracker.computeCurrentVelocity(1000, mMaximumFling); 4741 int vx = (int) mVelocityTracker.getXVelocity(); 4742 int vy = (int) mVelocityTracker.getYVelocity(); 4743 4744 if (mSnapScrollMode != SNAP_NONE) { 4745 if ((mSnapScrollMode & SNAP_X) == SNAP_X) { 4746 vy = 0; 4747 } else { 4748 vx = 0; 4749 } 4750 } 4751 4752 if (true /* EMG release: make our fling more like Maps' */) { 4753 // maps cuts their velocity in half 4754 vx = vx * 3 / 4; 4755 vy = vy * 3 / 4; 4756 } 4757 if ((maxX == 0 && vy == 0) || (maxY == 0 && vx == 0)) { 4758 WebViewCore.resumeUpdate(mWebViewCore); 4759 return; 4760 } 4761 float currentVelocity = mScroller.getCurrVelocity(); 4762 if (mLastVelocity > 0 && currentVelocity > 0) { 4763 float deltaR = (float) (Math.abs(Math.atan2(mLastVelY, mLastVelX) 4764 - Math.atan2(vy, vx))); 4765 final float circle = (float) (Math.PI) * 2.0f; 4766 if (deltaR > circle * 0.9f || deltaR < circle * 0.1f) { 4767 vx += currentVelocity * mLastVelX / mLastVelocity; 4768 vy += currentVelocity * mLastVelY / mLastVelocity; 4769 if (DebugFlags.WEB_VIEW) { 4770 Log.v(LOGTAG, "doFling vx= " + vx + " vy=" + vy); 4771 } 4772 } else if (DebugFlags.WEB_VIEW) { 4773 Log.v(LOGTAG, "doFling missed " + deltaR / circle); 4774 } 4775 } else if (DebugFlags.WEB_VIEW) { 4776 Log.v(LOGTAG, "doFling start last=" + mLastVelocity 4777 + " current=" + currentVelocity 4778 + " vx=" + vx + " vy=" + vy 4779 + " maxX=" + maxX + " maxY=" + maxY 4780 + " mScrollX=" + mScrollX + " mScrollY=" + mScrollY); 4781 } 4782 mLastVelX = vx; 4783 mLastVelY = vy; 4784 mLastVelocity = (float) Math.hypot(vx, vy); 4785 4786 mScroller.fling(mScrollX, mScrollY, -vx, -vy, 0, maxX, 0, maxY); 4787 // TODO: duration is calculated based on velocity, if the range is 4788 // small, the animation will stop before duration is up. We may 4789 // want to calculate how long the animation is going to run to precisely 4790 // resume the webcore update. 4791 final int time = mScroller.getDuration(); 4792 mPrivateHandler.sendEmptyMessageDelayed(RESUME_WEBCORE_UPDATE, time); 4793 awakenScrollBars(time); 4794 invalidate(); 4795 } 4796 4797 private boolean zoomWithPreview(float scale) { 4798 float oldScale = mActualScale; 4799 mInitialScrollX = mScrollX; 4800 mInitialScrollY = mScrollY; 4801 4802 // snap to DEFAULT_SCALE if it is close 4803 if (scale > (mDefaultScale - 0.05) && scale < (mDefaultScale + 0.05)) { 4804 scale = mDefaultScale; 4805 } 4806 4807 setNewZoomScale(scale, false); 4808 4809 if (oldScale != mActualScale) { 4810 // use mZoomPickerScale to see zoom preview first 4811 mZoomStart = SystemClock.uptimeMillis(); 4812 mInvInitialZoomScale = 1.0f / oldScale; 4813 mInvFinalZoomScale = 1.0f / mActualScale; 4814 mZoomScale = mActualScale; 4815 if (!mInZoomOverview) { 4816 mLastScale = scale; 4817 } 4818 invalidate(); 4819 return true; 4820 } else { 4821 return false; 4822 } 4823 } 4824 4825 /** 4826 * Returns a view containing zoom controls i.e. +/- buttons. The caller is 4827 * in charge of installing this view to the view hierarchy. This view will 4828 * become visible when the user starts scrolling via touch and fade away if 4829 * the user does not interact with it. 4830 * <p/> 4831 * API version 3 introduces a built-in zoom mechanism that is shown 4832 * automatically by the MapView. This is the preferred approach for 4833 * showing the zoom UI. 4834 * 4835 * @deprecated The built-in zoom mechanism is preferred, see 4836 * {@link WebSettings#setBuiltInZoomControls(boolean)}. 4837 */ 4838 @Deprecated 4839 public View getZoomControls() { 4840 if (!getSettings().supportZoom()) { 4841 Log.w(LOGTAG, "This WebView doesn't support zoom."); 4842 return null; 4843 } 4844 if (mZoomControls == null) { 4845 mZoomControls = createZoomControls(); 4846 4847 /* 4848 * need to be set to VISIBLE first so that getMeasuredHeight() in 4849 * {@link #onSizeChanged()} can return the measured value for proper 4850 * layout. 4851 */ 4852 mZoomControls.setVisibility(View.VISIBLE); 4853 mZoomControlRunnable = new Runnable() { 4854 public void run() { 4855 4856 /* Don't dismiss the controls if the user has 4857 * focus on them. Wait and check again later. 4858 */ 4859 if (!mZoomControls.hasFocus()) { 4860 mZoomControls.hide(); 4861 } else { 4862 mPrivateHandler.removeCallbacks(mZoomControlRunnable); 4863 mPrivateHandler.postDelayed(mZoomControlRunnable, 4864 ZOOM_CONTROLS_TIMEOUT); 4865 } 4866 } 4867 }; 4868 } 4869 return mZoomControls; 4870 } 4871 4872 private ExtendedZoomControls createZoomControls() { 4873 ExtendedZoomControls zoomControls = new ExtendedZoomControls(mContext 4874 , null); 4875 zoomControls.setOnZoomInClickListener(new OnClickListener() { 4876 public void onClick(View v) { 4877 // reset time out 4878 mPrivateHandler.removeCallbacks(mZoomControlRunnable); 4879 mPrivateHandler.postDelayed(mZoomControlRunnable, 4880 ZOOM_CONTROLS_TIMEOUT); 4881 zoomIn(); 4882 } 4883 }); 4884 zoomControls.setOnZoomOutClickListener(new OnClickListener() { 4885 public void onClick(View v) { 4886 // reset time out 4887 mPrivateHandler.removeCallbacks(mZoomControlRunnable); 4888 mPrivateHandler.postDelayed(mZoomControlRunnable, 4889 ZOOM_CONTROLS_TIMEOUT); 4890 zoomOut(); 4891 } 4892 }); 4893 return zoomControls; 4894 } 4895 4896 /** 4897 * Gets the {@link ZoomButtonsController} which can be used to add 4898 * additional buttons to the zoom controls window. 4899 * 4900 * @return The instance of {@link ZoomButtonsController} used by this class, 4901 * or null if it is unavailable. 4902 * @hide 4903 */ 4904 public ZoomButtonsController getZoomButtonsController() { 4905 return mZoomButtonsController; 4906 } 4907 4908 /** 4909 * Perform zoom in in the webview 4910 * @return TRUE if zoom in succeeds. FALSE if no zoom changes. 4911 */ 4912 public boolean zoomIn() { 4913 // TODO: alternatively we can disallow this during draw history mode 4914 switchOutDrawHistory(); 4915 // Center zooming to the center of the screen. 4916 if (mInZoomOverview) { 4917 // if in overview mode, bring it back to normal mode 4918 mLastTouchX = getViewWidth() * .5f; 4919 mLastTouchY = getViewHeight() * .5f; 4920 doDoubleTap(); 4921 return true; 4922 } else { 4923 mZoomCenterX = getViewWidth() * .5f; 4924 mZoomCenterY = getViewHeight() * .5f; 4925 return zoomWithPreview(mActualScale * 1.25f); 4926 } 4927 } 4928 4929 /** 4930 * Perform zoom out in the webview 4931 * @return TRUE if zoom out succeeds. FALSE if no zoom changes. 4932 */ 4933 public boolean zoomOut() { 4934 // TODO: alternatively we can disallow this during draw history mode 4935 switchOutDrawHistory(); 4936 float scale = mActualScale * 0.8f; 4937 if (scale < (mMinZoomScale + 0.1f) 4938 && mWebViewCore.getSettings().getUseWideViewPort() 4939 && mZoomOverviewWidth > Math.ceil(getViewWidth() 4940 * mInvActualScale)) { 4941 // when zoom out to min scale, switch to overview mode 4942 doDoubleTap(); 4943 return true; 4944 } else { 4945 // Center zooming to the center of the screen. 4946 mZoomCenterX = getViewWidth() * .5f; 4947 mZoomCenterY = getViewHeight() * .5f; 4948 return zoomWithPreview(scale); 4949 } 4950 } 4951 4952 private void updateSelection() { 4953 if (mNativeClass == 0) { 4954 return; 4955 } 4956 // mLastTouchX and mLastTouchY are the point in the current viewport 4957 int contentX = viewToContentX((int) mLastTouchX + mScrollX); 4958 int contentY = viewToContentY((int) mLastTouchY + mScrollY); 4959 Rect rect = new Rect(contentX - mNavSlop, contentY - mNavSlop, 4960 contentX + mNavSlop, contentY + mNavSlop); 4961 nativeSelectBestAt(rect); 4962 } 4963 4964 /** 4965 * Scroll the focused text field/area to match the WebTextView 4966 * @param xPercent New x position of the WebTextView from 0 to 1. 4967 * @param y New y position of the WebTextView in view coordinates 4968 */ 4969 /*package*/ void scrollFocusedTextInput(float xPercent, int y) { 4970 if (!inEditingMode() || mWebViewCore == null) { 4971 return; 4972 } 4973 mWebViewCore.sendMessage(EventHub.SCROLL_TEXT_INPUT, 4974 // Since this position is relative to the top of the text input 4975 // field, we do not need to take the title bar's height into 4976 // consideration. 4977 viewToContentDimension(y), 4978 new Float(xPercent)); 4979 } 4980 4981 /** 4982 * Set our starting point and time for a drag from the WebTextView. 4983 */ 4984 /*package*/ void initiateTextFieldDrag(float x, float y, long eventTime) { 4985 if (!inEditingMode()) { 4986 return; 4987 } 4988 mLastTouchX = x + (float) (mWebTextView.getLeft() - mScrollX); 4989 mLastTouchY = y + (float) (mWebTextView.getTop() - mScrollY); 4990 mLastTouchTime = eventTime; 4991 if (!mScroller.isFinished()) { 4992 abortAnimation(); 4993 mPrivateHandler.removeMessages(RESUME_WEBCORE_UPDATE); 4994 } 4995 mSnapScrollMode = SNAP_NONE; 4996 mVelocityTracker = VelocityTracker.obtain(); 4997 mTouchMode = TOUCH_DRAG_START_MODE; 4998 } 4999 5000 /** 5001 * Given a motion event from the WebTextView, set its location to our 5002 * coordinates, and handle the event. 5003 */ 5004 /*package*/ boolean textFieldDrag(MotionEvent event) { 5005 if (!inEditingMode()) { 5006 return false; 5007 } 5008 mDragFromTextInput = true; 5009 event.offsetLocation((float) (mWebTextView.getLeft() - mScrollX), 5010 (float) (mWebTextView.getTop() - mScrollY)); 5011 boolean result = onTouchEvent(event); 5012 mDragFromTextInput = false; 5013 return result; 5014 } 5015 5016 /** 5017 * Due a touch up from a WebTextView. This will be handled by webkit to 5018 * change the selection. 5019 * @param event MotionEvent in the WebTextView's coordinates. 5020 */ 5021 /*package*/ void touchUpOnTextField(MotionEvent event) { 5022 if (!inEditingMode()) { 5023 return; 5024 } 5025 int x = viewToContentX((int) event.getX() + mWebTextView.getLeft()); 5026 int y = viewToContentY((int) event.getY() + mWebTextView.getTop()); 5027 nativeMotionUp(x, y, mNavSlop); 5028 } 5029 5030 /** 5031 * Called when pressing the center key or trackball on a textfield. 5032 */ 5033 /*package*/ void centerKeyPressOnTextField() { 5034 mWebViewCore.sendMessage(EventHub.CLICK, nativeCursorFramePointer(), 5035 nativeCursorNodePointer()); 5036 // Need to show the soft keyboard if it's not readonly. 5037 if (!nativeCursorIsReadOnly()) { 5038 displaySoftKeyboard(true); 5039 } 5040 } 5041 5042 private void doShortPress() { 5043 if (mNativeClass == 0) { 5044 return; 5045 } 5046 switchOutDrawHistory(); 5047 // mLastTouchX and mLastTouchY are the point in the current viewport 5048 int contentX = viewToContentX((int) mLastTouchX + mScrollX); 5049 int contentY = viewToContentY((int) mLastTouchY + mScrollY); 5050 if (nativePointInNavCache(contentX, contentY, mNavSlop)) { 5051 WebViewCore.MotionUpData motionUpData = new WebViewCore 5052 .MotionUpData(); 5053 motionUpData.mFrame = nativeCacheHitFramePointer(); 5054 motionUpData.mNode = nativeCacheHitNodePointer(); 5055 motionUpData.mBounds = nativeCacheHitNodeBounds(); 5056 motionUpData.mX = contentX; 5057 motionUpData.mY = contentY; 5058 mWebViewCore.sendMessageAtFrontOfQueue(EventHub.VALID_NODE_BOUNDS, 5059 motionUpData); 5060 } else { 5061 doMotionUp(contentX, contentY, false); 5062 } 5063 } 5064 5065 private void doMotionUp(int contentX, int contentY, boolean useNavCache) { 5066 if (nativeMotionUp(contentX, contentY, useNavCache ? mNavSlop : 0)) { 5067 if (mLogEvent) { 5068 Checkin.updateStats(mContext.getContentResolver(), 5069 Checkin.Stats.Tag.BROWSER_SNAP_CENTER, 1, 0.0); 5070 } 5071 } 5072 if (nativeHasCursorNode() && !nativeCursorIsTextInput()) { 5073 playSoundEffect(SoundEffectConstants.CLICK); 5074 } 5075 } 5076 5077 private void doDoubleTap() { 5078 if (mWebViewCore.getSettings().getUseWideViewPort() == false) { 5079 return; 5080 } 5081 mZoomCenterX = mLastTouchX; 5082 mZoomCenterY = mLastTouchY; 5083 mInZoomOverview = !mInZoomOverview; 5084 // remove the zoom control after double tap 5085 WebSettings settings = getSettings(); 5086 if (settings.getBuiltInZoomControls()) { 5087 if (mZoomButtonsController.isVisible()) { 5088 mZoomButtonsController.setVisible(false); 5089 } 5090 } else { 5091 if (mZoomControlRunnable != null) { 5092 mPrivateHandler.removeCallbacks(mZoomControlRunnable); 5093 } 5094 if (mZoomControls != null) { 5095 mZoomControls.hide(); 5096 } 5097 } 5098 settings.setDoubleTapToastCount(0); 5099 if (mInZoomOverview) { 5100 float newScale = (float) getViewWidth() / mZoomOverviewWidth; 5101 if (Math.abs(mActualScale - newScale) < 0.01f) { 5102 // reset mInZoomOverview to false if scale doesn't change 5103 mInZoomOverview = false; 5104 } else { 5105 // Force the titlebar fully reveal in overview mode 5106 if (mScrollY < getTitleHeight()) mScrollY = 0; 5107 zoomWithPreview(newScale); 5108 } 5109 } else { 5110 // mLastTouchX and mLastTouchY are the point in the current viewport 5111 int contentX = viewToContentX((int) mLastTouchX + mScrollX); 5112 int contentY = viewToContentY((int) mLastTouchY + mScrollY); 5113 int left = nativeGetBlockLeftEdge(contentX, contentY, mActualScale); 5114 if (left != NO_LEFTEDGE) { 5115 // add a 5pt padding to the left edge. Re-calculate the zoom 5116 // center so that the new scroll x will be on the left edge. 5117 mZoomCenterX = left < 5 ? 0 : (left - 5) * mLastScale 5118 * mActualScale / (mLastScale - mActualScale); 5119 } 5120 zoomWithPreview(mLastScale); 5121 } 5122 } 5123 5124 // Called by JNI to handle a touch on a node representing an email address, 5125 // address, or phone number 5126 private void overrideLoading(String url) { 5127 mCallbackProxy.uiOverrideUrlLoading(url); 5128 } 5129 5130 @Override 5131 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 5132 boolean result = false; 5133 if (inEditingMode()) { 5134 result = mWebTextView.requestFocus(direction, 5135 previouslyFocusedRect); 5136 } else { 5137 result = super.requestFocus(direction, previouslyFocusedRect); 5138 if (mWebViewCore.getSettings().getNeedInitialFocus()) { 5139 // For cases such as GMail, where we gain focus from a direction, 5140 // we want to move to the first available link. 5141 // FIXME: If there are no visible links, we may not want to 5142 int fakeKeyDirection = 0; 5143 switch(direction) { 5144 case View.FOCUS_UP: 5145 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_UP; 5146 break; 5147 case View.FOCUS_DOWN: 5148 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_DOWN; 5149 break; 5150 case View.FOCUS_LEFT: 5151 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_LEFT; 5152 break; 5153 case View.FOCUS_RIGHT: 5154 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_RIGHT; 5155 break; 5156 default: 5157 return result; 5158 } 5159 if (mNativeClass != 0 && !nativeHasCursorNode()) { 5160 navHandledKey(fakeKeyDirection, 1, true, 0, true); 5161 } 5162 } 5163 } 5164 return result; 5165 } 5166 5167 @Override 5168 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 5169 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 5170 5171 int heightMode = MeasureSpec.getMode(heightMeasureSpec); 5172 int heightSize = MeasureSpec.getSize(heightMeasureSpec); 5173 int widthMode = MeasureSpec.getMode(widthMeasureSpec); 5174 int widthSize = MeasureSpec.getSize(widthMeasureSpec); 5175 5176 int measuredHeight = heightSize; 5177 int measuredWidth = widthSize; 5178 5179 // Grab the content size from WebViewCore. 5180 int contentHeight = contentToViewDimension(mContentHeight); 5181 int contentWidth = contentToViewDimension(mContentWidth); 5182 5183// Log.d(LOGTAG, "------- measure " + heightMode); 5184 5185 if (heightMode != MeasureSpec.EXACTLY) { 5186 mHeightCanMeasure = true; 5187 measuredHeight = contentHeight; 5188 if (heightMode == MeasureSpec.AT_MOST) { 5189 // If we are larger than the AT_MOST height, then our height can 5190 // no longer be measured and we should scroll internally. 5191 if (measuredHeight > heightSize) { 5192 measuredHeight = heightSize; 5193 mHeightCanMeasure = false; 5194 } 5195 } 5196 } else { 5197 mHeightCanMeasure = false; 5198 } 5199 if (mNativeClass != 0) { 5200 nativeSetHeightCanMeasure(mHeightCanMeasure); 5201 } 5202 // For the width, always use the given size unless unspecified. 5203 if (widthMode == MeasureSpec.UNSPECIFIED) { 5204 mWidthCanMeasure = true; 5205 measuredWidth = contentWidth; 5206 } else { 5207 mWidthCanMeasure = false; 5208 } 5209 5210 synchronized (this) { 5211 setMeasuredDimension(measuredWidth, measuredHeight); 5212 } 5213 } 5214 5215 @Override 5216 public boolean requestChildRectangleOnScreen(View child, 5217 Rect rect, 5218 boolean immediate) { 5219 rect.offset(child.getLeft() - child.getScrollX(), 5220 child.getTop() - child.getScrollY()); 5221 5222 int height = getViewHeightWithTitle(); 5223 int screenTop = mScrollY; 5224 int screenBottom = screenTop + height; 5225 5226 int scrollYDelta = 0; 5227 5228 if (rect.bottom > screenBottom) { 5229 int oneThirdOfScreenHeight = height / 3; 5230 if (rect.height() > 2 * oneThirdOfScreenHeight) { 5231 // If the rectangle is too tall to fit in the bottom two thirds 5232 // of the screen, place it at the top. 5233 scrollYDelta = rect.top - screenTop; 5234 } else { 5235 // If the rectangle will still fit on screen, we want its 5236 // top to be in the top third of the screen. 5237 scrollYDelta = rect.top - (screenTop + oneThirdOfScreenHeight); 5238 } 5239 } else if (rect.top < screenTop) { 5240 scrollYDelta = rect.top - screenTop; 5241 } 5242 5243 int width = getWidth() - getVerticalScrollbarWidth(); 5244 int screenLeft = mScrollX; 5245 int screenRight = screenLeft + width; 5246 5247 int scrollXDelta = 0; 5248 5249 if (rect.right > screenRight && rect.left > screenLeft) { 5250 if (rect.width() > width) { 5251 scrollXDelta += (rect.left - screenLeft); 5252 } else { 5253 scrollXDelta += (rect.right - screenRight); 5254 } 5255 } else if (rect.left < screenLeft) { 5256 scrollXDelta -= (screenLeft - rect.left); 5257 } 5258 5259 if ((scrollYDelta | scrollXDelta) != 0) { 5260 return pinScrollBy(scrollXDelta, scrollYDelta, !immediate, 0); 5261 } 5262 5263 return false; 5264 } 5265 5266 /* package */ void replaceTextfieldText(int oldStart, int oldEnd, 5267 String replace, int newStart, int newEnd) { 5268 WebViewCore.ReplaceTextData arg = new WebViewCore.ReplaceTextData(); 5269 arg.mReplace = replace; 5270 arg.mNewStart = newStart; 5271 arg.mNewEnd = newEnd; 5272 mTextGeneration++; 5273 arg.mTextGeneration = mTextGeneration; 5274 mWebViewCore.sendMessage(EventHub.REPLACE_TEXT, oldStart, oldEnd, arg); 5275 } 5276 5277 /* package */ void passToJavaScript(String currentText, KeyEvent event) { 5278 WebViewCore.JSKeyData arg = new WebViewCore.JSKeyData(); 5279 arg.mEvent = event; 5280 arg.mCurrentText = currentText; 5281 // Increase our text generation number, and pass it to webcore thread 5282 mTextGeneration++; 5283 mWebViewCore.sendMessage(EventHub.PASS_TO_JS, mTextGeneration, 0, arg); 5284 // WebKit's document state is not saved until about to leave the page. 5285 // To make sure the host application, like Browser, has the up to date 5286 // document state when it goes to background, we force to save the 5287 // document state. 5288 mWebViewCore.removeMessages(EventHub.SAVE_DOCUMENT_STATE); 5289 mWebViewCore.sendMessageDelayed(EventHub.SAVE_DOCUMENT_STATE, 5290 cursorData(), 1000); 5291 } 5292 5293 /* package */ WebViewCore getWebViewCore() { 5294 return mWebViewCore; 5295 } 5296 5297 //------------------------------------------------------------------------- 5298 // Methods can be called from a separate thread, like WebViewCore 5299 // If it needs to call the View system, it has to send message. 5300 //------------------------------------------------------------------------- 5301 5302 /** 5303 * General handler to receive message coming from webkit thread 5304 */ 5305 class PrivateHandler extends Handler { 5306 @Override 5307 public void handleMessage(Message msg) { 5308 // exclude INVAL_RECT_MSG_ID since it is frequently output 5309 if (DebugFlags.WEB_VIEW && msg.what != INVAL_RECT_MSG_ID) { 5310 Log.v(LOGTAG, msg.what < REMEMBER_PASSWORD || msg.what 5311 > DOM_FOCUS_CHANGED ? Integer.toString(msg.what) 5312 : HandlerDebugString[msg.what - REMEMBER_PASSWORD]); 5313 } 5314 if (mWebViewCore == null) { 5315 // after WebView's destroy() is called, skip handling messages. 5316 return; 5317 } 5318 switch (msg.what) { 5319 case REMEMBER_PASSWORD: { 5320 mDatabase.setUsernamePassword( 5321 msg.getData().getString("host"), 5322 msg.getData().getString("username"), 5323 msg.getData().getString("password")); 5324 ((Message) msg.obj).sendToTarget(); 5325 break; 5326 } 5327 case NEVER_REMEMBER_PASSWORD: { 5328 mDatabase.setUsernamePassword( 5329 msg.getData().getString("host"), null, null); 5330 ((Message) msg.obj).sendToTarget(); 5331 break; 5332 } 5333 case SWITCH_TO_SHORTPRESS: { 5334 // if mPreventDrag is not confirmed, treat it as no so that 5335 // it won't block panning the page. 5336 if (mPreventDrag == PREVENT_DRAG_MAYBE_YES) { 5337 mPreventDrag = PREVENT_DRAG_NO; 5338 mPreventLongPress = false; 5339 mPreventDoubleTap = false; 5340 } 5341 if (mTouchMode == TOUCH_INIT_MODE) { 5342 mTouchMode = mFullScreenHolder == null 5343 ? TOUCH_SHORTPRESS_START_MODE 5344 : TOUCH_SHORTPRESS_MODE; 5345 updateSelection(); 5346 } else if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) { 5347 mTouchMode = TOUCH_DONE_MODE; 5348 } 5349 break; 5350 } 5351 case SWITCH_TO_LONGPRESS: { 5352 if (mPreventLongPress) { 5353 mTouchMode = TOUCH_DONE_MODE; 5354 WebViewCore.TouchEventData ted 5355 = new WebViewCore.TouchEventData(); 5356 ted.mAction = WebViewCore.ACTION_LONGPRESS; 5357 ted.mX = viewToContentX((int) mLastTouchX + mScrollX); 5358 ted.mY = viewToContentY((int) mLastTouchY + mScrollY); 5359 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 5360 } else if (mPreventDrag == PREVENT_DRAG_NO) { 5361 mTouchMode = TOUCH_DONE_MODE; 5362 if (mFullScreenHolder == null) { 5363 performLongClick(); 5364 rebuildWebTextView(); 5365 } 5366 } 5367 break; 5368 } 5369 case RELEASE_SINGLE_TAP: { 5370 if (mPreventDrag == PREVENT_DRAG_NO) { 5371 mTouchMode = TOUCH_DONE_MODE; 5372 doShortPress(); 5373 } 5374 break; 5375 } 5376 case SCROLL_BY_MSG_ID: 5377 setContentScrollBy(msg.arg1, msg.arg2, (Boolean) msg.obj); 5378 break; 5379 case SYNC_SCROLL_TO_MSG_ID: 5380 if (mUserScroll) { 5381 // if user has scrolled explicitly, don't sync the 5382 // scroll position any more 5383 mUserScroll = false; 5384 break; 5385 } 5386 // fall through 5387 case SCROLL_TO_MSG_ID: 5388 if (setContentScrollTo(msg.arg1, msg.arg2)) { 5389 // if we can't scroll to the exact position due to pin, 5390 // send a message to WebCore to re-scroll when we get a 5391 // new picture 5392 mUserScroll = false; 5393 mWebViewCore.sendMessage(EventHub.SYNC_SCROLL, 5394 msg.arg1, msg.arg2); 5395 } 5396 break; 5397 case SPAWN_SCROLL_TO_MSG_ID: 5398 spawnContentScrollTo(msg.arg1, msg.arg2); 5399 break; 5400 case NEW_PICTURE_MSG_ID: { 5401 WebSettings settings = mWebViewCore.getSettings(); 5402 // called for new content 5403 final int viewWidth = getViewWidth(); 5404 final WebViewCore.DrawData draw = 5405 (WebViewCore.DrawData) msg.obj; 5406 final Point viewSize = draw.mViewPoint; 5407 boolean useWideViewport = settings.getUseWideViewPort(); 5408 WebViewCore.RestoreState restoreState = draw.mRestoreState; 5409 boolean hasRestoreState = restoreState != null; 5410 if (hasRestoreState) { 5411 mInZoomOverview = false; 5412 mLastScale = mInitialScaleInPercent > 0 5413 ? mInitialScaleInPercent / 100.0f 5414 : restoreState.mTextWrapScale; 5415 if (restoreState.mMinScale == 0) { 5416 if (restoreState.mMobileSite) { 5417 if (draw.mMinPrefWidth > 5418 Math.max(0, draw.mViewPoint.x)) { 5419 mMinZoomScale = (float) viewWidth 5420 / draw.mMinPrefWidth; 5421 mMinZoomScaleFixed = false; 5422 } else { 5423 mMinZoomScale = restoreState.mDefaultScale; 5424 mMinZoomScaleFixed = true; 5425 } 5426 } else { 5427 mMinZoomScale = DEFAULT_MIN_ZOOM_SCALE; 5428 mMinZoomScaleFixed = false; 5429 } 5430 } else { 5431 mMinZoomScale = restoreState.mMinScale; 5432 mMinZoomScaleFixed = true; 5433 } 5434 if (restoreState.mMaxScale == 0) { 5435 mMaxZoomScale = DEFAULT_MAX_ZOOM_SCALE; 5436 } else { 5437 mMaxZoomScale = restoreState.mMaxScale; 5438 } 5439 setNewZoomScale(mLastScale, false); 5440 setContentScrollTo(restoreState.mScrollX, 5441 restoreState.mScrollY); 5442 if (useWideViewport 5443 && settings.getLoadWithOverviewMode()) { 5444 if (restoreState.mViewScale == 0 5445 || (restoreState.mMobileSite 5446 && mMinZoomScale < restoreState.mDefaultScale)) { 5447 mInZoomOverview = true; 5448 } 5449 } 5450 // As we are on a new page, remove the WebTextView. This 5451 // is necessary for page loads driven by webkit, and in 5452 // particular when the user was on a password field, so 5453 // the WebTextView was visible. 5454 clearTextEntry(); 5455 // update the zoom buttons as the scale can be changed 5456 if (getSettings().getBuiltInZoomControls()) { 5457 updateZoomButtonsEnabled(); 5458 } 5459 } 5460 // We update the layout (i.e. request a layout from the 5461 // view system) if the last view size that we sent to 5462 // WebCore matches the view size of the picture we just 5463 // received in the fixed dimension. 5464 final boolean updateLayout = viewSize.x == mLastWidthSent 5465 && viewSize.y == mLastHeightSent; 5466 recordNewContentSize(draw.mWidthHeight.x, 5467 draw.mWidthHeight.y 5468 + (mFindIsUp ? mFindHeight : 0), updateLayout); 5469 if (DebugFlags.WEB_VIEW) { 5470 Rect b = draw.mInvalRegion.getBounds(); 5471 Log.v(LOGTAG, "NEW_PICTURE_MSG_ID {" + 5472 b.left+","+b.top+","+b.right+","+b.bottom+"}"); 5473 } 5474 invalidateContentRect(draw.mInvalRegion.getBounds()); 5475 if (mPictureListener != null) { 5476 mPictureListener.onNewPicture(WebView.this, capturePicture()); 5477 } 5478 if (useWideViewport) { 5479 // limit mZoomOverviewWidth to sMaxViewportWidth so that 5480 // if the page doesn't behave well, the WebView won't go 5481 // insane. 5482 mZoomOverviewWidth = Math.min(sMaxViewportWidth, Math 5483 .max(draw.mMinPrefWidth, draw.mViewPoint.x)); 5484 } 5485 if (!mMinZoomScaleFixed) { 5486 mMinZoomScale = (float) viewWidth / mZoomOverviewWidth; 5487 } 5488 if (!mDrawHistory && mInZoomOverview) { 5489 // fit the content width to the current view. Ignore 5490 // the rounding error case. 5491 if (Math.abs((viewWidth * mInvActualScale) 5492 - mZoomOverviewWidth) > 1) { 5493 setNewZoomScale((float) viewWidth 5494 / mZoomOverviewWidth, false); 5495 } 5496 } 5497 if (draw.mFocusSizeChanged && inEditingMode()) { 5498 mFocusSizeChanged = true; 5499 } 5500 if (hasRestoreState) { 5501 mViewManager.postReadyToDrawAll(); 5502 } 5503 break; 5504 } 5505 case WEBCORE_INITIALIZED_MSG_ID: 5506 // nativeCreate sets mNativeClass to a non-zero value 5507 nativeCreate(msg.arg1); 5508 break; 5509 case UPDATE_TEXTFIELD_TEXT_MSG_ID: 5510 // Make sure that the textfield is currently focused 5511 // and representing the same node as the pointer. 5512 if (inEditingMode() && 5513 mWebTextView.isSameTextField(msg.arg1)) { 5514 if (msg.getData().getBoolean("password")) { 5515 Spannable text = (Spannable) mWebTextView.getText(); 5516 int start = Selection.getSelectionStart(text); 5517 int end = Selection.getSelectionEnd(text); 5518 mWebTextView.setInPassword(true); 5519 // Restore the selection, which may have been 5520 // ruined by setInPassword. 5521 Spannable pword = 5522 (Spannable) mWebTextView.getText(); 5523 Selection.setSelection(pword, start, end); 5524 // If the text entry has created more events, ignore 5525 // this one. 5526 } else if (msg.arg2 == mTextGeneration) { 5527 mWebTextView.setTextAndKeepSelection( 5528 (String) msg.obj); 5529 } 5530 } 5531 break; 5532 case UPDATE_TEXT_SELECTION_MSG_ID: 5533 if (inEditingMode() 5534 && mWebTextView.isSameTextField(msg.arg1) 5535 && msg.arg2 == mTextGeneration) { 5536 WebViewCore.TextSelectionData tData 5537 = (WebViewCore.TextSelectionData) msg.obj; 5538 mWebTextView.setSelectionFromWebKit(tData.mStart, 5539 tData.mEnd); 5540 } 5541 break; 5542 case MOVE_OUT_OF_PLUGIN: 5543 navHandledKey(msg.arg1, 1, false, 0, true); 5544 break; 5545 case UPDATE_TEXT_ENTRY_MSG_ID: 5546 // this is sent after finishing resize in WebViewCore. Make 5547 // sure the text edit box is still on the screen. 5548 if (inEditingMode() && nativeCursorIsTextInput()) { 5549 mWebTextView.bringIntoView(); 5550 rebuildWebTextView(); 5551 } 5552 break; 5553 case CLEAR_TEXT_ENTRY: 5554 clearTextEntry(); 5555 break; 5556 case INVAL_RECT_MSG_ID: { 5557 Rect r = (Rect)msg.obj; 5558 if (r == null) { 5559 invalidate(); 5560 } else { 5561 // we need to scale r from content into view coords, 5562 // which viewInvalidate() does for us 5563 viewInvalidate(r.left, r.top, r.right, r.bottom); 5564 } 5565 break; 5566 } 5567 case REQUEST_FORM_DATA: 5568 AutoCompleteAdapter adapter = (AutoCompleteAdapter) msg.obj; 5569 if (mWebTextView.isSameTextField(msg.arg1)) { 5570 mWebTextView.setAdapterCustom(adapter); 5571 } 5572 break; 5573 case UPDATE_CLIPBOARD: 5574 String str = (String) msg.obj; 5575 if (DebugFlags.WEB_VIEW) { 5576 Log.v(LOGTAG, "UPDATE_CLIPBOARD " + str); 5577 } 5578 try { 5579 IClipboard clip = IClipboard.Stub.asInterface( 5580 ServiceManager.getService("clipboard")); 5581 clip.setClipboardText(str); 5582 } catch (android.os.RemoteException e) { 5583 Log.e(LOGTAG, "Clipboard failed", e); 5584 } 5585 break; 5586 case RESUME_WEBCORE_UPDATE: 5587 WebViewCore.resumeUpdate(mWebViewCore); 5588 break; 5589 5590 case LONG_PRESS_CENTER: 5591 // as this is shared by keydown and trackballdown, reset all 5592 // the states 5593 mGotCenterDown = false; 5594 mTrackballDown = false; 5595 // LONG_PRESS_CENTER is sent as a delayed message. If we 5596 // switch to windows overview, the WebView will be 5597 // temporarily removed from the view system. In that case, 5598 // do nothing. 5599 if (getParent() != null) { 5600 performLongClick(); 5601 } 5602 break; 5603 5604 case WEBCORE_NEED_TOUCH_EVENTS: 5605 mForwardTouchEvents = (msg.arg1 != 0); 5606 break; 5607 5608 case PREVENT_TOUCH_ID: 5609 if (msg.arg1 == MotionEvent.ACTION_DOWN) { 5610 // dont override if mPreventDrag has been set to no due 5611 // to time out 5612 if (mPreventDrag == PREVENT_DRAG_MAYBE_YES) { 5613 mPreventDrag = (msg.arg2 & TOUCH_PREVENT_DRAG) 5614 == TOUCH_PREVENT_DRAG ? PREVENT_DRAG_YES 5615 : PREVENT_DRAG_NO; 5616 if (mPreventDrag == PREVENT_DRAG_YES) { 5617 mTouchMode = TOUCH_DONE_MODE; 5618 } else { 5619 mPreventLongPress = 5620 (msg.arg2 & TOUCH_PREVENT_LONGPRESS) 5621 == TOUCH_PREVENT_LONGPRESS; 5622 mPreventDoubleTap = 5623 (msg.arg2 & TOUCH_PREVENT_DOUBLETAP) 5624 == TOUCH_PREVENT_DOUBLETAP; 5625 } 5626 } 5627 } 5628 break; 5629 5630 case REQUEST_KEYBOARD: 5631 if (msg.arg1 == 0) { 5632 hideSoftKeyboard(); 5633 } else { 5634 displaySoftKeyboard(false); 5635 if (DebugFlags.WEB_VIEW) { 5636 Log.v(LOGTAG, "REQUEST_KEYBOARD" 5637 + " focusCandidateIsPlugin=" 5638 + nativeFocusCandidateIsPlugin()); 5639 } 5640 } 5641 break; 5642 5643 case FIND_AGAIN: 5644 // Ignore if find has been dismissed. 5645 if (mFindIsUp) { 5646 findAll(mLastFind); 5647 } 5648 break; 5649 5650 case DRAG_HELD_MOTIONLESS: 5651 mHeldMotionless = MOTIONLESS_TRUE; 5652 invalidate(); 5653 // fall through to keep scrollbars awake 5654 5655 case AWAKEN_SCROLL_BARS: 5656 if (mTouchMode == TOUCH_DRAG_MODE 5657 && mHeldMotionless == MOTIONLESS_TRUE) { 5658 awakenScrollBars(ViewConfiguration 5659 .getScrollDefaultDelay(), false); 5660 mPrivateHandler.sendMessageDelayed(mPrivateHandler 5661 .obtainMessage(AWAKEN_SCROLL_BARS), 5662 ViewConfiguration.getScrollDefaultDelay()); 5663 } 5664 break; 5665 5666 case DO_MOTION_UP: 5667 doMotionUp(msg.arg1, msg.arg2, (Boolean) msg.obj); 5668 break; 5669 5670 case SHOW_FULLSCREEN: 5671 WebViewCore.PluginFullScreenData data 5672 = (WebViewCore.PluginFullScreenData) msg.obj; 5673 if (data.mNpp != 0 && data.mView != null) { 5674 if (mFullScreenHolder != null) { 5675 Log.w(LOGTAG, 5676 "Should not have another full screen."); 5677 mFullScreenHolder.dismiss(); 5678 } 5679 mFullScreenHolder = new PluginFullScreenHolder( 5680 WebView.this, data.mNpp); 5681 mFullScreenHolder.setContentView(data.mView); 5682 mFullScreenHolder.setCancelable(false); 5683 mFullScreenHolder.setCanceledOnTouchOutside(false); 5684 mFullScreenHolder.show(); 5685 } 5686 // move the matching embedded view fully into the view so 5687 // that touch will be valid instead of rejected due to out 5688 // of the visible bounds 5689 // TODO: do we need to preserve the original position and 5690 // scale so that we can revert it when leaving the full 5691 // screen mode? 5692 int x = contentToViewX(data.mDocX); 5693 int y = contentToViewY(data.mDocY); 5694 int width = contentToViewDimension(data.mDocWidth); 5695 int height = contentToViewDimension(data.mDocHeight); 5696 int viewWidth = getViewWidth(); 5697 int viewHeight = getViewHeight(); 5698 int newX = mScrollX; 5699 int newY = mScrollY; 5700 if (x < mScrollX) { 5701 newX = x + (width > viewWidth 5702 ? (width - viewWidth) / 2 : 0); 5703 } else if (x + width > mScrollX + viewWidth) { 5704 newX = x + width - viewWidth - (width > viewWidth 5705 ? (width - viewWidth) / 2 : 0); 5706 } 5707 if (y < mScrollY) { 5708 newY = y + (height > viewHeight 5709 ? (height - viewHeight) / 2 : 0); 5710 } else if (y + height > mScrollY + viewHeight) { 5711 newY = y + height - viewHeight - (height > viewHeight 5712 ? (height - viewHeight) / 2 : 0); 5713 } 5714 scrollTo(newX, newY); 5715 if (width > viewWidth || height > viewHeight) { 5716 mZoomCenterX = viewWidth * .5f; 5717 mZoomCenterY = viewHeight * .5f; 5718 setNewZoomScale(mActualScale 5719 / Math.max((float) width / viewWidth, 5720 (float) height / viewHeight), false); 5721 } 5722 // Now update the bound 5723 mFullScreenHolder.updateBound(contentToViewX(data.mDocX) 5724 - mScrollX, contentToViewY(data.mDocY) - mScrollY, 5725 contentToViewDimension(data.mDocWidth), 5726 contentToViewDimension(data.mDocHeight)); 5727 break; 5728 5729 case HIDE_FULLSCREEN: 5730 if (mFullScreenHolder != null) { 5731 mFullScreenHolder.dismiss(); 5732 mFullScreenHolder = null; 5733 } 5734 break; 5735 5736 case DOM_FOCUS_CHANGED: 5737 if (inEditingMode()) { 5738 nativeClearCursor(); 5739 rebuildWebTextView(); 5740 } 5741 break; 5742 5743 default: 5744 super.handleMessage(msg); 5745 break; 5746 } 5747 } 5748 } 5749 5750 // Class used to use a dropdown for a <select> element 5751 private class InvokeListBox implements Runnable { 5752 // Whether the listbox allows multiple selection. 5753 private boolean mMultiple; 5754 // Passed in to a list with multiple selection to tell 5755 // which items are selected. 5756 private int[] mSelectedArray; 5757 // Passed in to a list with single selection to tell 5758 // where the initial selection is. 5759 private int mSelection; 5760 5761 private Container[] mContainers; 5762 5763 // Need these to provide stable ids to my ArrayAdapter, 5764 // which normally does not have stable ids. (Bug 1250098) 5765 private class Container extends Object { 5766 /** 5767 * Possible values for mEnabled. Keep in sync with OptionStatus in 5768 * WebViewCore.cpp 5769 */ 5770 final static int OPTGROUP = -1; 5771 final static int OPTION_DISABLED = 0; 5772 final static int OPTION_ENABLED = 1; 5773 5774 String mString; 5775 int mEnabled; 5776 int mId; 5777 5778 public String toString() { 5779 return mString; 5780 } 5781 } 5782 5783 /** 5784 * Subclass ArrayAdapter so we can disable OptionGroupLabels, 5785 * and allow filtering. 5786 */ 5787 private class MyArrayListAdapter extends ArrayAdapter<Container> { 5788 public MyArrayListAdapter(Context context, Container[] objects, boolean multiple) { 5789 super(context, 5790 multiple ? com.android.internal.R.layout.select_dialog_multichoice : 5791 com.android.internal.R.layout.select_dialog_singlechoice, 5792 objects); 5793 } 5794 5795 @Override 5796 public View getView(int position, View convertView, 5797 ViewGroup parent) { 5798 // Always pass in null so that we will get a new CheckedTextView 5799 // Otherwise, an item which was previously used as an <optgroup> 5800 // element (i.e. has no check), could get used as an <option> 5801 // element, which needs a checkbox/radio, but it would not have 5802 // one. 5803 convertView = super.getView(position, null, parent); 5804 Container c = item(position); 5805 if (c != null && Container.OPTION_ENABLED != c.mEnabled) { 5806 // ListView does not draw dividers between disabled and 5807 // enabled elements. Use a LinearLayout to provide dividers 5808 LinearLayout layout = new LinearLayout(mContext); 5809 layout.setOrientation(LinearLayout.VERTICAL); 5810 if (position > 0) { 5811 View dividerTop = new View(mContext); 5812 dividerTop.setBackgroundResource( 5813 android.R.drawable.divider_horizontal_bright); 5814 layout.addView(dividerTop); 5815 } 5816 5817 if (Container.OPTGROUP == c.mEnabled) { 5818 // Currently select_dialog_multichoice and 5819 // select_dialog_singlechoice are CheckedTextViews. If 5820 // that changes, the class cast will no longer be valid. 5821 Assert.assertTrue( 5822 convertView instanceof CheckedTextView); 5823 ((CheckedTextView) convertView).setCheckMarkDrawable( 5824 null); 5825 } else { 5826 // c.mEnabled == Container.OPTION_DISABLED 5827 // Draw the disabled element in a disabled state. 5828 convertView.setEnabled(false); 5829 } 5830 5831 layout.addView(convertView); 5832 if (position < getCount() - 1) { 5833 View dividerBottom = new View(mContext); 5834 dividerBottom.setBackgroundResource( 5835 android.R.drawable.divider_horizontal_bright); 5836 layout.addView(dividerBottom); 5837 } 5838 return layout; 5839 } 5840 return convertView; 5841 } 5842 5843 @Override 5844 public boolean hasStableIds() { 5845 // AdapterView's onChanged method uses this to determine whether 5846 // to restore the old state. Return false so that the old (out 5847 // of date) state does not replace the new, valid state. 5848 return false; 5849 } 5850 5851 private Container item(int position) { 5852 if (position < 0 || position >= getCount()) { 5853 return null; 5854 } 5855 return (Container) getItem(position); 5856 } 5857 5858 @Override 5859 public long getItemId(int position) { 5860 Container item = item(position); 5861 if (item == null) { 5862 return -1; 5863 } 5864 return item.mId; 5865 } 5866 5867 @Override 5868 public boolean areAllItemsEnabled() { 5869 return false; 5870 } 5871 5872 @Override 5873 public boolean isEnabled(int position) { 5874 Container item = item(position); 5875 if (item == null) { 5876 return false; 5877 } 5878 return Container.OPTION_ENABLED == item.mEnabled; 5879 } 5880 } 5881 5882 private InvokeListBox(String[] array, int[] enabled, int[] selected) { 5883 mMultiple = true; 5884 mSelectedArray = selected; 5885 5886 int length = array.length; 5887 mContainers = new Container[length]; 5888 for (int i = 0; i < length; i++) { 5889 mContainers[i] = new Container(); 5890 mContainers[i].mString = array[i]; 5891 mContainers[i].mEnabled = enabled[i]; 5892 mContainers[i].mId = i; 5893 } 5894 } 5895 5896 private InvokeListBox(String[] array, int[] enabled, int selection) { 5897 mSelection = selection; 5898 mMultiple = false; 5899 5900 int length = array.length; 5901 mContainers = new Container[length]; 5902 for (int i = 0; i < length; i++) { 5903 mContainers[i] = new Container(); 5904 mContainers[i].mString = array[i]; 5905 mContainers[i].mEnabled = enabled[i]; 5906 mContainers[i].mId = i; 5907 } 5908 } 5909 5910 /* 5911 * Whenever the data set changes due to filtering, this class ensures 5912 * that the checked item remains checked. 5913 */ 5914 private class SingleDataSetObserver extends DataSetObserver { 5915 private long mCheckedId; 5916 private ListView mListView; 5917 private Adapter mAdapter; 5918 5919 /* 5920 * Create a new observer. 5921 * @param id The ID of the item to keep checked. 5922 * @param l ListView for getting and clearing the checked states 5923 * @param a Adapter for getting the IDs 5924 */ 5925 public SingleDataSetObserver(long id, ListView l, Adapter a) { 5926 mCheckedId = id; 5927 mListView = l; 5928 mAdapter = a; 5929 } 5930 5931 public void onChanged() { 5932 // The filter may have changed which item is checked. Find the 5933 // item that the ListView thinks is checked. 5934 int position = mListView.getCheckedItemPosition(); 5935 long id = mAdapter.getItemId(position); 5936 if (mCheckedId != id) { 5937 // Clear the ListView's idea of the checked item, since 5938 // it is incorrect 5939 mListView.clearChoices(); 5940 // Search for mCheckedId. If it is in the filtered list, 5941 // mark it as checked 5942 int count = mAdapter.getCount(); 5943 for (int i = 0; i < count; i++) { 5944 if (mAdapter.getItemId(i) == mCheckedId) { 5945 mListView.setItemChecked(i, true); 5946 break; 5947 } 5948 } 5949 } 5950 } 5951 5952 public void onInvalidate() {} 5953 } 5954 5955 public void run() { 5956 final ListView listView = (ListView) LayoutInflater.from(mContext) 5957 .inflate(com.android.internal.R.layout.select_dialog, null); 5958 final MyArrayListAdapter adapter = new 5959 MyArrayListAdapter(mContext, mContainers, mMultiple); 5960 AlertDialog.Builder b = new AlertDialog.Builder(mContext) 5961 .setView(listView).setCancelable(true) 5962 .setInverseBackgroundForced(true); 5963 5964 if (mMultiple) { 5965 b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { 5966 public void onClick(DialogInterface dialog, int which) { 5967 mWebViewCore.sendMessage( 5968 EventHub.LISTBOX_CHOICES, 5969 adapter.getCount(), 0, 5970 listView.getCheckedItemPositions()); 5971 }}); 5972 b.setNegativeButton(android.R.string.cancel, 5973 new DialogInterface.OnClickListener() { 5974 public void onClick(DialogInterface dialog, int which) { 5975 mWebViewCore.sendMessage( 5976 EventHub.SINGLE_LISTBOX_CHOICE, -2, 0); 5977 }}); 5978 } 5979 final AlertDialog dialog = b.create(); 5980 listView.setAdapter(adapter); 5981 listView.setFocusableInTouchMode(true); 5982 // There is a bug (1250103) where the checks in a ListView with 5983 // multiple items selected are associated with the positions, not 5984 // the ids, so the items do not properly retain their checks when 5985 // filtered. Do not allow filtering on multiple lists until 5986 // that bug is fixed. 5987 5988 listView.setTextFilterEnabled(!mMultiple); 5989 if (mMultiple) { 5990 listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); 5991 int length = mSelectedArray.length; 5992 for (int i = 0; i < length; i++) { 5993 listView.setItemChecked(mSelectedArray[i], true); 5994 } 5995 } else { 5996 listView.setOnItemClickListener(new OnItemClickListener() { 5997 public void onItemClick(AdapterView parent, View v, 5998 int position, long id) { 5999 mWebViewCore.sendMessage( 6000 EventHub.SINGLE_LISTBOX_CHOICE, (int)id, 0); 6001 dialog.dismiss(); 6002 } 6003 }); 6004 if (mSelection != -1) { 6005 listView.setSelection(mSelection); 6006 listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 6007 listView.setItemChecked(mSelection, true); 6008 DataSetObserver observer = new SingleDataSetObserver( 6009 adapter.getItemId(mSelection), listView, adapter); 6010 adapter.registerDataSetObserver(observer); 6011 } 6012 } 6013 dialog.setOnCancelListener(new DialogInterface.OnCancelListener() { 6014 public void onCancel(DialogInterface dialog) { 6015 mWebViewCore.sendMessage( 6016 EventHub.SINGLE_LISTBOX_CHOICE, -2, 0); 6017 } 6018 }); 6019 dialog.show(); 6020 } 6021 } 6022 6023 /* 6024 * Request a dropdown menu for a listbox with multiple selection. 6025 * 6026 * @param array Labels for the listbox. 6027 * @param enabledArray State for each element in the list. See static 6028 * integers in Container class. 6029 * @param selectedArray Which positions are initally selected. 6030 */ 6031 void requestListBox(String[] array, int[] enabledArray, int[] 6032 selectedArray) { 6033 mPrivateHandler.post( 6034 new InvokeListBox(array, enabledArray, selectedArray)); 6035 } 6036 6037 /* 6038 * Request a dropdown menu for a listbox with single selection or a single 6039 * <select> element. 6040 * 6041 * @param array Labels for the listbox. 6042 * @param enabledArray State for each element in the list. See static 6043 * integers in Container class. 6044 * @param selection Which position is initally selected. 6045 */ 6046 void requestListBox(String[] array, int[] enabledArray, int selection) { 6047 mPrivateHandler.post( 6048 new InvokeListBox(array, enabledArray, selection)); 6049 } 6050 6051 // called by JNI 6052 private void sendMoveFocus(int frame, int node) { 6053 mWebViewCore.sendMessage(EventHub.SET_MOVE_FOCUS, 6054 new WebViewCore.CursorData(frame, node, 0, 0)); 6055 } 6056 6057 // called by JNI 6058 private void sendMoveMouse(int frame, int node, int x, int y) { 6059 mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE, 6060 new WebViewCore.CursorData(frame, node, x, y)); 6061 } 6062 6063 /* 6064 * Send a mouse move event to the webcore thread. 6065 * 6066 * @param removeFocus Pass true if the "mouse" cursor is now over a node 6067 * which wants key events, but it is not the focus. This 6068 * will make the visual appear as though nothing is in 6069 * focus. Remove the WebTextView, if present, and stop 6070 * drawing the blinking caret. 6071 * called by JNI 6072 */ 6073 private void sendMoveMouseIfLatest(boolean removeFocus) { 6074 if (removeFocus) { 6075 clearTextEntry(); 6076 setFocusControllerInactive(); 6077 } 6078 mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE_IF_LATEST, 6079 cursorData()); 6080 } 6081 6082 // called by JNI 6083 private void sendMotionUp(int touchGeneration, 6084 int frame, int node, int x, int y) { 6085 WebViewCore.TouchUpData touchUpData = new WebViewCore.TouchUpData(); 6086 touchUpData.mMoveGeneration = touchGeneration; 6087 touchUpData.mFrame = frame; 6088 touchUpData.mNode = node; 6089 touchUpData.mX = x; 6090 touchUpData.mY = y; 6091 mWebViewCore.sendMessage(EventHub.TOUCH_UP, touchUpData); 6092 } 6093 6094 6095 private int getScaledMaxXScroll() { 6096 int width; 6097 if (mHeightCanMeasure == false) { 6098 width = getViewWidth() / 4; 6099 } else { 6100 Rect visRect = new Rect(); 6101 calcOurVisibleRect(visRect); 6102 width = visRect.width() / 2; 6103 } 6104 // FIXME the divisor should be retrieved from somewhere 6105 return viewToContentX(width); 6106 } 6107 6108 private int getScaledMaxYScroll() { 6109 int height; 6110 if (mHeightCanMeasure == false) { 6111 height = getViewHeight() / 4; 6112 } else { 6113 Rect visRect = new Rect(); 6114 calcOurVisibleRect(visRect); 6115 height = visRect.height() / 2; 6116 } 6117 // FIXME the divisor should be retrieved from somewhere 6118 // the closest thing today is hard-coded into ScrollView.java 6119 // (from ScrollView.java, line 363) int maxJump = height/2; 6120 return Math.round(height * mInvActualScale); 6121 } 6122 6123 /** 6124 * Called by JNI to invalidate view 6125 */ 6126 private void viewInvalidate() { 6127 invalidate(); 6128 } 6129 6130 // return true if the key was handled 6131 private boolean navHandledKey(int keyCode, int count, boolean noScroll, 6132 long time, boolean ignorePlugin) { 6133 if (mNativeClass == 0) { 6134 return false; 6135 } 6136 if (ignorePlugin == false && nativeFocusIsPlugin()) { 6137 KeyEvent event = new KeyEvent(time, time, KeyEvent.ACTION_DOWN 6138 , keyCode, count, (mShiftIsPressed ? KeyEvent.META_SHIFT_ON : 0) 6139 | (false ? KeyEvent.META_ALT_ON : 0) // FIXME 6140 | (false ? KeyEvent.META_SYM_ON : 0) // FIXME 6141 , 0, 0, 0); 6142 mWebViewCore.sendMessage(EventHub.KEY_DOWN, event); 6143 mWebViewCore.sendMessage(EventHub.KEY_UP, event); 6144 return true; 6145 } 6146 mLastCursorTime = time; 6147 mLastCursorBounds = nativeGetCursorRingBounds(); 6148 boolean keyHandled 6149 = nativeMoveCursor(keyCode, count, noScroll) == false; 6150 if (DebugFlags.WEB_VIEW) { 6151 Log.v(LOGTAG, "navHandledKey mLastCursorBounds=" + mLastCursorBounds 6152 + " mLastCursorTime=" + mLastCursorTime 6153 + " handled=" + keyHandled); 6154 } 6155 if (keyHandled == false || mHeightCanMeasure == false) { 6156 return keyHandled; 6157 } 6158 Rect contentCursorRingBounds = nativeGetCursorRingBounds(); 6159 if (contentCursorRingBounds.isEmpty()) return keyHandled; 6160 Rect viewCursorRingBounds = contentToViewRect(contentCursorRingBounds); 6161 Rect visRect = new Rect(); 6162 calcOurVisibleRect(visRect); 6163 Rect outset = new Rect(visRect); 6164 int maxXScroll = visRect.width() / 2; 6165 int maxYScroll = visRect.height() / 2; 6166 outset.inset(-maxXScroll, -maxYScroll); 6167 if (Rect.intersects(outset, viewCursorRingBounds) == false) { 6168 return keyHandled; 6169 } 6170 // FIXME: Necessary because ScrollView/ListView do not scroll left/right 6171 int maxH = Math.min(viewCursorRingBounds.right - visRect.right, 6172 maxXScroll); 6173 if (maxH > 0) { 6174 pinScrollBy(maxH, 0, true, 0); 6175 } else { 6176 maxH = Math.max(viewCursorRingBounds.left - visRect.left, 6177 -maxXScroll); 6178 if (maxH < 0) { 6179 pinScrollBy(maxH, 0, true, 0); 6180 } 6181 } 6182 if (mLastCursorBounds.isEmpty()) return keyHandled; 6183 if (mLastCursorBounds.equals(contentCursorRingBounds)) { 6184 return keyHandled; 6185 } 6186 if (DebugFlags.WEB_VIEW) { 6187 Log.v(LOGTAG, "navHandledKey contentCursorRingBounds=" 6188 + contentCursorRingBounds); 6189 } 6190 requestRectangleOnScreen(viewCursorRingBounds); 6191 mUserScroll = true; 6192 return keyHandled; 6193 } 6194 6195 /** 6196 * Set the background color. It's white by default. Pass 6197 * zero to make the view transparent. 6198 * @param color the ARGB color described by Color.java 6199 */ 6200 public void setBackgroundColor(int color) { 6201 mBackgroundColor = color; 6202 mWebViewCore.sendMessage(EventHub.SET_BACKGROUND_COLOR, color); 6203 } 6204 6205 public void debugDump() { 6206 nativeDebugDump(); 6207 mWebViewCore.sendMessage(EventHub.DUMP_NAVTREE); 6208 } 6209 6210 /** 6211 * Draw the HTML page into the specified canvas. This call ignores any 6212 * view-specific zoom, scroll offset, or other changes. It does not draw 6213 * any view-specific chrome, such as progress or URL bars. 6214 * 6215 * @hide only needs to be accessible to Browser and testing 6216 */ 6217 public void drawPage(Canvas canvas) { 6218 mWebViewCore.drawContentPicture(canvas, 0, false, false); 6219 } 6220 6221 /** 6222 * Update our cache with updatedText. 6223 * @param updatedText The new text to put in our cache. 6224 */ 6225 /* package */ void updateCachedTextfield(String updatedText) { 6226 // Also place our generation number so that when we look at the cache 6227 // we recognize that it is up to date. 6228 nativeUpdateCachedTextfield(updatedText, mTextGeneration); 6229 } 6230 6231 private native int nativeCacheHitFramePointer(); 6232 private native Rect nativeCacheHitNodeBounds(); 6233 private native int nativeCacheHitNodePointer(); 6234 /* package */ native void nativeClearCursor(); 6235 private native void nativeCreate(int ptr); 6236 private native int nativeCursorFramePointer(); 6237 private native Rect nativeCursorNodeBounds(); 6238 /* package */ native int nativeCursorNodePointer(); 6239 /* package */ native boolean nativeCursorMatchesFocus(); 6240 private native boolean nativeCursorIntersects(Rect visibleRect); 6241 private native boolean nativeCursorIsAnchor(); 6242 private native boolean nativeCursorIsReadOnly(); 6243 private native boolean nativeCursorIsTextInput(); 6244 private native Point nativeCursorPosition(); 6245 private native String nativeCursorText(); 6246 /** 6247 * Returns true if the native cursor node says it wants to handle key events 6248 * (ala plugins). This can only be called if mNativeClass is non-zero! 6249 */ 6250 private native boolean nativeCursorWantsKeyEvents(); 6251 private native void nativeDebugDump(); 6252 private native void nativeDestroy(); 6253 private native void nativeDrawCursorRing(Canvas content); 6254 private native void nativeDrawMatches(Canvas canvas); 6255 private native void nativeDrawSelectionPointer(Canvas content, 6256 float scale, int x, int y, boolean extendSelection); 6257 private native void nativeDrawSelectionRegion(Canvas content); 6258 private native void nativeDumpDisplayTree(String urlOrNull); 6259 private native int nativeFindAll(String findLower, String findUpper); 6260 private native void nativeFindNext(boolean forward); 6261 private native int nativeFocusCandidateFramePointer(); 6262 private native boolean nativeFocusCandidateIsPassword(); 6263 private native boolean nativeFocusCandidateIsPlugin(); 6264 private native boolean nativeFocusCandidateIsRtlText(); 6265 private native boolean nativeFocusCandidateIsTextInput(); 6266 /* package */ native int nativeFocusCandidateMaxLength(); 6267 /* package */ native String nativeFocusCandidateName(); 6268 private native Rect nativeFocusCandidateNodeBounds(); 6269 /* package */ native int nativeFocusCandidatePointer(); 6270 private native String nativeFocusCandidateText(); 6271 private native int nativeFocusCandidateTextSize(); 6272 /** 6273 * Returns an integer corresponding to WebView.cpp::type. 6274 * See WebTextView.setType() 6275 */ 6276 private native int nativeFocusCandidateType(); 6277 private native boolean nativeFocusIsPlugin(); 6278 /* package */ native int nativeFocusNodePointer(); 6279 private native Rect nativeGetCursorRingBounds(); 6280 private native Region nativeGetSelection(); 6281 private native boolean nativeHasCursorNode(); 6282 private native boolean nativeHasFocusNode(); 6283 private native void nativeHideCursor(); 6284 private native String nativeImageURI(int x, int y); 6285 private native void nativeInstrumentReport(); 6286 /* package */ native void nativeMoveCursorToNextTextInput(); 6287 // return true if the page has been scrolled 6288 private native boolean nativeMotionUp(int x, int y, int slop); 6289 // returns false if it handled the key 6290 private native boolean nativeMoveCursor(int keyCode, int count, 6291 boolean noScroll); 6292 private native int nativeMoveGeneration(); 6293 private native void nativeMoveSelection(int x, int y, 6294 boolean extendSelection); 6295 private native boolean nativePointInNavCache(int x, int y, int slop); 6296 // Like many other of our native methods, you must make sure that 6297 // mNativeClass is not null before calling this method. 6298 private native void nativeRecordButtons(boolean focused, 6299 boolean pressed, boolean invalidate); 6300 private native void nativeSelectBestAt(Rect rect); 6301 private native void nativeSetFindIsUp(); 6302 private native void nativeSetFollowedLink(boolean followed); 6303 private native void nativeSetHeightCanMeasure(boolean measure); 6304 // Returns a value corresponding to CachedFrame::ImeAction 6305 /* package */ native int nativeTextFieldAction(); 6306 private native int nativeTextGeneration(); 6307 // Never call this version except by updateCachedTextfield(String) - 6308 // we always want to pass in our generation number. 6309 private native void nativeUpdateCachedTextfield(String updatedText, 6310 int generation); 6311 // return NO_LEFTEDGE means failure. 6312 private static final int NO_LEFTEDGE = -1; 6313 private native int nativeGetBlockLeftEdge(int x, int y, float scale); 6314} 6315