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