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