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