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