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