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