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