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