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