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