WebView.java revision e621d6ffb9602c21e6f6f4f12ac02680a3c78601
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.webkit; 18 19import android.app.AlertDialog; 20import android.content.Context; 21import android.content.DialogInterface; 22import android.content.Intent; 23import android.content.DialogInterface.OnCancelListener; 24import android.database.DataSetObserver; 25import android.graphics.Bitmap; 26import android.graphics.Canvas; 27import android.graphics.Color; 28import android.graphics.Paint; 29import android.graphics.Path; 30import android.graphics.Picture; 31import android.graphics.Point; 32import android.graphics.Rect; 33import android.graphics.Region; 34import android.graphics.drawable.Drawable; 35import android.net.http.SslCertificate; 36import android.net.Uri; 37import android.os.Bundle; 38import android.os.Handler; 39import android.os.Message; 40import android.os.ServiceManager; 41import android.os.SystemClock; 42import android.provider.Checkin; 43import android.text.IClipboard; 44import android.text.Selection; 45import android.text.Spannable; 46import android.util.AttributeSet; 47import android.util.EventLog; 48import android.util.Log; 49import android.util.TypedValue; 50import android.view.Gravity; 51import android.view.KeyEvent; 52import android.view.LayoutInflater; 53import android.view.MotionEvent; 54import android.view.SoundEffectConstants; 55import android.view.VelocityTracker; 56import android.view.View; 57import android.view.ViewConfiguration; 58import android.view.ViewGroup; 59import android.view.ViewParent; 60import android.view.ViewTreeObserver; 61import android.view.animation.AlphaAnimation; 62import android.view.inputmethod.EditorInfo; 63import android.view.inputmethod.InputMethodManager; 64import android.webkit.WebTextView.AutoCompleteAdapter; 65import android.webkit.WebViewCore.EventHub; 66import android.widget.AbsoluteLayout; 67import android.widget.Adapter; 68import android.widget.AdapterView; 69import android.widget.ArrayAdapter; 70import android.widget.FrameLayout; 71import android.widget.ImageView; 72import android.widget.ListView; 73import android.widget.ScrollBarDrawable; 74import android.widget.Scroller; 75import android.widget.Toast; 76import android.widget.ZoomButtonsController; 77import android.widget.ZoomControls; 78import android.widget.AdapterView.OnItemClickListener; 79 80import java.io.File; 81import java.io.FileInputStream; 82import java.io.FileNotFoundException; 83import java.io.FileOutputStream; 84import java.io.IOException; 85import java.net.URLDecoder; 86import java.util.ArrayList; 87import java.util.List; 88import java.util.Map; 89 90/** 91 * <p>A View that displays web pages. This class is the basis upon which you 92 * can roll your own web browser or simply display some online content within your Activity. 93 * It uses the WebKit rendering engine to display 94 * web pages and includes methods to navigate forward and backward 95 * through a history, zoom in and out, perform text searches and more.</p> 96 * <p>To enable the built-in zoom, set 97 * {@link #getSettings() WebSettings}.{@link WebSettings#setBuiltInZoomControls(boolean)} 98 * (introduced in API version 3). 99 * <p>Note that, in order for your Activity to access the Internet and load web pages 100 * in a WebView, you must add the <var>INTERNET</var> permissions to your 101 * Android Manifest file:</p> 102 * <pre><uses-permission android:name="android.permission.INTERNET" /></pre> 103 * 104 * <p>This must be a child of the <code><manifest></code> element.</p> 105 * 106 * <h3>Basic usage</h3> 107 * 108 * <p>By default, a WebView provides no browser-like widgets, does not 109 * enable JavaScript and errors will be ignored. If your goal is only 110 * to display some HTML as a part of your UI, this is probably fine; 111 * the user won't need to interact with the web page beyond reading 112 * it, and the web page won't need to interact with the user. If you 113 * actually want a fully blown web browser, then you probably want to 114 * invoke the Browser application with your URL rather than show it 115 * with a WebView. See {@link android.content.Intent} for more information.</p> 116 * 117 * <pre class="prettyprint"> 118 * WebView webview = new WebView(this); 119 * setContentView(webview); 120 * 121 * // Simplest usage: note that an exception will NOT be thrown 122 * // if there is an error loading this page (see below). 123 * webview.loadUrl("http://slashdot.org/"); 124 * 125 * // Of course you can also load from any string: 126 * String summary = "<html><body>You scored <b>192</b> points.</body></html>"; 127 * webview.loadData(summary, "text/html", "utf-8"); 128 * // ... although note that there are restrictions on what this HTML can do. 129 * // See the JavaDocs for loadData and loadDataWithBaseUrl for more info. 130 * </pre> 131 * 132 * <p>A WebView has several customization points where you can add your 133 * own behavior. These are:</p> 134 * 135 * <ul> 136 * <li>Creating and setting a {@link android.webkit.WebChromeClient} subclass. 137 * This class is called when something that might impact a 138 * browser UI happens, for instance, progress updates and 139 * JavaScript alerts are sent here. 140 * </li> 141 * <li>Creating and setting a {@link android.webkit.WebViewClient} subclass. 142 * It will be called when things happen that impact the 143 * rendering of the content, eg, errors or form submissions. You 144 * can also intercept URL loading here.</li> 145 * <li>Via the {@link android.webkit.WebSettings} class, which contains 146 * miscellaneous configuration. </li> 147 * <li>With the {@link android.webkit.WebView#addJavascriptInterface} method. 148 * This lets you bind Java objects into the WebView so they can be 149 * controlled from the web pages JavaScript.</li> 150 * </ul> 151 * 152 * <p>Here's a more complicated example, showing error handling, 153 * settings, and progress notification:</p> 154 * 155 * <pre class="prettyprint"> 156 * // Let's display the progress in the activity title bar, like the 157 * // browser app does. 158 * getWindow().requestFeature(Window.FEATURE_PROGRESS); 159 * 160 * webview.getSettings().setJavaScriptEnabled(true); 161 * 162 * final Activity activity = this; 163 * webview.setWebChromeClient(new WebChromeClient() { 164 * public void onProgressChanged(WebView view, int progress) { 165 * // Activities and WebViews measure progress with different scales. 166 * // The progress meter will automatically disappear when we reach 100% 167 * activity.setProgress(progress * 1000); 168 * } 169 * }); 170 * webview.setWebViewClient(new WebViewClient() { 171 * public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { 172 * Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show(); 173 * } 174 * }); 175 * 176 * webview.loadUrl("http://slashdot.org/"); 177 * </pre> 178 * 179 * <h3>Cookie and window management</h3> 180 * 181 * <p>For obvious security reasons, your application has its own 182 * cache, cookie store etc - it does not share the Browser 183 * applications data. Cookies are managed on a separate thread, so 184 * operations like index building don't block the UI 185 * thread. Follow the instructions in {@link android.webkit.CookieSyncManager} 186 * if you want to use cookies in your application. 187 * </p> 188 * 189 * <p>By default, requests by the HTML to open new windows are 190 * ignored. This is true whether they be opened by JavaScript or by 191 * the target attribute on a link. You can customize your 192 * WebChromeClient to provide your own behaviour for opening multiple windows, 193 * and render them in whatever manner you want.</p> 194 * 195 * <p>Standard behavior for an Activity is to be destroyed and 196 * recreated when the devices orientation is changed. This will cause 197 * the WebView to reload the current page. If you don't want that, you 198 * can set your Activity to handle the orientation and keyboardHidden 199 * changes, and then just leave the WebView alone. It'll automatically 200 * re-orient itself as appropriate.</p> 201 */ 202public class WebView extends AbsoluteLayout 203 implements ViewTreeObserver.OnGlobalFocusChangeListener, 204 ViewGroup.OnHierarchyChangeListener { 205 206 // if AUTO_REDRAW_HACK is true, then the CALL key will toggle redrawing 207 // the screen all-the-time. Good for profiling our drawing code 208 static private final boolean AUTO_REDRAW_HACK = false; 209 // true means redraw the screen all-the-time. Only with AUTO_REDRAW_HACK 210 private boolean mAutoRedraw; 211 212 static final String LOGTAG = "webview"; 213 214 private static class ExtendedZoomControls extends FrameLayout { 215 public ExtendedZoomControls(Context context, AttributeSet attrs) { 216 super(context, attrs); 217 LayoutInflater inflater = (LayoutInflater) 218 context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 219 inflater.inflate(com.android.internal.R.layout.zoom_magnify, this, true); 220 mPlusMinusZoomControls = (ZoomControls) findViewById( 221 com.android.internal.R.id.zoomControls); 222 mZoomMagnify = (ImageView) findViewById(com.android.internal.R.id.zoomMagnify); 223 } 224 225 public void show(boolean showZoom, boolean canZoomOut) { 226 mPlusMinusZoomControls.setVisibility( 227 showZoom ? View.VISIBLE : View.GONE); 228 mZoomMagnify.setVisibility(canZoomOut ? View.VISIBLE : View.GONE); 229 fade(View.VISIBLE, 0.0f, 1.0f); 230 } 231 232 public void hide() { 233 fade(View.GONE, 1.0f, 0.0f); 234 } 235 236 private void fade(int visibility, float startAlpha, float endAlpha) { 237 AlphaAnimation anim = new AlphaAnimation(startAlpha, endAlpha); 238 anim.setDuration(500); 239 startAnimation(anim); 240 setVisibility(visibility); 241 } 242 243 public void setIsZoomMagnifyEnabled(boolean isEnabled) { 244 mZoomMagnify.setEnabled(isEnabled); 245 } 246 247 public boolean hasFocus() { 248 return mPlusMinusZoomControls.hasFocus() || mZoomMagnify.hasFocus(); 249 } 250 251 public void setOnZoomInClickListener(OnClickListener listener) { 252 mPlusMinusZoomControls.setOnZoomInClickListener(listener); 253 } 254 255 public void setOnZoomOutClickListener(OnClickListener listener) { 256 mPlusMinusZoomControls.setOnZoomOutClickListener(listener); 257 } 258 259 public void setOnZoomMagnifyClickListener(OnClickListener listener) { 260 mZoomMagnify.setOnClickListener(listener); 261 } 262 263 ZoomControls mPlusMinusZoomControls; 264 ImageView mZoomMagnify; 265 } 266 267 /** 268 * Transportation object for returning WebView across thread boundaries. 269 */ 270 public class WebViewTransport { 271 private WebView mWebview; 272 273 /** 274 * Set the WebView to the transportation object. 275 * @param webview The WebView to transport. 276 */ 277 public synchronized void setWebView(WebView webview) { 278 mWebview = webview; 279 } 280 281 /** 282 * Return the WebView object. 283 * @return WebView The transported WebView object. 284 */ 285 public synchronized WebView getWebView() { 286 return mWebview; 287 } 288 } 289 290 // A final CallbackProxy shared by WebViewCore and BrowserFrame. 291 private final CallbackProxy mCallbackProxy; 292 293 private final WebViewDatabase mDatabase; 294 295 // SSL certificate for the main top-level page (if secure) 296 private SslCertificate mCertificate; 297 298 // Native WebView pointer that is 0 until the native object has been 299 // created. 300 private int mNativeClass; 301 // This would be final but it needs to be set to null when the WebView is 302 // destroyed. 303 private WebViewCore mWebViewCore; 304 // Handler for dispatching UI messages. 305 /* package */ final Handler mPrivateHandler = new PrivateHandler(); 306 private WebTextView mWebTextView; 307 // Used to ignore changes to webkit text that arrives to the UI side after 308 // more key events. 309 private int mTextGeneration; 310 311 // Used by WebViewCore to create child views. 312 /* package */ final ViewManager mViewManager; 313 314 /** 315 * Position of the last touch event. 316 */ 317 private float mLastTouchX; 318 private float mLastTouchY; 319 320 /** 321 * Time of the last touch event. 322 */ 323 private long mLastTouchTime; 324 325 /** 326 * Time of the last time sending touch event to WebViewCore 327 */ 328 private long mLastSentTouchTime; 329 330 /** 331 * The minimum elapsed time before sending another ACTION_MOVE event to 332 * WebViewCore. This really should be tuned for each type of the devices. 333 * For example in Google Map api test case, it takes Dream device at least 334 * 150ms to do a full cycle in the WebViewCore by processing a touch event, 335 * triggering the layout and drawing the picture. While the same process 336 * takes 60+ms on the current high speed device. If we make 337 * TOUCH_SENT_INTERVAL too small, there will be multiple touch events sent 338 * to WebViewCore queue and the real layout and draw events will be pushed 339 * to further, which slows down the refresh rate. Choose 50 to favor the 340 * current high speed devices. For Dream like devices, 100 is a better 341 * choice. Maybe make this in the buildspec later. 342 */ 343 private static final int TOUCH_SENT_INTERVAL = 50; 344 345 /** 346 * Helper class to get velocity for fling 347 */ 348 VelocityTracker mVelocityTracker; 349 private int mMaximumFling; 350 private float mLastVelocity; 351 private float mLastVelX; 352 private float mLastVelY; 353 354 // use this flag to control whether enabling the new double tap zoom 355 static final boolean ENABLE_DOUBLETAP_ZOOM = true; 356 357 /** 358 * Touch mode 359 */ 360 private int mTouchMode = TOUCH_DONE_MODE; 361 private static final int TOUCH_INIT_MODE = 1; 362 private static final int TOUCH_DRAG_START_MODE = 2; 363 private static final int TOUCH_DRAG_MODE = 3; 364 private static final int TOUCH_SHORTPRESS_START_MODE = 4; 365 private static final int TOUCH_SHORTPRESS_MODE = 5; 366 private static final int TOUCH_DOUBLECLICK_MODE = 6; 367 private static final int TOUCH_DONE_MODE = 7; 368 private static final int TOUCH_SELECT_MODE = 8; 369 // touch mode values specific to scale+scroll 370 private static final int FIRST_SCROLL_ZOOM = 9; 371 private static final int SCROLL_ZOOM_ANIMATION_IN = 9; 372 private static final int SCROLL_ZOOM_ANIMATION_OUT = 10; 373 private static final int SCROLL_ZOOM_OUT = 11; 374 private static final int LAST_SCROLL_ZOOM = 11; 375 // end of touch mode values specific to scale+scroll 376 private static final int TOUCH_DOUBLE_TAP_MODE = 12; 377 378 // Whether to forward the touch events to WebCore 379 private boolean mForwardTouchEvents = false; 380 381 // Whether to prevent drag during touch. The initial value depends on 382 // mForwardTouchEvents. If WebCore wants touch events, we assume it will 383 // take control of touch events unless it says no for touch down event. 384 private boolean mPreventDrag; 385 386 // To keep track of whether the current drag was initiated by a WebTextView, 387 // so that we know not to hide the cursor 388 boolean mDragFromTextInput; 389 390 // Whether or not to draw the cursor ring. 391 private boolean mDrawCursorRing = true; 392 393 // true if onPause has been called (and not onResume) 394 private boolean mIsPaused; 395 396 /** 397 * Customizable constant 398 */ 399 // pre-computed square of ViewConfiguration.getScaledTouchSlop() 400 private int mTouchSlopSquare; 401 // pre-computed square of ViewConfiguration.getScaledDoubleTapSlop() 402 private int mDoubleTapSlopSquare; 403 // pre-computed density adjusted navigation slop 404 private int mNavSlop; 405 // This should be ViewConfiguration.getTapTimeout() 406 // But system time out is 100ms, which is too short for the browser. 407 // In the browser, if it switches out of tap too soon, jump tap won't work. 408 private static final int TAP_TIMEOUT = 200; 409 // This should be ViewConfiguration.getLongPressTimeout() 410 // But system time out is 500ms, which is too short for the browser. 411 // With a short timeout, it's difficult to treat trigger a short press. 412 private static final int LONG_PRESS_TIMEOUT = 1000; 413 // needed to avoid flinging after a pause of no movement 414 private static final int MIN_FLING_TIME = 250; 415 // The time that the Zoom Controls are visible before fading away 416 private static final long ZOOM_CONTROLS_TIMEOUT = 417 ViewConfiguration.getZoomControlsTimeout(); 418 // The amount of content to overlap between two screens when going through 419 // pages with the space bar, in pixels. 420 private static final int PAGE_SCROLL_OVERLAP = 24; 421 422 /** 423 * These prevent calling requestLayout if either dimension is fixed. This 424 * depends on the layout parameters and the measure specs. 425 */ 426 boolean mWidthCanMeasure; 427 boolean mHeightCanMeasure; 428 429 // Remember the last dimensions we sent to the native side so we can avoid 430 // sending the same dimensions more than once. 431 int mLastWidthSent; 432 int mLastHeightSent; 433 434 private int mContentWidth; // cache of value from WebViewCore 435 private int mContentHeight; // cache of value from WebViewCore 436 437 // Need to have the separate control for horizontal and vertical scrollbar 438 // style than the View's single scrollbar style 439 private boolean mOverlayHorizontalScrollbar = true; 440 private boolean mOverlayVerticalScrollbar = false; 441 442 // our standard speed. this way small distances will be traversed in less 443 // time than large distances, but we cap the duration, so that very large 444 // distances won't take too long to get there. 445 private static final int STD_SPEED = 480; // pixels per second 446 // time for the longest scroll animation 447 private static final int MAX_DURATION = 750; // milliseconds 448 private Scroller mScroller; 449 450 private boolean mWrapContent; 451 452 /** 453 * Private message ids 454 */ 455 private static final int REMEMBER_PASSWORD = 1; 456 private static final int NEVER_REMEMBER_PASSWORD = 2; 457 private static final int SWITCH_TO_SHORTPRESS = 3; 458 private static final int SWITCH_TO_LONGPRESS = 4; 459 private static final int RELEASE_SINGLE_TAP = 5; 460 private static final int REQUEST_FORM_DATA = 6; 461 private static final int SWITCH_TO_CLICK = 7; 462 private static final int RESUME_WEBCORE_UPDATE = 8; 463 464 //! arg1=x, arg2=y 465 static final int SCROLL_TO_MSG_ID = 10; 466 static final int SCROLL_BY_MSG_ID = 11; 467 //! arg1=x, arg2=y 468 static final int SPAWN_SCROLL_TO_MSG_ID = 12; 469 //! arg1=x, arg2=y 470 static final int SYNC_SCROLL_TO_MSG_ID = 13; 471 static final int NEW_PICTURE_MSG_ID = 14; 472 static final int UPDATE_TEXT_ENTRY_MSG_ID = 15; 473 static final int WEBCORE_INITIALIZED_MSG_ID = 16; 474 static final int UPDATE_TEXTFIELD_TEXT_MSG_ID = 17; 475 static final int MOVE_OUT_OF_PLUGIN = 19; 476 static final int CLEAR_TEXT_ENTRY = 20; 477 static final int UPDATE_TEXT_SELECTION_MSG_ID = 21; 478 static final int UPDATE_CLIPBOARD = 22; 479 static final int LONG_PRESS_CENTER = 23; 480 static final int PREVENT_TOUCH_ID = 24; 481 static final int WEBCORE_NEED_TOUCH_EVENTS = 25; 482 // obj=Rect in doc coordinates 483 static final int INVAL_RECT_MSG_ID = 26; 484 static final int REQUEST_KEYBOARD = 27; 485 486 static final String[] HandlerDebugString = { 487 "REMEMBER_PASSWORD", // = 1; 488 "NEVER_REMEMBER_PASSWORD", // = 2; 489 "SWITCH_TO_SHORTPRESS", // = 3; 490 "SWITCH_TO_LONGPRESS", // = 4; 491 "RELEASE_SINGLE_TAP", // = 5; 492 "REQUEST_FORM_DATA", // = 6; 493 "SWITCH_TO_CLICK", // = 7; 494 "RESUME_WEBCORE_UPDATE", // = 8; 495 "9", 496 "SCROLL_TO_MSG_ID", // = 10; 497 "SCROLL_BY_MSG_ID", // = 11; 498 "SPAWN_SCROLL_TO_MSG_ID", // = 12; 499 "SYNC_SCROLL_TO_MSG_ID", // = 13; 500 "NEW_PICTURE_MSG_ID", // = 14; 501 "UPDATE_TEXT_ENTRY_MSG_ID", // = 15; 502 "WEBCORE_INITIALIZED_MSG_ID", // = 16; 503 "UPDATE_TEXTFIELD_TEXT_MSG_ID", // = 17; 504 "18", // = 18; 505 "MOVE_OUT_OF_PLUGIN", // = 19; 506 "CLEAR_TEXT_ENTRY", // = 20; 507 "UPDATE_TEXT_SELECTION_MSG_ID", // = 21; 508 "UPDATE_CLIPBOARD", // = 22; 509 "LONG_PRESS_CENTER", // = 23; 510 "PREVENT_TOUCH_ID", // = 24; 511 "WEBCORE_NEED_TOUCH_EVENTS", // = 25; 512 "INVAL_RECT_MSG_ID", // = 26; 513 "REQUEST_KEYBOARD" // = 27; 514 }; 515 516 // default scale limit. Depending on the display density 517 private static float DEFAULT_MAX_ZOOM_SCALE; 518 private static float DEFAULT_MIN_ZOOM_SCALE; 519 // scale limit, which can be set through viewport meta tag in the web page 520 private float mMaxZoomScale; 521 private float mMinZoomScale; 522 private boolean mMinZoomScaleFixed = true; 523 524 // initial scale in percent. 0 means using default. 525 private int mInitialScale = 0; 526 527 // while in the zoom overview mode, the page's width is fully fit to the 528 // current window. The page is alive, in another words, you can click to 529 // follow the links. Double tap will toggle between zoom overview mode and 530 // the last zoom scale. 531 boolean mInZoomOverview = false; 532 533 // ideally mZoomOverviewWidth should be mContentWidth. But sites like espn, 534 // engadget always have wider mContentWidth no matter what viewport size is. 535 int mZoomOverviewWidth = WebViewCore.DEFAULT_VIEWPORT_WIDTH; 536 float mLastScale; 537 538 // default scale. Depending on the display density. 539 static int DEFAULT_SCALE_PERCENT; 540 private float mDefaultScale; 541 542 // set to true temporarily while the zoom control is being dragged 543 private boolean mPreviewZoomOnly = false; 544 545 // computed scale and inverse, from mZoomWidth. 546 private float mActualScale; 547 private float mInvActualScale; 548 // if this is non-zero, it is used on drawing rather than mActualScale 549 private float mZoomScale; 550 private float mInvInitialZoomScale; 551 private float mInvFinalZoomScale; 552 private int mInitialScrollX; 553 private int mInitialScrollY; 554 private long mZoomStart; 555 private static final int ZOOM_ANIMATION_LENGTH = 500; 556 557 private boolean mUserScroll = false; 558 559 private int mSnapScrollMode = SNAP_NONE; 560 private static final int SNAP_NONE = 1; 561 private static final int SNAP_X = 2; 562 private static final int SNAP_Y = 3; 563 private static final int SNAP_X_LOCK = 4; 564 private static final int SNAP_Y_LOCK = 5; 565 private boolean mSnapPositive; 566 567 // Used to match key downs and key ups 568 private boolean mGotKeyDown; 569 570 /* package */ static boolean mLogEvent = true; 571 private static final int EVENT_LOG_ZOOM_LEVEL_CHANGE = 70101; 572 private static final int EVENT_LOG_DOUBLE_TAP_DURATION = 70102; 573 574 // for event log 575 private long mLastTouchUpTime = 0; 576 577 /** 578 * URI scheme for telephone number 579 */ 580 public static final String SCHEME_TEL = "tel:"; 581 /** 582 * URI scheme for email address 583 */ 584 public static final String SCHEME_MAILTO = "mailto:"; 585 /** 586 * URI scheme for map address 587 */ 588 public static final String SCHEME_GEO = "geo:0,0?q="; 589 590 private int mBackgroundColor = Color.WHITE; 591 592 // Used to notify listeners of a new picture. 593 private PictureListener mPictureListener; 594 /** 595 * Interface to listen for new pictures as they change. 596 */ 597 public interface PictureListener { 598 /** 599 * Notify the listener that the picture has changed. 600 * @param view The WebView that owns the picture. 601 * @param picture The new picture. 602 */ 603 public void onNewPicture(WebView view, Picture picture); 604 } 605 606 // FIXME: Want to make this public, but need to change the API file. 607 public /*static*/ class HitTestResult { 608 /** 609 * Default HitTestResult, where the target is unknown 610 */ 611 public static final int UNKNOWN_TYPE = 0; 612 /** 613 * HitTestResult for hitting a HTML::a tag 614 */ 615 public static final int ANCHOR_TYPE = 1; 616 /** 617 * HitTestResult for hitting a phone number 618 */ 619 public static final int PHONE_TYPE = 2; 620 /** 621 * HitTestResult for hitting a map address 622 */ 623 public static final int GEO_TYPE = 3; 624 /** 625 * HitTestResult for hitting an email address 626 */ 627 public static final int EMAIL_TYPE = 4; 628 /** 629 * HitTestResult for hitting an HTML::img tag 630 */ 631 public static final int IMAGE_TYPE = 5; 632 /** 633 * HitTestResult for hitting a HTML::a tag which contains HTML::img 634 */ 635 public static final int IMAGE_ANCHOR_TYPE = 6; 636 /** 637 * HitTestResult for hitting a HTML::a tag with src=http 638 */ 639 public static final int SRC_ANCHOR_TYPE = 7; 640 /** 641 * HitTestResult for hitting a HTML::a tag with src=http + HTML::img 642 */ 643 public static final int SRC_IMAGE_ANCHOR_TYPE = 8; 644 /** 645 * HitTestResult for hitting an edit text area 646 */ 647 public static final int EDIT_TEXT_TYPE = 9; 648 649 private int mType; 650 private String mExtra; 651 652 HitTestResult() { 653 mType = UNKNOWN_TYPE; 654 } 655 656 private void setType(int type) { 657 mType = type; 658 } 659 660 private void setExtra(String extra) { 661 mExtra = extra; 662 } 663 664 public int getType() { 665 return mType; 666 } 667 668 public String getExtra() { 669 return mExtra; 670 } 671 } 672 673 // The View containing the zoom controls 674 private ExtendedZoomControls mZoomControls; 675 private Runnable mZoomControlRunnable; 676 677 private ZoomButtonsController mZoomButtonsController; 678 679 // These keep track of the center point of the zoom. They are used to 680 // determine the point around which we should zoom. 681 private float mZoomCenterX; 682 private float mZoomCenterY; 683 684 private ZoomButtonsController.OnZoomListener mZoomListener = 685 new ZoomButtonsController.OnZoomListener() { 686 687 public void onVisibilityChanged(boolean visible) { 688 if (visible) { 689 switchOutDrawHistory(); 690 updateZoomButtonsEnabled(); 691 } 692 } 693 694 public void onZoom(boolean zoomIn) { 695 if (zoomIn) { 696 zoomIn(); 697 } else { 698 zoomOut(); 699 } 700 701 updateZoomButtonsEnabled(); 702 } 703 }; 704 705 /** 706 * Construct a new WebView with a Context object. 707 * @param context A Context object used to access application assets. 708 */ 709 public WebView(Context context) { 710 this(context, null); 711 } 712 713 /** 714 * Construct a new WebView with layout parameters. 715 * @param context A Context object used to access application assets. 716 * @param attrs An AttributeSet passed to our parent. 717 */ 718 public WebView(Context context, AttributeSet attrs) { 719 this(context, attrs, com.android.internal.R.attr.webViewStyle); 720 } 721 722 /** 723 * Construct a new WebView with layout parameters and a default style. 724 * @param context A Context object used to access application assets. 725 * @param attrs An AttributeSet passed to our parent. 726 * @param defStyle The default style resource ID. 727 */ 728 public WebView(Context context, AttributeSet attrs, int defStyle) { 729 this(context, attrs, defStyle, null); 730 } 731 732 /** 733 * Construct a new WebView with layout parameters, a default style and a set 734 * of custom Javscript interfaces to be added to the WebView at initialization 735 * time. This guraratees that these interfaces will be available when the JS 736 * context is initialized. 737 * @param context A Context object used to access application assets. 738 * @param attrs An AttributeSet passed to our parent. 739 * @param defStyle The default style resource ID. 740 * @param javascriptInterfaces is a Map of intareface names, as keys, and 741 * object implementing those interfaces, as values. 742 * @hide pending API council approval. 743 */ 744 protected WebView(Context context, AttributeSet attrs, int defStyle, 745 Map<String, Object> javascriptInterfaces) { 746 super(context, attrs, defStyle); 747 init(); 748 749 mCallbackProxy = new CallbackProxy(context, this); 750 mWebViewCore = new WebViewCore(context, this, mCallbackProxy, javascriptInterfaces); 751 mDatabase = WebViewDatabase.getInstance(context); 752 mScroller = new Scroller(context); 753 754 mViewManager = new ViewManager(this); 755 756 mZoomButtonsController = new ZoomButtonsController(this); 757 mZoomButtonsController.setOnZoomListener(mZoomListener); 758 // ZoomButtonsController positions the buttons at the bottom, but in 759 // the middle. Change their layout parameters so they appear on the 760 // right. 761 View controls = mZoomButtonsController.getZoomControls(); 762 ViewGroup.LayoutParams params = controls.getLayoutParams(); 763 if (params instanceof FrameLayout.LayoutParams) { 764 FrameLayout.LayoutParams frameParams = (FrameLayout.LayoutParams) 765 params; 766 frameParams.gravity = Gravity.RIGHT; 767 } 768 } 769 770 private void updateZoomButtonsEnabled() { 771 boolean canZoomIn = mActualScale < mMaxZoomScale; 772 boolean canZoomOut = mActualScale > mMinZoomScale && !mInZoomOverview; 773 if (!canZoomIn && !canZoomOut) { 774 // Hide the zoom in and out buttons, as well as the fit to page 775 // button, if the page cannot zoom 776 mZoomButtonsController.getZoomControls().setVisibility(View.GONE); 777 } else { 778 // Bring back the hidden zoom controls. 779 mZoomButtonsController.getZoomControls() 780 .setVisibility(View.VISIBLE); 781 // Set each one individually, as a page may be able to zoom in 782 // or out. 783 mZoomButtonsController.setZoomInEnabled(canZoomIn); 784 mZoomButtonsController.setZoomOutEnabled(canZoomOut); 785 } 786 } 787 788 private void init() { 789 setWillNotDraw(false); 790 setFocusable(true); 791 setFocusableInTouchMode(true); 792 setClickable(true); 793 setLongClickable(true); 794 795 final ViewConfiguration configuration = ViewConfiguration.get(getContext()); 796 int slop = configuration.getScaledTouchSlop(); 797 mTouchSlopSquare = slop * slop; 798 mMinLockSnapReverseDistance = slop; 799 slop = configuration.getScaledDoubleTapSlop(); 800 mDoubleTapSlopSquare = slop * slop; 801 final float density = getContext().getResources().getDisplayMetrics().density; 802 // use one line height, 16 based on our current default font, for how 803 // far we allow a touch be away from the edge of a link 804 mNavSlop = (int) (16 * density); 805 // density adjusted scale factors 806 DEFAULT_SCALE_PERCENT = (int) (100 * density); 807 mDefaultScale = density; 808 mActualScale = density; 809 mInvActualScale = 1 / density; 810 DEFAULT_MAX_ZOOM_SCALE = 4.0f * density; 811 DEFAULT_MIN_ZOOM_SCALE = 0.25f * density; 812 mMaxZoomScale = DEFAULT_MAX_ZOOM_SCALE; 813 mMinZoomScale = DEFAULT_MIN_ZOOM_SCALE; 814 mMaximumFling = configuration.getScaledMaximumFlingVelocity(); 815 } 816 817 /* package */void updateDefaultZoomDensity(int zoomDensity) { 818 final float density = getContext().getResources().getDisplayMetrics().density 819 * 100 / zoomDensity; 820 if (Math.abs(density - mDefaultScale) > 0.01) { 821 float scaleFactor = density / mDefaultScale; 822 // adjust the limits 823 mNavSlop = (int) (16 * density); 824 DEFAULT_SCALE_PERCENT = (int) (100 * density); 825 DEFAULT_MAX_ZOOM_SCALE = 4.0f * density; 826 DEFAULT_MIN_ZOOM_SCALE = 0.25f * density; 827 mDefaultScale = density; 828 mMaxZoomScale *= scaleFactor; 829 mMinZoomScale *= scaleFactor; 830 setNewZoomScale(mActualScale * scaleFactor, false); 831 } 832 } 833 834 /* package */ boolean onSavePassword(String schemePlusHost, String username, 835 String password, final Message resumeMsg) { 836 boolean rVal = false; 837 if (resumeMsg == null) { 838 // null resumeMsg implies saving password silently 839 mDatabase.setUsernamePassword(schemePlusHost, username, password); 840 } else { 841 final Message remember = mPrivateHandler.obtainMessage( 842 REMEMBER_PASSWORD); 843 remember.getData().putString("host", schemePlusHost); 844 remember.getData().putString("username", username); 845 remember.getData().putString("password", password); 846 remember.obj = resumeMsg; 847 848 final Message neverRemember = mPrivateHandler.obtainMessage( 849 NEVER_REMEMBER_PASSWORD); 850 neverRemember.getData().putString("host", schemePlusHost); 851 neverRemember.getData().putString("username", username); 852 neverRemember.getData().putString("password", password); 853 neverRemember.obj = resumeMsg; 854 855 new AlertDialog.Builder(getContext()) 856 .setTitle(com.android.internal.R.string.save_password_label) 857 .setMessage(com.android.internal.R.string.save_password_message) 858 .setPositiveButton(com.android.internal.R.string.save_password_notnow, 859 new DialogInterface.OnClickListener() { 860 public void onClick(DialogInterface dialog, int which) { 861 resumeMsg.sendToTarget(); 862 } 863 }) 864 .setNeutralButton(com.android.internal.R.string.save_password_remember, 865 new DialogInterface.OnClickListener() { 866 public void onClick(DialogInterface dialog, int which) { 867 remember.sendToTarget(); 868 } 869 }) 870 .setNegativeButton(com.android.internal.R.string.save_password_never, 871 new DialogInterface.OnClickListener() { 872 public void onClick(DialogInterface dialog, int which) { 873 neverRemember.sendToTarget(); 874 } 875 }) 876 .setOnCancelListener(new OnCancelListener() { 877 public void onCancel(DialogInterface dialog) { 878 resumeMsg.sendToTarget(); 879 } 880 }).show(); 881 // Return true so that WebViewCore will pause while the dialog is 882 // up. 883 rVal = true; 884 } 885 return rVal; 886 } 887 888 @Override 889 public void setScrollBarStyle(int style) { 890 if (style == View.SCROLLBARS_INSIDE_INSET 891 || style == View.SCROLLBARS_OUTSIDE_INSET) { 892 mOverlayHorizontalScrollbar = mOverlayVerticalScrollbar = false; 893 } else { 894 mOverlayHorizontalScrollbar = mOverlayVerticalScrollbar = true; 895 } 896 super.setScrollBarStyle(style); 897 } 898 899 /** 900 * Specify whether the horizontal scrollbar has overlay style. 901 * @param overlay TRUE if horizontal scrollbar should have overlay style. 902 */ 903 public void setHorizontalScrollbarOverlay(boolean overlay) { 904 mOverlayHorizontalScrollbar = overlay; 905 } 906 907 /** 908 * Specify whether the vertical scrollbar has overlay style. 909 * @param overlay TRUE if vertical scrollbar should have overlay style. 910 */ 911 public void setVerticalScrollbarOverlay(boolean overlay) { 912 mOverlayVerticalScrollbar = overlay; 913 } 914 915 /** 916 * Return whether horizontal scrollbar has overlay style 917 * @return TRUE if horizontal scrollbar has overlay style. 918 */ 919 public boolean overlayHorizontalScrollbar() { 920 return mOverlayHorizontalScrollbar; 921 } 922 923 /** 924 * Return whether vertical scrollbar has overlay style 925 * @return TRUE if vertical scrollbar has overlay style. 926 */ 927 public boolean overlayVerticalScrollbar() { 928 return mOverlayVerticalScrollbar; 929 } 930 931 /* 932 * Return the width of the view where the content of WebView should render 933 * to. 934 */ 935 private int getViewWidth() { 936 if (!isVerticalScrollBarEnabled() || mOverlayVerticalScrollbar) { 937 return getWidth(); 938 } else { 939 return getWidth() - getVerticalScrollbarWidth(); 940 } 941 } 942 943 /* 944 * returns the height of the titlebarview (if any). Does not care about 945 * scrolling 946 */ 947 private int getTitleHeight() { 948 return mTitleBar != null ? mTitleBar.getHeight() : 0; 949 } 950 951 /* 952 * Return the amount of the titlebarview (if any) that is visible 953 */ 954 private int getVisibleTitleHeight() { 955 return Math.max(getTitleHeight() - mScrollY, 0); 956 } 957 958 /* 959 * Return the height of the view where the content of WebView should render 960 * to. Note that this excludes mTitleBar, if there is one. 961 */ 962 private int getViewHeight() { 963 int height = getHeight(); 964 if (isHorizontalScrollBarEnabled() && !mOverlayHorizontalScrollbar) { 965 height -= getHorizontalScrollbarHeight(); 966 } 967 return height - getVisibleTitleHeight(); 968 } 969 970 /** 971 * @return The SSL certificate for the main top-level page or null if 972 * there is no certificate (the site is not secure). 973 */ 974 public SslCertificate getCertificate() { 975 return mCertificate; 976 } 977 978 /** 979 * Sets the SSL certificate for the main top-level page. 980 */ 981 public void setCertificate(SslCertificate certificate) { 982 // here, the certificate can be null (if the site is not secure) 983 mCertificate = certificate; 984 } 985 986 //------------------------------------------------------------------------- 987 // Methods called by activity 988 //------------------------------------------------------------------------- 989 990 /** 991 * Save the username and password for a particular host in the WebView's 992 * internal database. 993 * @param host The host that required the credentials. 994 * @param username The username for the given host. 995 * @param password The password for the given host. 996 */ 997 public void savePassword(String host, String username, String password) { 998 mDatabase.setUsernamePassword(host, username, password); 999 } 1000 1001 /** 1002 * Set the HTTP authentication credentials for a given host and realm. 1003 * 1004 * @param host The host for the credentials. 1005 * @param realm The realm for the credentials. 1006 * @param username The username for the password. If it is null, it means 1007 * password can't be saved. 1008 * @param password The password 1009 */ 1010 public void setHttpAuthUsernamePassword(String host, String realm, 1011 String username, String password) { 1012 mDatabase.setHttpAuthUsernamePassword(host, realm, username, password); 1013 } 1014 1015 /** 1016 * Retrieve the HTTP authentication username and password for a given 1017 * host & realm pair 1018 * 1019 * @param host The host for which the credentials apply. 1020 * @param realm The realm for which the credentials apply. 1021 * @return String[] if found, String[0] is username, which can be null and 1022 * String[1] is password. Return null if it can't find anything. 1023 */ 1024 public String[] getHttpAuthUsernamePassword(String host, String realm) { 1025 return mDatabase.getHttpAuthUsernamePassword(host, realm); 1026 } 1027 1028 /** 1029 * Destroy the internal state of the WebView. This method should be called 1030 * after the WebView has been removed from the view system. No other 1031 * methods may be called on a WebView after destroy. 1032 */ 1033 public void destroy() { 1034 clearTextEntry(); 1035 if (mWebViewCore != null) { 1036 // Set the handlers to null before destroying WebViewCore so no 1037 // more messages will be posted. 1038 mCallbackProxy.setWebViewClient(null); 1039 mCallbackProxy.setWebChromeClient(null); 1040 // Tell WebViewCore to destroy itself 1041 WebViewCore webViewCore = mWebViewCore; 1042 mWebViewCore = null; // prevent using partial webViewCore 1043 webViewCore.destroy(); 1044 // Remove any pending messages that might not be serviced yet. 1045 mPrivateHandler.removeCallbacksAndMessages(null); 1046 mCallbackProxy.removeCallbacksAndMessages(null); 1047 // Wake up the WebCore thread just in case it is waiting for a 1048 // javascript dialog. 1049 synchronized (mCallbackProxy) { 1050 mCallbackProxy.notify(); 1051 } 1052 } 1053 if (mNativeClass != 0) { 1054 nativeDestroy(); 1055 mNativeClass = 0; 1056 } 1057 } 1058 1059 /** 1060 * Enables platform notifications of data state and proxy changes. 1061 */ 1062 public static void enablePlatformNotifications() { 1063 Network.enablePlatformNotifications(); 1064 } 1065 1066 /** 1067 * If platform notifications are enabled, this should be called 1068 * from the Activity's onPause() or onStop(). 1069 */ 1070 public static void disablePlatformNotifications() { 1071 Network.disablePlatformNotifications(); 1072 } 1073 1074 /** 1075 * Sets JavaScript engine flags. 1076 * 1077 * @param flags JS engine flags in a String 1078 * 1079 * @hide pending API solidification 1080 */ 1081 public void setJsFlags(String flags) { 1082 mWebViewCore.sendMessage(EventHub.SET_JS_FLAGS, flags); 1083 } 1084 1085 /** 1086 * Inform WebView of the network state. This is used to set 1087 * the javascript property window.navigator.isOnline and 1088 * generates the online/offline event as specified in HTML5, sec. 5.7.7 1089 * @param networkUp boolean indicating if network is available 1090 */ 1091 public void setNetworkAvailable(boolean networkUp) { 1092 mWebViewCore.sendMessage(EventHub.SET_NETWORK_STATE, 1093 networkUp ? 1 : 0, 0); 1094 } 1095 1096 /** 1097 * Save the state of this WebView used in 1098 * {@link android.app.Activity#onSaveInstanceState}. Please note that this 1099 * method no longer stores the display data for this WebView. The previous 1100 * behavior could potentially leak files if {@link #restoreState} was never 1101 * called. See {@link #savePicture} and {@link #restorePicture} for saving 1102 * and restoring the display data. 1103 * @param outState The Bundle to store the WebView state. 1104 * @return The same copy of the back/forward list used to save the state. If 1105 * saveState fails, the returned list will be null. 1106 * @see #savePicture 1107 * @see #restorePicture 1108 */ 1109 public WebBackForwardList saveState(Bundle outState) { 1110 if (outState == null) { 1111 return null; 1112 } 1113 // We grab a copy of the back/forward list because a client of WebView 1114 // may have invalidated the history list by calling clearHistory. 1115 WebBackForwardList list = copyBackForwardList(); 1116 final int currentIndex = list.getCurrentIndex(); 1117 final int size = list.getSize(); 1118 // We should fail saving the state if the list is empty or the index is 1119 // not in a valid range. 1120 if (currentIndex < 0 || currentIndex >= size || size == 0) { 1121 return null; 1122 } 1123 outState.putInt("index", currentIndex); 1124 // FIXME: This should just be a byte[][] instead of ArrayList but 1125 // Parcel.java does not have the code to handle multi-dimensional 1126 // arrays. 1127 ArrayList<byte[]> history = new ArrayList<byte[]>(size); 1128 for (int i = 0; i < size; i++) { 1129 WebHistoryItem item = list.getItemAtIndex(i); 1130 byte[] data = item.getFlattenedData(); 1131 if (data == null) { 1132 // It would be very odd to not have any data for a given history 1133 // item. And we will fail to rebuild the history list without 1134 // flattened data. 1135 return null; 1136 } 1137 history.add(data); 1138 } 1139 outState.putSerializable("history", history); 1140 if (mCertificate != null) { 1141 outState.putBundle("certificate", 1142 SslCertificate.saveState(mCertificate)); 1143 } 1144 return list; 1145 } 1146 1147 /** 1148 * Save the current display data to the Bundle given. Used in conjunction 1149 * with {@link #saveState}. 1150 * @param b A Bundle to store the display data. 1151 * @param dest The file to store the serialized picture data. Will be 1152 * overwritten with this WebView's picture data. 1153 * @return True if the picture was successfully saved. 1154 */ 1155 public boolean savePicture(Bundle b, File dest) { 1156 if (dest == null || b == null) { 1157 return false; 1158 } 1159 final Picture p = capturePicture(); 1160 try { 1161 final FileOutputStream out = new FileOutputStream(dest); 1162 p.writeToStream(out); 1163 out.close(); 1164 } catch (FileNotFoundException e){ 1165 e.printStackTrace(); 1166 } catch (IOException e) { 1167 e.printStackTrace(); 1168 } catch (RuntimeException e) { 1169 e.printStackTrace(); 1170 } 1171 if (dest.length() > 0) { 1172 b.putInt("scrollX", mScrollX); 1173 b.putInt("scrollY", mScrollY); 1174 b.putFloat("scale", mActualScale); 1175 if (mInZoomOverview) { 1176 b.putFloat("lastScale", mLastScale); 1177 } 1178 return true; 1179 } 1180 return false; 1181 } 1182 1183 /** 1184 * Restore the display data that was save in {@link #savePicture}. Used in 1185 * conjunction with {@link #restoreState}. 1186 * @param b A Bundle containing the saved display data. 1187 * @param src The file where the picture data was stored. 1188 * @return True if the picture was successfully restored. 1189 */ 1190 public boolean restorePicture(Bundle b, File src) { 1191 if (src == null || b == null) { 1192 return false; 1193 } 1194 if (src.exists()) { 1195 Picture p = null; 1196 try { 1197 final FileInputStream in = new FileInputStream(src); 1198 p = Picture.createFromStream(in); 1199 in.close(); 1200 } catch (FileNotFoundException e){ 1201 e.printStackTrace(); 1202 } catch (RuntimeException e) { 1203 e.printStackTrace(); 1204 } catch (IOException e) { 1205 e.printStackTrace(); 1206 } 1207 if (p != null) { 1208 int sx = b.getInt("scrollX", 0); 1209 int sy = b.getInt("scrollY", 0); 1210 float scale = b.getFloat("scale", 1.0f); 1211 mDrawHistory = true; 1212 mHistoryPicture = p; 1213 mScrollX = sx; 1214 mScrollY = sy; 1215 mHistoryWidth = Math.round(p.getWidth() * scale); 1216 mHistoryHeight = Math.round(p.getHeight() * scale); 1217 // as getWidth() / getHeight() of the view are not 1218 // available yet, set up mActualScale, so that when 1219 // onSizeChanged() is called, the rest will be set 1220 // correctly 1221 mActualScale = scale; 1222 float lastScale = b.getFloat("lastScale", -1.0f); 1223 if (lastScale > 0) { 1224 mInZoomOverview = true; 1225 mLastScale = lastScale; 1226 } else { 1227 mInZoomOverview = false; 1228 } 1229 invalidate(); 1230 return true; 1231 } 1232 } 1233 return false; 1234 } 1235 1236 /** 1237 * Restore the state of this WebView from the given map used in 1238 * {@link android.app.Activity#onRestoreInstanceState}. This method should 1239 * be called to restore the state of the WebView before using the object. If 1240 * it is called after the WebView has had a chance to build state (load 1241 * pages, create a back/forward list, etc.) there may be undesirable 1242 * side-effects. Please note that this method no longer restores the 1243 * display data for this WebView. See {@link #savePicture} and {@link 1244 * #restorePicture} for saving and restoring the display data. 1245 * @param inState The incoming Bundle of state. 1246 * @return The restored back/forward list or null if restoreState failed. 1247 * @see #savePicture 1248 * @see #restorePicture 1249 */ 1250 public WebBackForwardList restoreState(Bundle inState) { 1251 WebBackForwardList returnList = null; 1252 if (inState == null) { 1253 return returnList; 1254 } 1255 if (inState.containsKey("index") && inState.containsKey("history")) { 1256 mCertificate = SslCertificate.restoreState( 1257 inState.getBundle("certificate")); 1258 1259 final WebBackForwardList list = mCallbackProxy.getBackForwardList(); 1260 final int index = inState.getInt("index"); 1261 // We can't use a clone of the list because we need to modify the 1262 // shared copy, so synchronize instead to prevent concurrent 1263 // modifications. 1264 synchronized (list) { 1265 final List<byte[]> history = 1266 (List<byte[]>) inState.getSerializable("history"); 1267 final int size = history.size(); 1268 // Check the index bounds so we don't crash in native code while 1269 // restoring the history index. 1270 if (index < 0 || index >= size) { 1271 return null; 1272 } 1273 for (int i = 0; i < size; i++) { 1274 byte[] data = history.remove(0); 1275 if (data == null) { 1276 // If we somehow have null data, we cannot reconstruct 1277 // the item and thus our history list cannot be rebuilt. 1278 return null; 1279 } 1280 WebHistoryItem item = new WebHistoryItem(data); 1281 list.addHistoryItem(item); 1282 } 1283 // Grab the most recent copy to return to the caller. 1284 returnList = copyBackForwardList(); 1285 // Update the copy to have the correct index. 1286 returnList.setCurrentIndex(index); 1287 } 1288 // Remove all pending messages because we are restoring previous 1289 // state. 1290 mWebViewCore.removeMessages(); 1291 // Send a restore state message. 1292 mWebViewCore.sendMessage(EventHub.RESTORE_STATE, index); 1293 } 1294 return returnList; 1295 } 1296 1297 /** 1298 * Load the given url. 1299 * @param url The url of the resource to load. 1300 */ 1301 public void loadUrl(String url) { 1302 if (url == null) { 1303 return; 1304 } 1305 switchOutDrawHistory(); 1306 mWebViewCore.sendMessage(EventHub.LOAD_URL, url); 1307 clearTextEntry(); 1308 } 1309 1310 /** 1311 * Load the url with postData using "POST" method into the WebView. If url 1312 * is not a network url, it will be loaded with {link 1313 * {@link #loadUrl(String)} instead. 1314 * 1315 * @param url The url of the resource to load. 1316 * @param postData The data will be passed to "POST" request. 1317 */ 1318 public void postUrl(String url, byte[] postData) { 1319 if (URLUtil.isNetworkUrl(url)) { 1320 switchOutDrawHistory(); 1321 WebViewCore.PostUrlData arg = new WebViewCore.PostUrlData(); 1322 arg.mUrl = url; 1323 arg.mPostData = postData; 1324 mWebViewCore.sendMessage(EventHub.POST_URL, arg); 1325 clearTextEntry(); 1326 } else { 1327 loadUrl(url); 1328 } 1329 } 1330 1331 /** 1332 * Load the given data into the WebView. This will load the data into 1333 * WebView using the data: scheme. Content loaded through this mechanism 1334 * does not have the ability to load content from the network. 1335 * @param data A String of data in the given encoding. 1336 * @param mimeType The MIMEType of the data. i.e. text/html, image/jpeg 1337 * @param encoding The encoding of the data. i.e. utf-8, base64 1338 */ 1339 public void loadData(String data, String mimeType, String encoding) { 1340 loadUrl("data:" + mimeType + ";" + encoding + "," + data); 1341 } 1342 1343 /** 1344 * Load the given data into the WebView, use the provided URL as the base 1345 * URL for the content. The base URL is the URL that represents the page 1346 * that is loaded through this interface. As such, it is used for the 1347 * history entry and to resolve any relative URLs. The failUrl is used if 1348 * browser fails to load the data provided. If it is empty or null, and the 1349 * load fails, then no history entry is created. 1350 * <p> 1351 * Note for post 1.0. Due to the change in the WebKit, the access to asset 1352 * files through "file:///android_asset/" for the sub resources is more 1353 * restricted. If you provide null or empty string as baseUrl, you won't be 1354 * able to access asset files. If the baseUrl is anything other than 1355 * http(s)/ftp(s)/about/javascript as scheme, you can access asset files for 1356 * sub resources. 1357 * 1358 * @param baseUrl Url to resolve relative paths with, if null defaults to 1359 * "about:blank" 1360 * @param data A String of data in the given encoding. 1361 * @param mimeType The MIMEType of the data. i.e. text/html. If null, 1362 * defaults to "text/html" 1363 * @param encoding The encoding of the data. i.e. utf-8, us-ascii 1364 * @param failUrl URL to use if the content fails to load or null. 1365 */ 1366 public void loadDataWithBaseURL(String baseUrl, String data, 1367 String mimeType, String encoding, String failUrl) { 1368 1369 if (baseUrl != null && baseUrl.toLowerCase().startsWith("data:")) { 1370 loadData(data, mimeType, encoding); 1371 return; 1372 } 1373 switchOutDrawHistory(); 1374 WebViewCore.BaseUrlData arg = new WebViewCore.BaseUrlData(); 1375 arg.mBaseUrl = baseUrl; 1376 arg.mData = data; 1377 arg.mMimeType = mimeType; 1378 arg.mEncoding = encoding; 1379 arg.mFailUrl = failUrl; 1380 mWebViewCore.sendMessage(EventHub.LOAD_DATA, arg); 1381 clearTextEntry(); 1382 } 1383 1384 /** 1385 * Stop the current load. 1386 */ 1387 public void stopLoading() { 1388 // TODO: should we clear all the messages in the queue before sending 1389 // STOP_LOADING? 1390 switchOutDrawHistory(); 1391 mWebViewCore.sendMessage(EventHub.STOP_LOADING); 1392 } 1393 1394 /** 1395 * Reload the current url. 1396 */ 1397 public void reload() { 1398 switchOutDrawHistory(); 1399 mWebViewCore.sendMessage(EventHub.RELOAD); 1400 } 1401 1402 /** 1403 * Return true if this WebView has a back history item. 1404 * @return True iff this WebView has a back history item. 1405 */ 1406 public boolean canGoBack() { 1407 WebBackForwardList l = mCallbackProxy.getBackForwardList(); 1408 synchronized (l) { 1409 if (l.getClearPending()) { 1410 return false; 1411 } else { 1412 return l.getCurrentIndex() > 0; 1413 } 1414 } 1415 } 1416 1417 /** 1418 * Go back in the history of this WebView. 1419 */ 1420 public void goBack() { 1421 goBackOrForward(-1); 1422 } 1423 1424 /** 1425 * Return true if this WebView has a forward history item. 1426 * @return True iff this Webview has a forward history item. 1427 */ 1428 public boolean canGoForward() { 1429 WebBackForwardList l = mCallbackProxy.getBackForwardList(); 1430 synchronized (l) { 1431 if (l.getClearPending()) { 1432 return false; 1433 } else { 1434 return l.getCurrentIndex() < l.getSize() - 1; 1435 } 1436 } 1437 } 1438 1439 /** 1440 * Go forward in the history of this WebView. 1441 */ 1442 public void goForward() { 1443 goBackOrForward(1); 1444 } 1445 1446 /** 1447 * Return true if the page can go back or forward the given 1448 * number of steps. 1449 * @param steps The negative or positive number of steps to move the 1450 * history. 1451 */ 1452 public boolean canGoBackOrForward(int steps) { 1453 WebBackForwardList l = mCallbackProxy.getBackForwardList(); 1454 synchronized (l) { 1455 if (l.getClearPending()) { 1456 return false; 1457 } else { 1458 int newIndex = l.getCurrentIndex() + steps; 1459 return newIndex >= 0 && newIndex < l.getSize(); 1460 } 1461 } 1462 } 1463 1464 /** 1465 * Go to the history item that is the number of steps away from 1466 * the current item. Steps is negative if backward and positive 1467 * if forward. 1468 * @param steps The number of steps to take back or forward in the back 1469 * forward list. 1470 */ 1471 public void goBackOrForward(int steps) { 1472 goBackOrForward(steps, false); 1473 } 1474 1475 private void goBackOrForward(int steps, boolean ignoreSnapshot) { 1476 // every time we go back or forward, we want to reset the 1477 // WebView certificate: 1478 // if the new site is secure, we will reload it and get a 1479 // new certificate set; 1480 // if the new site is not secure, the certificate must be 1481 // null, and that will be the case 1482 mCertificate = null; 1483 if (steps != 0) { 1484 clearTextEntry(); 1485 mWebViewCore.sendMessage(EventHub.GO_BACK_FORWARD, steps, 1486 ignoreSnapshot ? 1 : 0); 1487 } 1488 } 1489 1490 private boolean extendScroll(int y) { 1491 int finalY = mScroller.getFinalY(); 1492 int newY = pinLocY(finalY + y); 1493 if (newY == finalY) return false; 1494 mScroller.setFinalY(newY); 1495 mScroller.extendDuration(computeDuration(0, y)); 1496 return true; 1497 } 1498 1499 /** 1500 * Scroll the contents of the view up by half the view size 1501 * @param top true to jump to the top of the page 1502 * @return true if the page was scrolled 1503 */ 1504 public boolean pageUp(boolean top) { 1505 if (mNativeClass == 0) { 1506 return false; 1507 } 1508 nativeClearCursor(); // start next trackball movement from page edge 1509 if (top) { 1510 // go to the top of the document 1511 return pinScrollTo(mScrollX, 0, true, 0); 1512 } 1513 // Page up 1514 int h = getHeight(); 1515 int y; 1516 if (h > 2 * PAGE_SCROLL_OVERLAP) { 1517 y = -h + PAGE_SCROLL_OVERLAP; 1518 } else { 1519 y = -h / 2; 1520 } 1521 mUserScroll = true; 1522 return mScroller.isFinished() ? pinScrollBy(0, y, true, 0) 1523 : extendScroll(y); 1524 } 1525 1526 /** 1527 * Scroll the contents of the view down by half the page size 1528 * @param bottom true to jump to bottom of page 1529 * @return true if the page was scrolled 1530 */ 1531 public boolean pageDown(boolean bottom) { 1532 if (mNativeClass == 0) { 1533 return false; 1534 } 1535 nativeClearCursor(); // start next trackball movement from page edge 1536 if (bottom) { 1537 return pinScrollTo(mScrollX, mContentHeight, true, 0); 1538 } 1539 // Page down. 1540 int h = getHeight(); 1541 int y; 1542 if (h > 2 * PAGE_SCROLL_OVERLAP) { 1543 y = h - PAGE_SCROLL_OVERLAP; 1544 } else { 1545 y = h / 2; 1546 } 1547 mUserScroll = true; 1548 return mScroller.isFinished() ? pinScrollBy(0, y, true, 0) 1549 : extendScroll(y); 1550 } 1551 1552 /** 1553 * Clear the view so that onDraw() will draw nothing but white background, 1554 * and onMeasure() will return 0 if MeasureSpec is not MeasureSpec.EXACTLY 1555 */ 1556 public void clearView() { 1557 mContentWidth = 0; 1558 mContentHeight = 0; 1559 mWebViewCore.sendMessage(EventHub.CLEAR_CONTENT); 1560 } 1561 1562 /** 1563 * Return a new picture that captures the current display of the webview. 1564 * This is a copy of the display, and will be unaffected if the webview 1565 * later loads a different URL. 1566 * 1567 * @return a picture containing the current contents of the view. Note this 1568 * picture is of the entire document, and is not restricted to the 1569 * bounds of the view. 1570 */ 1571 public Picture capturePicture() { 1572 if (null == mWebViewCore) return null; // check for out of memory tab 1573 return mWebViewCore.copyContentPicture(); 1574 } 1575 1576 /** 1577 * Return true if the browser is displaying a TextView for text input. 1578 */ 1579 private boolean inEditingMode() { 1580 return mWebTextView != null && mWebTextView.getParent() != null 1581 && mWebTextView.hasFocus(); 1582 } 1583 1584 private void clearTextEntry() { 1585 if (inEditingMode()) { 1586 mWebTextView.remove(); 1587 } 1588 } 1589 1590 /** 1591 * Return the current scale of the WebView 1592 * @return The current scale. 1593 */ 1594 public float getScale() { 1595 return mActualScale; 1596 } 1597 1598 /** 1599 * Set the initial scale for the WebView. 0 means default. If 1600 * {@link WebSettings#getUseWideViewPort()} is true, it zooms out all the 1601 * way. Otherwise it starts with 100%. If initial scale is greater than 0, 1602 * WebView starts will this value as initial scale. 1603 * 1604 * @param scaleInPercent The initial scale in percent. 1605 */ 1606 public void setInitialScale(int scaleInPercent) { 1607 mInitialScale = scaleInPercent; 1608 } 1609 1610 /** 1611 * Invoke the graphical zoom picker widget for this WebView. This will 1612 * result in the zoom widget appearing on the screen to control the zoom 1613 * level of this WebView. 1614 */ 1615 public void invokeZoomPicker() { 1616 if (!getSettings().supportZoom()) { 1617 Log.w(LOGTAG, "This WebView doesn't support zoom."); 1618 return; 1619 } 1620 clearTextEntry(); 1621 if (getSettings().getBuiltInZoomControls()) { 1622 mZoomButtonsController.setVisible(true); 1623 } else { 1624 mPrivateHandler.removeCallbacks(mZoomControlRunnable); 1625 mPrivateHandler.postDelayed(mZoomControlRunnable, 1626 ZOOM_CONTROLS_TIMEOUT); 1627 } 1628 } 1629 1630 /** 1631 * Return a HitTestResult based on the current cursor node. If a HTML::a tag 1632 * is found and the anchor has a non-javascript url, the HitTestResult type 1633 * is set to SRC_ANCHOR_TYPE and the url is set in the "extra" field. If the 1634 * anchor does not have a url or if it is a javascript url, the type will 1635 * be UNKNOWN_TYPE and the url has to be retrieved through 1636 * {@link #requestFocusNodeHref} asynchronously. If a HTML::img tag is 1637 * found, the HitTestResult type is set to IMAGE_TYPE and the url is set in 1638 * the "extra" field. A type of 1639 * SRC_IMAGE_ANCHOR_TYPE indicates an anchor with a url that has an image as 1640 * a child node. If a phone number is found, the HitTestResult type is set 1641 * to PHONE_TYPE and the phone number is set in the "extra" field of 1642 * HitTestResult. If a map address is found, the HitTestResult type is set 1643 * to GEO_TYPE and the address is set in the "extra" field of HitTestResult. 1644 * If an email address is found, the HitTestResult type is set to EMAIL_TYPE 1645 * and the email is set in the "extra" field of HitTestResult. Otherwise, 1646 * HitTestResult type is set to UNKNOWN_TYPE. 1647 */ 1648 public HitTestResult getHitTestResult() { 1649 if (mNativeClass == 0) { 1650 return null; 1651 } 1652 1653 HitTestResult result = new HitTestResult(); 1654 if (nativeHasCursorNode()) { 1655 if (nativeCursorIsTextInput()) { 1656 result.setType(HitTestResult.EDIT_TEXT_TYPE); 1657 } else { 1658 String text = nativeCursorText(); 1659 if (text != null) { 1660 if (text.startsWith(SCHEME_TEL)) { 1661 result.setType(HitTestResult.PHONE_TYPE); 1662 result.setExtra(text.substring(SCHEME_TEL.length())); 1663 } else if (text.startsWith(SCHEME_MAILTO)) { 1664 result.setType(HitTestResult.EMAIL_TYPE); 1665 result.setExtra(text.substring(SCHEME_MAILTO.length())); 1666 } else if (text.startsWith(SCHEME_GEO)) { 1667 result.setType(HitTestResult.GEO_TYPE); 1668 result.setExtra(URLDecoder.decode(text 1669 .substring(SCHEME_GEO.length()))); 1670 } else if (nativeCursorIsAnchor()) { 1671 result.setType(HitTestResult.SRC_ANCHOR_TYPE); 1672 result.setExtra(text); 1673 } 1674 } 1675 } 1676 } 1677 int type = result.getType(); 1678 if (type == HitTestResult.UNKNOWN_TYPE 1679 || type == HitTestResult.SRC_ANCHOR_TYPE) { 1680 // Now check to see if it is an image. 1681 int contentX = viewToContentX((int) mLastTouchX + mScrollX); 1682 int contentY = viewToContentY((int) mLastTouchY + mScrollY); 1683 String text = nativeImageURI(contentX, contentY); 1684 if (text != null) { 1685 result.setType(type == HitTestResult.UNKNOWN_TYPE ? 1686 HitTestResult.IMAGE_TYPE : 1687 HitTestResult.SRC_IMAGE_ANCHOR_TYPE); 1688 result.setExtra(text); 1689 } 1690 } 1691 return result; 1692 } 1693 1694 /** 1695 * Request the href of an anchor element due to getFocusNodePath returning 1696 * "href." If hrefMsg is null, this method returns immediately and does not 1697 * dispatch hrefMsg to its target. 1698 * 1699 * @param hrefMsg This message will be dispatched with the result of the 1700 * request as the data member with "url" as key. The result can 1701 * be null. 1702 */ 1703 // FIXME: API change required to change the name of this function. We now 1704 // look at the cursor node, and not the focus node. Also, what is 1705 // getFocusNodePath? 1706 public void requestFocusNodeHref(Message hrefMsg) { 1707 if (hrefMsg == null || mNativeClass == 0) { 1708 return; 1709 } 1710 if (nativeCursorIsAnchor()) { 1711 mWebViewCore.sendMessage(EventHub.REQUEST_CURSOR_HREF, 1712 nativeCursorFramePointer(), nativeCursorNodePointer(), 1713 hrefMsg); 1714 } 1715 } 1716 1717 /** 1718 * Request the url of the image last touched by the user. msg will be sent 1719 * to its target with a String representing the url as its object. 1720 * 1721 * @param msg This message will be dispatched with the result of the request 1722 * as the data member with "url" as key. The result can be null. 1723 */ 1724 public void requestImageRef(Message msg) { 1725 int contentX = viewToContentX((int) mLastTouchX + mScrollX); 1726 int contentY = viewToContentY((int) mLastTouchY + mScrollY); 1727 String ref = nativeImageURI(contentX, contentY); 1728 Bundle data = msg.getData(); 1729 data.putString("url", ref); 1730 msg.setData(data); 1731 msg.sendToTarget(); 1732 } 1733 1734 private static int pinLoc(int x, int viewMax, int docMax) { 1735// Log.d(LOGTAG, "-- pinLoc " + x + " " + viewMax + " " + docMax); 1736 if (docMax < viewMax) { // the doc has room on the sides for "blank" 1737 // pin the short document to the top/left of the screen 1738 x = 0; 1739// Log.d(LOGTAG, "--- center " + x); 1740 } else if (x < 0) { 1741 x = 0; 1742// Log.d(LOGTAG, "--- zero"); 1743 } else if (x + viewMax > docMax) { 1744 x = docMax - viewMax; 1745// Log.d(LOGTAG, "--- pin " + x); 1746 } 1747 return x; 1748 } 1749 1750 // Expects x in view coordinates 1751 private int pinLocX(int x) { 1752 return pinLoc(x, getViewWidth(), computeHorizontalScrollRange()); 1753 } 1754 1755 // Expects y in view coordinates 1756 private int pinLocY(int y) { 1757 int titleH = getTitleHeight(); 1758 // if the titlebar is still visible, just pin against 0 1759 if (y <= titleH) { 1760 return Math.max(y, 0); 1761 } 1762 // convert to 0-based coordinate (subtract the title height) 1763 // pin(), and then add the title height back in 1764 return pinLoc(y - titleH, getViewHeight(), 1765 computeVerticalScrollRange()) + titleH; 1766 } 1767 1768 /** 1769 * A title bar which is embedded in this WebView, and scrolls along with it 1770 * vertically, but not horizontally. 1771 */ 1772 private View mTitleBar; 1773 1774 /** 1775 * Add or remove a title bar to be embedded into the WebView, and scroll 1776 * along with it vertically, while remaining in view horizontally. Pass 1777 * null to remove the title bar from the WebView, and return to drawing 1778 * the WebView normally without translating to account for the title bar. 1779 * @hide 1780 */ 1781 public void setEmbeddedTitleBar(View v) { 1782 if (mTitleBar == v) return; 1783 if (mTitleBar != null) { 1784 removeView(mTitleBar); 1785 } 1786 if (null != v) { 1787 addView(v, new AbsoluteLayout.LayoutParams( 1788 ViewGroup.LayoutParams.FILL_PARENT, 1789 ViewGroup.LayoutParams.WRAP_CONTENT, 0, 0)); 1790 } 1791 mTitleBar = v; 1792 } 1793 1794 /** 1795 * Given an x coordinate in view space, convert it to content space. Also 1796 * may be used for absolute heights (such as for the WebTextView's 1797 * textSize, which is unaffected by the height of the title bar). 1798 */ 1799 /*package*/ int viewToContentX(int x) { 1800 return Math.round(x * mInvActualScale); 1801 } 1802 1803 /** 1804 * Given a y coordinate in view space, convert it to content space. 1805 * Takes into account the height of the title bar if there is one 1806 * embedded into the WebView. 1807 */ 1808 /*package*/ int viewToContentY(int y) { 1809 return viewToContentX(y - getTitleHeight()); 1810 } 1811 1812 /** 1813 * Given a distance in content space, convert it to view space. Note: this 1814 * does not reflect translation, just scaling, so this should not be called 1815 * with coordinates, but should be called for dimensions like width or 1816 * height. 1817 */ 1818 /*package*/ int contentToViewDimension(int d) { 1819 return Math.round(d * mActualScale); 1820 } 1821 1822 /** 1823 * Given an x coordinate in content space, convert it to view 1824 * space. Also used for absolute heights. 1825 */ 1826 /*package*/ int contentToViewX(int x) { 1827 return contentToViewDimension(x); 1828 } 1829 1830 /** 1831 * Given a y coordinate in content space, convert it to view 1832 * space. Takes into account the height of the title bar. 1833 */ 1834 /*package*/ int contentToViewY(int y) { 1835 return contentToViewDimension(y) + getTitleHeight(); 1836 } 1837 1838 // Called by JNI to invalidate the View, given rectangle coordinates in 1839 // content space 1840 private void viewInvalidate(int l, int t, int r, int b) { 1841 invalidate(contentToViewX(l), contentToViewY(t), contentToViewX(r), 1842 contentToViewY(b)); 1843 } 1844 1845 // Called by JNI to invalidate the View after a delay, given rectangle 1846 // coordinates in content space 1847 private void viewInvalidateDelayed(long delay, int l, int t, int r, int b) { 1848 postInvalidateDelayed(delay, contentToViewX(l), contentToViewY(t), 1849 contentToViewX(r), contentToViewY(b)); 1850 } 1851 1852 private Rect contentToView(Rect x) { 1853 return new Rect(contentToViewX(x.left), contentToViewY(x.top) 1854 , contentToViewX(x.right), contentToViewY(x.bottom)); 1855 } 1856 1857 // stop the scroll animation, and don't let a subsequent fling add 1858 // to the existing velocity 1859 private void abortAnimation() { 1860 mScroller.abortAnimation(); 1861 mLastVelocity = 0; 1862 } 1863 1864 /* call from webcoreview.draw(), so we're still executing in the UI thread 1865 */ 1866 private void recordNewContentSize(int w, int h, boolean updateLayout) { 1867 1868 // premature data from webkit, ignore 1869 if ((w | h) == 0) { 1870 return; 1871 } 1872 1873 // don't abort a scroll animation if we didn't change anything 1874 if (mContentWidth != w || mContentHeight != h) { 1875 // record new dimensions 1876 mContentWidth = w; 1877 mContentHeight = h; 1878 // If history Picture is drawn, don't update scroll. They will be 1879 // updated when we get out of that mode. 1880 if (!mDrawHistory) { 1881 // repin our scroll, taking into account the new content size 1882 int oldX = mScrollX; 1883 int oldY = mScrollY; 1884 mScrollX = pinLocX(mScrollX); 1885 mScrollY = pinLocY(mScrollY); 1886 // android.util.Log.d("skia", "recordNewContentSize - 1887 // abortAnimation"); 1888 abortAnimation(); // just in case 1889 if (oldX != mScrollX || oldY != mScrollY) { 1890 sendOurVisibleRect(); 1891 } 1892 } 1893 } 1894 contentSizeChanged(updateLayout); 1895 } 1896 1897 private void setNewZoomScale(float scale, boolean force) { 1898 if (scale < mMinZoomScale) { 1899 scale = mMinZoomScale; 1900 } else if (scale > mMaxZoomScale) { 1901 scale = mMaxZoomScale; 1902 } 1903 if (scale != mActualScale || force) { 1904 if (mDrawHistory) { 1905 // If history Picture is drawn, don't update scroll. They will 1906 // be updated when we get out of that mode. 1907 if (scale != mActualScale && !mPreviewZoomOnly) { 1908 mCallbackProxy.onScaleChanged(mActualScale, scale); 1909 } 1910 mActualScale = scale; 1911 mInvActualScale = 1 / scale; 1912 if (!mPreviewZoomOnly) { 1913 sendViewSizeZoom(); 1914 } 1915 } else { 1916 // update our scroll so we don't appear to jump 1917 // i.e. keep the center of the doc in the center of the view 1918 1919 int oldX = mScrollX; 1920 int oldY = mScrollY; 1921 float ratio = scale * mInvActualScale; // old inverse 1922 float sx = ratio * oldX + (ratio - 1) * mZoomCenterX; 1923 float sy = ratio * oldY + (ratio - 1) * mZoomCenterY; 1924 1925 // now update our new scale and inverse 1926 if (scale != mActualScale && !mPreviewZoomOnly) { 1927 mCallbackProxy.onScaleChanged(mActualScale, scale); 1928 } 1929 mActualScale = scale; 1930 mInvActualScale = 1 / scale; 1931 1932 // Scale all the child views 1933 mViewManager.scaleAll(); 1934 1935 // as we don't have animation for scaling, don't do animation 1936 // for scrolling, as it causes weird intermediate state 1937 // pinScrollTo(Math.round(sx), Math.round(sy)); 1938 mScrollX = pinLocX(Math.round(sx)); 1939 mScrollY = pinLocY(Math.round(sy)); 1940 1941 if (!mPreviewZoomOnly) { 1942 sendViewSizeZoom(); 1943 sendOurVisibleRect(); 1944 } 1945 } 1946 } 1947 } 1948 1949 // Used to avoid sending many visible rect messages. 1950 private Rect mLastVisibleRectSent; 1951 private Rect mLastGlobalRect; 1952 1953 private Rect sendOurVisibleRect() { 1954 Rect rect = new Rect(); 1955 calcOurContentVisibleRect(rect); 1956 // Rect.equals() checks for null input. 1957 if (!rect.equals(mLastVisibleRectSent)) { 1958 Point pos = new Point(rect.left, rect.top); 1959 mWebViewCore.sendMessage(EventHub.SET_SCROLL_OFFSET, 1960 nativeMoveGeneration(), 0, pos); 1961 mLastVisibleRectSent = rect; 1962 } 1963 Rect globalRect = new Rect(); 1964 if (getGlobalVisibleRect(globalRect) 1965 && !globalRect.equals(mLastGlobalRect)) { 1966 if (DebugFlags.WEB_VIEW) { 1967 Log.v(LOGTAG, "sendOurVisibleRect=(" + globalRect.left + "," 1968 + globalRect.top + ",r=" + globalRect.right + ",b=" 1969 + globalRect.bottom); 1970 } 1971 // TODO: the global offset is only used by windowRect() 1972 // in ChromeClientAndroid ; other clients such as touch 1973 // and mouse events could return view + screen relative points. 1974 mWebViewCore.sendMessage(EventHub.SET_GLOBAL_BOUNDS, globalRect); 1975 mLastGlobalRect = globalRect; 1976 } 1977 return rect; 1978 } 1979 1980 // Sets r to be the visible rectangle of our webview in view coordinates 1981 private void calcOurVisibleRect(Rect r) { 1982 Point p = new Point(); 1983 getGlobalVisibleRect(r, p); 1984 r.offset(-p.x, -p.y); 1985 if (mFindIsUp) { 1986 r.bottom -= FIND_HEIGHT; 1987 } 1988 } 1989 1990 // Sets r to be our visible rectangle in content coordinates 1991 private void calcOurContentVisibleRect(Rect r) { 1992 calcOurVisibleRect(r); 1993 r.left = viewToContentX(r.left); 1994 r.top = viewToContentY(r.top); 1995 r.right = viewToContentX(r.right); 1996 r.bottom = viewToContentY(r.bottom); 1997 } 1998 1999 static class ViewSizeData { 2000 int mWidth; 2001 int mHeight; 2002 int mTextWrapWidth; 2003 float mScale; 2004 boolean mIgnoreHeight; 2005 } 2006 2007 /** 2008 * Compute unzoomed width and height, and if they differ from the last 2009 * values we sent, send them to webkit (to be used has new viewport) 2010 * 2011 * @return true if new values were sent 2012 */ 2013 private boolean sendViewSizeZoom() { 2014 int viewWidth = getViewWidth(); 2015 int newWidth = Math.round(viewWidth * mInvActualScale); 2016 int newHeight = Math.round(getViewHeight() * mInvActualScale); 2017 /* 2018 * Because the native side may have already done a layout before the 2019 * View system was able to measure us, we have to send a height of 0 to 2020 * remove excess whitespace when we grow our width. This will trigger a 2021 * layout and a change in content size. This content size change will 2022 * mean that contentSizeChanged will either call this method directly or 2023 * indirectly from onSizeChanged. 2024 */ 2025 if (newWidth > mLastWidthSent && mWrapContent) { 2026 newHeight = 0; 2027 } 2028 // Avoid sending another message if the dimensions have not changed. 2029 if (newWidth != mLastWidthSent || newHeight != mLastHeightSent) { 2030 ViewSizeData data = new ViewSizeData(); 2031 data.mWidth = newWidth; 2032 data.mHeight = newHeight; 2033 // while in zoom overview mode, the text are wrapped to the screen 2034 // width matching mLastScale. So that we don't trigger re-flow while 2035 // toggling between overview mode and normal mode. 2036 data.mTextWrapWidth = mInZoomOverview ? Math.round(viewWidth 2037 / mLastScale) : newWidth; 2038 data.mScale = mActualScale; 2039 data.mIgnoreHeight = mZoomScale != 0 && !mHeightCanMeasure; 2040 mWebViewCore.sendMessage(EventHub.VIEW_SIZE_CHANGED, data); 2041 mLastWidthSent = newWidth; 2042 mLastHeightSent = newHeight; 2043 return true; 2044 } 2045 return false; 2046 } 2047 2048 @Override 2049 protected int computeHorizontalScrollRange() { 2050 if (mDrawHistory) { 2051 return mHistoryWidth; 2052 } else { 2053 // to avoid rounding error caused unnecessary scrollbar, use floor 2054 return (int) Math.floor(mContentWidth * mActualScale); 2055 } 2056 } 2057 2058 // Make sure this stays in sync with the actual height of the FindDialog. 2059 private static final int FIND_HEIGHT = 79; 2060 2061 @Override 2062 protected int computeVerticalScrollRange() { 2063 if (mDrawHistory) { 2064 return mHistoryHeight; 2065 } else { 2066 // to avoid rounding error caused unnecessary scrollbar, use floor 2067 return (int) Math.floor(mContentHeight * mActualScale); 2068 } 2069 } 2070 2071 @Override 2072 protected int computeVerticalScrollOffset() { 2073 return Math.max(mScrollY - getTitleHeight(), 0); 2074 } 2075 2076 @Override 2077 protected int computeVerticalScrollExtent() { 2078 return getViewHeight(); 2079 } 2080 2081 /** @hide */ 2082 @Override 2083 protected void onDrawVerticalScrollBar(Canvas canvas, 2084 Drawable scrollBar, 2085 int l, int t, int r, int b) { 2086 scrollBar.setBounds(l, t + getVisibleTitleHeight(), r, b); 2087 scrollBar.draw(canvas); 2088 } 2089 2090 /** 2091 * Get the url for the current page. This is not always the same as the url 2092 * passed to WebViewClient.onPageStarted because although the load for 2093 * that url has begun, the current page may not have changed. 2094 * @return The url for the current page. 2095 */ 2096 public String getUrl() { 2097 WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem(); 2098 return h != null ? h.getUrl() : null; 2099 } 2100 2101 /** 2102 * Get the original url for the current page. This is not always the same 2103 * as the url passed to WebViewClient.onPageStarted because although the 2104 * load for that url has begun, the current page may not have changed. 2105 * Also, there may have been redirects resulting in a different url to that 2106 * originally requested. 2107 * @return The url that was originally requested for the current page. 2108 */ 2109 public String getOriginalUrl() { 2110 WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem(); 2111 return h != null ? h.getOriginalUrl() : null; 2112 } 2113 2114 /** 2115 * Get the title for the current page. This is the title of the current page 2116 * until WebViewClient.onReceivedTitle is called. 2117 * @return The title for the current page. 2118 */ 2119 public String getTitle() { 2120 WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem(); 2121 return h != null ? h.getTitle() : null; 2122 } 2123 2124 /** 2125 * Get the favicon for the current page. This is the favicon of the current 2126 * page until WebViewClient.onReceivedIcon is called. 2127 * @return The favicon for the current page. 2128 */ 2129 public Bitmap getFavicon() { 2130 WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem(); 2131 return h != null ? h.getFavicon() : null; 2132 } 2133 2134 /** 2135 * Get the touch icon url for the apple-touch-icon <link> element. 2136 * @hide 2137 */ 2138 public String getTouchIconUrl() { 2139 WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem(); 2140 return h != null ? h.getTouchIconUrl() : null; 2141 } 2142 2143 /** 2144 * Get the progress for the current page. 2145 * @return The progress for the current page between 0 and 100. 2146 */ 2147 public int getProgress() { 2148 return mCallbackProxy.getProgress(); 2149 } 2150 2151 /** 2152 * @return the height of the HTML content. 2153 */ 2154 public int getContentHeight() { 2155 return mContentHeight; 2156 } 2157 2158 /** 2159 * Pause all layout, parsing, and javascript timers for all webviews. This 2160 * is a global requests, not restricted to just this webview. This can be 2161 * useful if the application has been paused. 2162 */ 2163 public void pauseTimers() { 2164 mWebViewCore.sendMessage(EventHub.PAUSE_TIMERS); 2165 } 2166 2167 /** 2168 * Resume all layout, parsing, and javascript timers for all webviews. 2169 * This will resume dispatching all timers. 2170 */ 2171 public void resumeTimers() { 2172 mWebViewCore.sendMessage(EventHub.RESUME_TIMERS); 2173 } 2174 2175 /** 2176 * Call this to pause any extra processing associated with this view and 2177 * its associated DOM/plugins/javascript/etc. For example, if the view is 2178 * taken offscreen, this could be called to reduce unnecessary CPU and/or 2179 * network traffic. When the view is again "active", call onResume(). 2180 * 2181 * Note that this differs from pauseTimers(), which affects all views/DOMs 2182 * @hide 2183 */ 2184 public void onPause() { 2185 if (!mIsPaused) { 2186 mIsPaused = true; 2187 mWebViewCore.sendMessage(EventHub.ON_PAUSE); 2188 } 2189 } 2190 2191 /** 2192 * Call this to balanace a previous call to onPause() 2193 * @hide 2194 */ 2195 public void onResume() { 2196 if (mIsPaused) { 2197 mIsPaused = false; 2198 mWebViewCore.sendMessage(EventHub.ON_RESUME); 2199 } 2200 } 2201 2202 /** 2203 * Returns true if the view is paused, meaning onPause() was called. Calling 2204 * onResume() sets the paused state back to false. 2205 * @hide 2206 */ 2207 public boolean isPaused() { 2208 return mIsPaused; 2209 } 2210 2211 /** 2212 * Call this to inform the view that memory is low so that it can 2213 * free any available memory. 2214 * @hide 2215 */ 2216 public void freeMemory() { 2217 mWebViewCore.sendMessage(EventHub.FREE_MEMORY); 2218 } 2219 2220 /** 2221 * Clear the resource cache. Note that the cache is per-application, so 2222 * this will clear the cache for all WebViews used. 2223 * 2224 * @param includeDiskFiles If false, only the RAM cache is cleared. 2225 */ 2226 public void clearCache(boolean includeDiskFiles) { 2227 // Note: this really needs to be a static method as it clears cache for all 2228 // WebView. But we need mWebViewCore to send message to WebCore thread, so 2229 // we can't make this static. 2230 mWebViewCore.sendMessage(EventHub.CLEAR_CACHE, 2231 includeDiskFiles ? 1 : 0, 0); 2232 } 2233 2234 /** 2235 * Make sure that clearing the form data removes the adapter from the 2236 * currently focused textfield if there is one. 2237 */ 2238 public void clearFormData() { 2239 if (inEditingMode()) { 2240 AutoCompleteAdapter adapter = null; 2241 mWebTextView.setAdapterCustom(adapter); 2242 } 2243 } 2244 2245 /** 2246 * Tell the WebView to clear its internal back/forward list. 2247 */ 2248 public void clearHistory() { 2249 mCallbackProxy.getBackForwardList().setClearPending(); 2250 mWebViewCore.sendMessage(EventHub.CLEAR_HISTORY); 2251 } 2252 2253 /** 2254 * Clear the SSL preferences table stored in response to proceeding with SSL 2255 * certificate errors. 2256 */ 2257 public void clearSslPreferences() { 2258 mWebViewCore.sendMessage(EventHub.CLEAR_SSL_PREF_TABLE); 2259 } 2260 2261 /** 2262 * Return the WebBackForwardList for this WebView. This contains the 2263 * back/forward list for use in querying each item in the history stack. 2264 * This is a copy of the private WebBackForwardList so it contains only a 2265 * snapshot of the current state. Multiple calls to this method may return 2266 * different objects. The object returned from this method will not be 2267 * updated to reflect any new state. 2268 */ 2269 public WebBackForwardList copyBackForwardList() { 2270 return mCallbackProxy.getBackForwardList().clone(); 2271 } 2272 2273 /* 2274 * Highlight and scroll to the next occurance of String in findAll. 2275 * Wraps the page infinitely, and scrolls. Must be called after 2276 * calling findAll. 2277 * 2278 * @param forward Direction to search. 2279 */ 2280 public void findNext(boolean forward) { 2281 nativeFindNext(forward); 2282 } 2283 2284 /* 2285 * Find all instances of find on the page and highlight them. 2286 * @param find String to find. 2287 * @return int The number of occurances of the String "find" 2288 * that were found. 2289 */ 2290 public int findAll(String find) { 2291 mFindIsUp = true; 2292 int result = nativeFindAll(find.toLowerCase(), find.toUpperCase()); 2293 invalidate(); 2294 return result; 2295 } 2296 2297 // Used to know whether the find dialog is open. Affects whether 2298 // or not we draw the highlights for matches. 2299 private boolean mFindIsUp; 2300 2301 /** 2302 * Return the first substring consisting of the address of a physical 2303 * location. Currently, only addresses in the United States are detected, 2304 * and consist of: 2305 * - a house number 2306 * - a street name 2307 * - a street type (Road, Circle, etc), either spelled out or abbreviated 2308 * - a city name 2309 * - a state or territory, either spelled out or two-letter abbr. 2310 * - an optional 5 digit or 9 digit zip code. 2311 * 2312 * All names must be correctly capitalized, and the zip code, if present, 2313 * must be valid for the state. The street type must be a standard USPS 2314 * spelling or abbreviation. The state or territory must also be spelled 2315 * or abbreviated using USPS standards. The house number may not exceed 2316 * five digits. 2317 * @param addr The string to search for addresses. 2318 * 2319 * @return the address, or if no address is found, return null. 2320 */ 2321 public static String findAddress(String addr) { 2322 return findAddress(addr, false); 2323 } 2324 2325 /** 2326 * @hide 2327 * Return the first substring consisting of the address of a physical 2328 * location. Currently, only addresses in the United States are detected, 2329 * and consist of: 2330 * - a house number 2331 * - a street name 2332 * - a street type (Road, Circle, etc), either spelled out or abbreviated 2333 * - a city name 2334 * - a state or territory, either spelled out or two-letter abbr. 2335 * - an optional 5 digit or 9 digit zip code. 2336 * 2337 * Names are optionally capitalized, and the zip code, if present, 2338 * must be valid for the state. The street type must be a standard USPS 2339 * spelling or abbreviation. The state or territory must also be spelled 2340 * or abbreviated using USPS standards. The house number may not exceed 2341 * five digits. 2342 * @param addr The string to search for addresses. 2343 * @param caseInsensitive addr Set to true to make search ignore case. 2344 * 2345 * @return the address, or if no address is found, return null. 2346 */ 2347 public static String findAddress(String addr, boolean caseInsensitive) { 2348 return WebViewCore.nativeFindAddress(addr, caseInsensitive); 2349 } 2350 2351 /* 2352 * Clear the highlighting surrounding text matches created by findAll. 2353 */ 2354 public void clearMatches() { 2355 mFindIsUp = false; 2356 nativeSetFindIsDown(); 2357 // Now that the dialog has been removed, ensure that we scroll to a 2358 // location that is not beyond the end of the page. 2359 pinScrollTo(mScrollX, mScrollY, false, 0); 2360 invalidate(); 2361 } 2362 2363 /** 2364 * Query the document to see if it contains any image references. The 2365 * message object will be dispatched with arg1 being set to 1 if images 2366 * were found and 0 if the document does not reference any images. 2367 * @param response The message that will be dispatched with the result. 2368 */ 2369 public void documentHasImages(Message response) { 2370 if (response == null) { 2371 return; 2372 } 2373 mWebViewCore.sendMessage(EventHub.DOC_HAS_IMAGES, response); 2374 } 2375 2376 @Override 2377 public void computeScroll() { 2378 if (mScroller.computeScrollOffset()) { 2379 int oldX = mScrollX; 2380 int oldY = mScrollY; 2381 mScrollX = mScroller.getCurrX(); 2382 mScrollY = mScroller.getCurrY(); 2383 postInvalidate(); // So we draw again 2384 if (oldX != mScrollX || oldY != mScrollY) { 2385 // as onScrollChanged() is not called, sendOurVisibleRect() 2386 // needs to be call explicitly 2387 sendOurVisibleRect(); 2388 } 2389 } else { 2390 super.computeScroll(); 2391 } 2392 } 2393 2394 private static int computeDuration(int dx, int dy) { 2395 int distance = Math.max(Math.abs(dx), Math.abs(dy)); 2396 int duration = distance * 1000 / STD_SPEED; 2397 return Math.min(duration, MAX_DURATION); 2398 } 2399 2400 // helper to pin the scrollBy parameters (already in view coordinates) 2401 // returns true if the scroll was changed 2402 private boolean pinScrollBy(int dx, int dy, boolean animate, int animationDuration) { 2403 return pinScrollTo(mScrollX + dx, mScrollY + dy, animate, animationDuration); 2404 } 2405 2406 // helper to pin the scrollTo parameters (already in view coordinates) 2407 // returns true if the scroll was changed 2408 private boolean pinScrollTo(int x, int y, boolean animate, int animationDuration) { 2409 x = pinLocX(x); 2410 y = pinLocY(y); 2411 int dx = x - mScrollX; 2412 int dy = y - mScrollY; 2413 2414 if ((dx | dy) == 0) { 2415 return false; 2416 } 2417 2418 if (true && animate) { 2419 // Log.d(LOGTAG, "startScroll: " + dx + " " + dy); 2420 2421 mScroller.startScroll(mScrollX, mScrollY, dx, dy, 2422 animationDuration > 0 ? animationDuration : computeDuration(dx, dy)); 2423 invalidate(); 2424 } else { 2425 abortAnimation(); // just in case 2426 scrollTo(x, y); 2427 } 2428 return true; 2429 } 2430 2431 // Scale from content to view coordinates, and pin. 2432 // Also called by jni webview.cpp 2433 private boolean setContentScrollBy(int cx, int cy, boolean animate) { 2434 if (mDrawHistory) { 2435 // disallow WebView to change the scroll position as History Picture 2436 // is used in the view system. 2437 // TODO: as we switchOutDrawHistory when trackball or navigation 2438 // keys are hit, this should be safe. Right? 2439 return false; 2440 } 2441 cx = contentToViewDimension(cx); 2442 cy = contentToViewDimension(cy); 2443 if (mHeightCanMeasure) { 2444 // move our visible rect according to scroll request 2445 if (cy != 0) { 2446 Rect tempRect = new Rect(); 2447 calcOurVisibleRect(tempRect); 2448 tempRect.offset(cx, cy); 2449 requestRectangleOnScreen(tempRect); 2450 } 2451 // FIXME: We scroll horizontally no matter what because currently 2452 // ScrollView and ListView will not scroll horizontally. 2453 // FIXME: Why do we only scroll horizontally if there is no 2454 // vertical scroll? 2455// Log.d(LOGTAG, "setContentScrollBy cy=" + cy); 2456 return cy == 0 && cx != 0 && pinScrollBy(cx, 0, animate, 0); 2457 } else { 2458 return pinScrollBy(cx, cy, animate, 0); 2459 } 2460 } 2461 2462 // scale from content to view coordinates, and pin 2463 // return true if pin caused the final x/y different than the request cx/cy; 2464 // return false if the view scroll to the exact position as it is requested. 2465 private boolean setContentScrollTo(int cx, int cy) { 2466 if (mDrawHistory) { 2467 // disallow WebView to change the scroll position as History Picture 2468 // is used in the view system. 2469 // One known case where this is called is that WebCore tries to 2470 // restore the scroll position. As history Picture already uses the 2471 // saved scroll position, it is ok to skip this. 2472 return false; 2473 } 2474 int vx = contentToViewX(cx); 2475 int vy = contentToViewY(cy); 2476// Log.d(LOGTAG, "content scrollTo [" + cx + " " + cy + "] view=[" + 2477// vx + " " + vy + "]"); 2478 pinScrollTo(vx, vy, false, 0); 2479 if (mScrollX != vx || mScrollY != vy) { 2480 return true; 2481 } else { 2482 return false; 2483 } 2484 } 2485 2486 // scale from content to view coordinates, and pin 2487 private void spawnContentScrollTo(int cx, int cy) { 2488 if (mDrawHistory) { 2489 // disallow WebView to change the scroll position as History Picture 2490 // is used in the view system. 2491 return; 2492 } 2493 int vx = contentToViewX(cx); 2494 int vy = contentToViewY(cy); 2495 pinScrollTo(vx, vy, true, 0); 2496 } 2497 2498 /** 2499 * These are from webkit, and are in content coordinate system (unzoomed) 2500 */ 2501 private void contentSizeChanged(boolean updateLayout) { 2502 // suppress 0,0 since we usually see real dimensions soon after 2503 // this avoids drawing the prev content in a funny place. If we find a 2504 // way to consolidate these notifications, this check may become 2505 // obsolete 2506 if ((mContentWidth | mContentHeight) == 0) { 2507 return; 2508 } 2509 2510 if (mHeightCanMeasure) { 2511 if (getMeasuredHeight() != contentToViewDimension(mContentHeight) 2512 && updateLayout) { 2513 requestLayout(); 2514 } 2515 } else if (mWidthCanMeasure) { 2516 if (getMeasuredWidth() != contentToViewDimension(mContentWidth) 2517 && updateLayout) { 2518 requestLayout(); 2519 } 2520 } else { 2521 // If we don't request a layout, try to send our view size to the 2522 // native side to ensure that WebCore has the correct dimensions. 2523 sendViewSizeZoom(); 2524 } 2525 } 2526 2527 /** 2528 * Set the WebViewClient that will receive various notifications and 2529 * requests. This will replace the current handler. 2530 * @param client An implementation of WebViewClient. 2531 */ 2532 public void setWebViewClient(WebViewClient client) { 2533 mCallbackProxy.setWebViewClient(client); 2534 } 2535 2536 /** 2537 * Register the interface to be used when content can not be handled by 2538 * the rendering engine, and should be downloaded instead. This will replace 2539 * the current handler. 2540 * @param listener An implementation of DownloadListener. 2541 */ 2542 public void setDownloadListener(DownloadListener listener) { 2543 mCallbackProxy.setDownloadListener(listener); 2544 } 2545 2546 /** 2547 * Set the chrome handler. This is an implementation of WebChromeClient for 2548 * use in handling Javascript dialogs, favicons, titles, and the progress. 2549 * This will replace the current handler. 2550 * @param client An implementation of WebChromeClient. 2551 */ 2552 public void setWebChromeClient(WebChromeClient client) { 2553 mCallbackProxy.setWebChromeClient(client); 2554 } 2555 2556 /** 2557 * Gets the chrome handler. 2558 * @return the current WebChromeClient instance. 2559 * 2560 * @hide API council approval. 2561 */ 2562 public WebChromeClient getWebChromeClient() { 2563 return mCallbackProxy.getWebChromeClient(); 2564 } 2565 2566 /** 2567 * Set the Picture listener. This is an interface used to receive 2568 * notifications of a new Picture. 2569 * @param listener An implementation of WebView.PictureListener. 2570 */ 2571 public void setPictureListener(PictureListener listener) { 2572 mPictureListener = listener; 2573 } 2574 2575 /** 2576 * {@hide} 2577 */ 2578 /* FIXME: Debug only! Remove for SDK! */ 2579 public void externalRepresentation(Message callback) { 2580 mWebViewCore.sendMessage(EventHub.REQUEST_EXT_REPRESENTATION, callback); 2581 } 2582 2583 /** 2584 * {@hide} 2585 */ 2586 /* FIXME: Debug only! Remove for SDK! */ 2587 public void documentAsText(Message callback) { 2588 mWebViewCore.sendMessage(EventHub.REQUEST_DOC_AS_TEXT, callback); 2589 } 2590 2591 /** 2592 * Use this function to bind an object to Javascript so that the 2593 * methods can be accessed from Javascript. 2594 * <p><strong>IMPORTANT:</strong> 2595 * <ul> 2596 * <li> Using addJavascriptInterface() allows JavaScript to control your 2597 * application. This can be a very useful feature or a dangerous security 2598 * issue. When the HTML in the WebView is untrustworthy (for example, part 2599 * or all of the HTML is provided by some person or process), then an 2600 * attacker could inject HTML that will execute your code and possibly any 2601 * code of the attacker's choosing.<br> 2602 * Do not use addJavascriptInterface() unless all of the HTML in this 2603 * WebView was written by you.</li> 2604 * <li> The Java object that is bound runs in another thread and not in 2605 * the thread that it was constructed in.</li> 2606 * </ul></p> 2607 * @param obj The class instance to bind to Javascript 2608 * @param interfaceName The name to used to expose the class in Javascript 2609 */ 2610 public void addJavascriptInterface(Object obj, String interfaceName) { 2611 WebViewCore.JSInterfaceData arg = new WebViewCore.JSInterfaceData(); 2612 arg.mObject = obj; 2613 arg.mInterfaceName = interfaceName; 2614 mWebViewCore.sendMessage(EventHub.ADD_JS_INTERFACE, arg); 2615 } 2616 2617 /** 2618 * Return the WebSettings object used to control the settings for this 2619 * WebView. 2620 * @return A WebSettings object that can be used to control this WebView's 2621 * settings. 2622 */ 2623 public WebSettings getSettings() { 2624 return mWebViewCore.getSettings(); 2625 } 2626 2627 /** 2628 * Return the list of currently loaded plugins. 2629 * @return The list of currently loaded plugins. 2630 * 2631 * @deprecated This was used for Gears, which has been deprecated. 2632 */ 2633 @Deprecated 2634 public static synchronized PluginList getPluginList() { 2635 return null; 2636 } 2637 2638 /** 2639 * @deprecated This was used for Gears, which has been deprecated. 2640 */ 2641 @Deprecated 2642 public void refreshPlugins(boolean reloadOpenPages) { } 2643 2644 //------------------------------------------------------------------------- 2645 // Override View methods 2646 //------------------------------------------------------------------------- 2647 2648 @Override 2649 protected void finalize() throws Throwable { 2650 try { 2651 destroy(); 2652 } finally { 2653 super.finalize(); 2654 } 2655 } 2656 2657 @Override 2658 protected boolean drawChild(Canvas canvas, View child, long drawingTime) { 2659 if (child == mTitleBar) { 2660 // When drawing the title bar, move it horizontally to always show 2661 // at the top of the WebView. 2662 mTitleBar.offsetLeftAndRight(mScrollX - mTitleBar.getLeft()); 2663 } 2664 return super.drawChild(canvas, child, drawingTime); 2665 } 2666 2667 @Override 2668 protected void onDraw(Canvas canvas) { 2669 int saveCount = canvas.getSaveCount(); 2670 if (mTitleBar != null) { 2671 canvas.save(); 2672 canvas.translate(0, (int) mTitleBar.getHeight()); 2673 } 2674 // if mNativeClass is 0, the WebView has been destroyed. Do nothing. 2675 if (mNativeClass == 0) { 2676 return; 2677 } 2678 if (mWebViewCore.mEndScaleZoom) { 2679 mWebViewCore.mEndScaleZoom = false; 2680 if (mTouchMode >= FIRST_SCROLL_ZOOM 2681 && mTouchMode <= LAST_SCROLL_ZOOM) { 2682 setHorizontalScrollBarEnabled(true); 2683 setVerticalScrollBarEnabled(true); 2684 mTouchMode = TOUCH_DONE_MODE; 2685 } 2686 } 2687 canvas.save(); 2688 if (mTouchMode >= FIRST_SCROLL_ZOOM && mTouchMode <= LAST_SCROLL_ZOOM) { 2689 scrollZoomDraw(canvas); 2690 } else { 2691 // Update the buttons in the picture, so when we draw the picture 2692 // to the screen, they are in the correct state. 2693 // Tell the native side if user is a) touching the screen, 2694 // b) pressing the trackball down, or c) pressing the enter key 2695 // If the cursor is on a button, we need to draw it in the pressed 2696 // state. 2697 // If mNativeClass is 0, we should not reach here, so we do not 2698 // need to check it again. 2699 nativeRecordButtons(hasFocus() && hasWindowFocus(), 2700 mTouchMode == TOUCH_SHORTPRESS_START_MODE 2701 || mTrackballDown || mGotCenterDown, false); 2702 drawCoreAndCursorRing(canvas, mBackgroundColor, mDrawCursorRing); 2703 } 2704 canvas.restoreToCount(saveCount); 2705 2706 if (AUTO_REDRAW_HACK && mAutoRedraw) { 2707 invalidate(); 2708 } 2709 } 2710 2711 @Override 2712 public void setLayoutParams(ViewGroup.LayoutParams params) { 2713 if (params.height == LayoutParams.WRAP_CONTENT) { 2714 mWrapContent = true; 2715 } 2716 super.setLayoutParams(params); 2717 } 2718 2719 @Override 2720 public boolean performLongClick() { 2721 if (mNativeClass != 0 && nativeCursorIsTextInput()) { 2722 // Send the click so that the textfield is in focus 2723 // FIXME: When we start respecting changes to the native textfield's 2724 // selection, need to make sure that this does not change it. 2725 mWebViewCore.sendMessage(EventHub.CLICK, nativeCursorFramePointer(), 2726 nativeCursorNodePointer()); 2727 rebuildWebTextView(); 2728 } 2729 if (inEditingMode()) { 2730 return mWebTextView.performLongClick(); 2731 } else { 2732 return super.performLongClick(); 2733 } 2734 } 2735 2736 /** 2737 * Need to adjust the WebTextView after a change in zoom, since mActualScale 2738 * has changed. This is especially important for password fields, which are 2739 * drawn by the WebTextView, since it conveys more information than what 2740 * webkit draws. Thus we need to reposition it to show in the correct 2741 * place. 2742 */ 2743 private boolean mNeedToAdjustWebTextView; 2744 2745 private void drawCoreAndCursorRing(Canvas canvas, int color, 2746 boolean drawCursorRing) { 2747 if (mDrawHistory) { 2748 canvas.scale(mActualScale, mActualScale); 2749 canvas.drawPicture(mHistoryPicture); 2750 return; 2751 } 2752 2753 boolean animateZoom = mZoomScale != 0; 2754 boolean animateScroll = !mScroller.isFinished() 2755 || mVelocityTracker != null; 2756 if (animateZoom) { 2757 float zoomScale; 2758 int interval = (int) (SystemClock.uptimeMillis() - mZoomStart); 2759 if (interval < ZOOM_ANIMATION_LENGTH) { 2760 float ratio = (float) interval / ZOOM_ANIMATION_LENGTH; 2761 zoomScale = 1.0f / (mInvInitialZoomScale 2762 + (mInvFinalZoomScale - mInvInitialZoomScale) * ratio); 2763 invalidate(); 2764 } else { 2765 zoomScale = mZoomScale; 2766 // set mZoomScale to be 0 as we have done animation 2767 mZoomScale = 0; 2768 if (mNeedToAdjustWebTextView) { 2769 mNeedToAdjustWebTextView = false; 2770 mWebTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, 2771 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(TypedValue.COMPLEX_UNIT_PX, 3337 contentToViewDimension(nativeFocusCandidateTextSize())); 3338 Rect visibleRect = new Rect(); 3339 calcOurContentVisibleRect(visibleRect); 3340 // Note that sendOurVisibleRect calls viewToContent, so the coordinates 3341 // should be in content coordinates. 3342 Rect bounds = nativeFocusCandidateNodeBounds(); 3343 if (!Rect.intersects(bounds, visibleRect)) { 3344 mWebTextView.bringIntoView(); 3345 } 3346 String text = nativeFocusCandidateText(); 3347 int nodePointer = nativeFocusCandidatePointer(); 3348 if (alreadyThere && mWebTextView.isSameTextField(nodePointer)) { 3349 // It is possible that we have the same textfield, but it has moved, 3350 // i.e. In the case of opening/closing the screen. 3351 // In that case, we need to set the dimensions, but not the other 3352 // aspects. 3353 // We also need to restore the selection, which gets wrecked by 3354 // calling setTextEntryRect. 3355 Spannable spannable = (Spannable) mWebTextView.getText(); 3356 int start = Selection.getSelectionStart(spannable); 3357 int end = Selection.getSelectionEnd(spannable); 3358 // If the text has been changed by webkit, update it. However, if 3359 // there has been more UI text input, ignore it. We will receive 3360 // another update when that text is recognized. 3361 if (text != null && !text.equals(spannable.toString()) 3362 && nativeTextGeneration() == mTextGeneration) { 3363 mWebTextView.setTextAndKeepSelection(text); 3364 } else { 3365 Selection.setSelection(spannable, start, end); 3366 } 3367 } else { 3368 Rect vBox = contentToView(bounds); 3369 mWebTextView.setRect(vBox.left, vBox.top, vBox.width(), 3370 vBox.height()); 3371 mWebTextView.setGravity(nativeFocusCandidateIsRtlText() ? 3372 Gravity.RIGHT : Gravity.NO_GRAVITY); 3373 // this needs to be called before update adapter thread starts to 3374 // ensure the mWebTextView has the same node pointer 3375 mWebTextView.setNodePointer(nodePointer); 3376 int maxLength = -1; 3377 boolean isTextField = nativeFocusCandidateIsTextField(); 3378 if (isTextField) { 3379 maxLength = nativeFocusCandidateMaxLength(); 3380 String name = nativeFocusCandidateName(); 3381 if (mWebViewCore.getSettings().getSaveFormData() 3382 && name != null) { 3383 Message update = mPrivateHandler.obtainMessage( 3384 REQUEST_FORM_DATA, nodePointer); 3385 RequestFormData updater = new RequestFormData(name, 3386 getUrl(), update); 3387 Thread t = new Thread(updater); 3388 t.start(); 3389 } 3390 } 3391 mWebTextView.setMaxLength(maxLength); 3392 AutoCompleteAdapter adapter = null; 3393 mWebTextView.setAdapterCustom(adapter); 3394 mWebTextView.setSingleLine(isTextField); 3395 mWebTextView.setInPassword(nativeFocusCandidateIsPassword()); 3396 if (null == text) { 3397 mWebTextView.setText("", 0, 0); 3398 if (DebugFlags.WEB_VIEW) { 3399 Log.v(LOGTAG, "rebuildWebTextView null == text"); 3400 } 3401 } else { 3402 // Change to true to enable the old style behavior, where 3403 // entering a textfield/textarea always set the selection to the 3404 // whole field. This was desirable for the case where the user 3405 // intends to scroll past the field using the trackball. 3406 // However, it causes a problem when replying to emails - the 3407 // user expects the cursor to be at the beginning of the 3408 // textarea. Testing out a new behavior, where textfields set 3409 // selection at the end, and textareas at the beginning. 3410 if (false) { 3411 mWebTextView.setText(text, 0, text.length()); 3412 } else if (isTextField) { 3413 int length = text.length(); 3414 mWebTextView.setText(text, length, length); 3415 if (DebugFlags.WEB_VIEW) { 3416 Log.v(LOGTAG, "rebuildWebTextView length=" + length); 3417 } 3418 } else { 3419 mWebTextView.setText(text, 0, 0); 3420 if (DebugFlags.WEB_VIEW) { 3421 Log.v(LOGTAG, "rebuildWebTextView !isTextField"); 3422 } 3423 } 3424 } 3425 mWebTextView.requestFocus(); 3426 } 3427 } 3428 3429 /* 3430 * This class requests an Adapter for the WebTextView which shows past 3431 * entries stored in the database. It is a Runnable so that it can be done 3432 * in its own thread, without slowing down the UI. 3433 */ 3434 private class RequestFormData implements Runnable { 3435 private String mName; 3436 private String mUrl; 3437 private Message mUpdateMessage; 3438 3439 public RequestFormData(String name, String url, Message msg) { 3440 mName = name; 3441 mUrl = url; 3442 mUpdateMessage = msg; 3443 } 3444 3445 public void run() { 3446 ArrayList<String> pastEntries = mDatabase.getFormData(mUrl, mName); 3447 if (pastEntries.size() > 0) { 3448 AutoCompleteAdapter adapter = new 3449 AutoCompleteAdapter(mContext, pastEntries); 3450 mUpdateMessage.obj = adapter; 3451 mUpdateMessage.sendToTarget(); 3452 } 3453 } 3454 } 3455 3456 // This is used to determine long press with the center key. Does not 3457 // affect long press with the trackball/touch. 3458 private boolean mGotCenterDown = false; 3459 3460 @Override 3461 public boolean onKeyDown(int keyCode, KeyEvent event) { 3462 if (DebugFlags.WEB_VIEW) { 3463 Log.v(LOGTAG, "keyDown at " + System.currentTimeMillis() 3464 + ", " + event + ", unicode=" + event.getUnicodeChar()); 3465 } 3466 3467 if (mNativeClass == 0) { 3468 return false; 3469 } 3470 3471 // do this hack up front, so it always works, regardless of touch-mode 3472 if (AUTO_REDRAW_HACK && (keyCode == KeyEvent.KEYCODE_CALL)) { 3473 mAutoRedraw = !mAutoRedraw; 3474 if (mAutoRedraw) { 3475 invalidate(); 3476 } 3477 return true; 3478 } 3479 3480 // Bubble up the key event if 3481 // 1. it is a system key; or 3482 // 2. the host application wants to handle it; or 3483 // 3. webview is in scroll-zoom state; 3484 if (event.isSystem() 3485 || mCallbackProxy.uiOverrideKeyEvent(event) 3486 || (mTouchMode >= FIRST_SCROLL_ZOOM && mTouchMode <= LAST_SCROLL_ZOOM)) { 3487 return false; 3488 } 3489 3490 if (mShiftIsPressed == false && nativeCursorWantsKeyEvents() == false 3491 && (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT 3492 || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT)) { 3493 mExtendSelection = false; 3494 mShiftIsPressed = true; 3495 if (nativeHasCursorNode()) { 3496 Rect rect = nativeCursorNodeBounds(); 3497 mSelectX = contentToViewX(rect.left); 3498 mSelectY = contentToViewY(rect.top); 3499 } else { 3500 mSelectX = mScrollX + (int) mLastTouchX; 3501 mSelectY = mScrollY + (int) mLastTouchY; 3502 } 3503 nativeHideCursor(); 3504 } 3505 3506 if (keyCode >= KeyEvent.KEYCODE_DPAD_UP 3507 && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) { 3508 // always handle the navigation keys in the UI thread 3509 switchOutDrawHistory(); 3510 if (navHandledKey(keyCode, 1, false, event.getEventTime(), false)) { 3511 playSoundEffect(keyCodeToSoundsEffect(keyCode)); 3512 return true; 3513 } 3514 // Bubble up the key event as WebView doesn't handle it 3515 return false; 3516 } 3517 3518 if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { 3519 switchOutDrawHistory(); 3520 if (event.getRepeatCount() == 0) { 3521 mGotCenterDown = true; 3522 mPrivateHandler.sendMessageDelayed(mPrivateHandler 3523 .obtainMessage(LONG_PRESS_CENTER), LONG_PRESS_TIMEOUT); 3524 // Already checked mNativeClass, so we do not need to check it 3525 // again. 3526 nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true); 3527 return true; 3528 } 3529 // Bubble up the key event as WebView doesn't handle it 3530 return false; 3531 } 3532 3533 if (keyCode != KeyEvent.KEYCODE_SHIFT_LEFT 3534 && keyCode != KeyEvent.KEYCODE_SHIFT_RIGHT) { 3535 // turn off copy select if a shift-key combo is pressed 3536 mExtendSelection = mShiftIsPressed = false; 3537 if (mTouchMode == TOUCH_SELECT_MODE) { 3538 mTouchMode = TOUCH_INIT_MODE; 3539 } 3540 } 3541 3542 if (getSettings().getNavDump()) { 3543 switch (keyCode) { 3544 case KeyEvent.KEYCODE_4: 3545 // "/data/data/com.android.browser/displayTree.txt" 3546 nativeDumpDisplayTree(getUrl()); 3547 break; 3548 case KeyEvent.KEYCODE_5: 3549 case KeyEvent.KEYCODE_6: 3550 // 5: dump the dom tree to the file 3551 // "/data/data/com.android.browser/domTree.txt" 3552 // 6: dump the dom tree to the adb log 3553 mWebViewCore.sendMessage(EventHub.DUMP_DOMTREE, 3554 (keyCode == KeyEvent.KEYCODE_5) ? 1 : 0, 0); 3555 break; 3556 case KeyEvent.KEYCODE_7: 3557 case KeyEvent.KEYCODE_8: 3558 // 7: dump the render tree to the file 3559 // "/data/data/com.android.browser/renderTree.txt" 3560 // 8: dump the render tree to the adb log 3561 mWebViewCore.sendMessage(EventHub.DUMP_RENDERTREE, 3562 (keyCode == KeyEvent.KEYCODE_7) ? 1 : 0, 0); 3563 break; 3564 case KeyEvent.KEYCODE_9: 3565 nativeInstrumentReport(); 3566 return true; 3567 } 3568 } 3569 3570 if (nativeCursorIsPlugin()) { 3571 nativeUpdatePluginReceivesEvents(); 3572 invalidate(); 3573 } else if (nativeCursorIsTextInput()) { 3574 // This message will put the node in focus, for the DOM's notion 3575 // of focus, and make the focuscontroller active 3576 mWebViewCore.sendMessage(EventHub.CLICK, nativeCursorFramePointer(), 3577 nativeCursorNodePointer()); 3578 // This will bring up the WebTextView and put it in focus, for 3579 // our view system's notion of focus 3580 rebuildWebTextView(); 3581 // Now we need to pass the event to it 3582 return mWebTextView.onKeyDown(keyCode, event); 3583 } else if (nativeHasFocusNode()) { 3584 // In this case, the cursor is not on a text input, but the focus 3585 // might be. Check it, and if so, hand over to the WebTextView. 3586 rebuildWebTextView(); 3587 if (inEditingMode()) { 3588 return mWebTextView.onKeyDown(keyCode, event); 3589 } 3590 } 3591 3592 // TODO: should we pass all the keys to DOM or check the meta tag 3593 if (nativeCursorWantsKeyEvents() || true) { 3594 // pass the key to DOM 3595 mWebViewCore.sendMessage(EventHub.KEY_DOWN, event); 3596 // return true as DOM handles the key 3597 return true; 3598 } 3599 3600 // Bubble up the key event as WebView doesn't handle it 3601 return false; 3602 } 3603 3604 @Override 3605 public boolean onKeyUp(int keyCode, KeyEvent event) { 3606 if (DebugFlags.WEB_VIEW) { 3607 Log.v(LOGTAG, "keyUp at " + System.currentTimeMillis() 3608 + ", " + event + ", unicode=" + event.getUnicodeChar()); 3609 } 3610 3611 if (mNativeClass == 0) { 3612 return false; 3613 } 3614 3615 // special CALL handling when cursor node's href is "tel:XXX" 3616 if (keyCode == KeyEvent.KEYCODE_CALL && nativeHasCursorNode()) { 3617 String text = nativeCursorText(); 3618 if (!nativeCursorIsTextInput() && text != null 3619 && text.startsWith(SCHEME_TEL)) { 3620 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(text)); 3621 getContext().startActivity(intent); 3622 return true; 3623 } 3624 } 3625 3626 // Bubble up the key event if 3627 // 1. it is a system key; or 3628 // 2. the host application wants to handle it; 3629 if (event.isSystem() || mCallbackProxy.uiOverrideKeyEvent(event)) { 3630 return false; 3631 } 3632 3633 // special handling in scroll_zoom state 3634 if (mTouchMode >= FIRST_SCROLL_ZOOM && mTouchMode <= LAST_SCROLL_ZOOM) { 3635 if (KeyEvent.KEYCODE_DPAD_CENTER == keyCode 3636 && mTouchMode != SCROLL_ZOOM_ANIMATION_IN) { 3637 setZoomScrollIn(); 3638 mTouchMode = SCROLL_ZOOM_ANIMATION_IN; 3639 invalidate(); 3640 return true; 3641 } 3642 return false; 3643 } 3644 3645 if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT 3646 || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT) { 3647 if (commitCopy()) { 3648 return true; 3649 } 3650 } 3651 3652 if (keyCode >= KeyEvent.KEYCODE_DPAD_UP 3653 && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) { 3654 // always handle the navigation keys in the UI thread 3655 // Bubble up the key event as WebView doesn't handle it 3656 return false; 3657 } 3658 3659 if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { 3660 // remove the long press message first 3661 mPrivateHandler.removeMessages(LONG_PRESS_CENTER); 3662 mGotCenterDown = false; 3663 3664 if (mShiftIsPressed) { 3665 return false; 3666 } 3667 if (getSettings().supportZoom() 3668 && mTouchMode == TOUCH_DOUBLECLICK_MODE) { 3669 zoomScrollOut(); 3670 } else { 3671 mPrivateHandler.sendMessageDelayed(mPrivateHandler 3672 .obtainMessage(SWITCH_TO_CLICK), TAP_TIMEOUT); 3673 if (DebugFlags.WEB_VIEW) { 3674 Log.v(LOGTAG, "TOUCH_DOUBLECLICK_MODE"); 3675 } 3676 mTouchMode = TOUCH_DOUBLECLICK_MODE; 3677 } 3678 return true; 3679 } 3680 3681 // TODO: should we pass all the keys to DOM or check the meta tag 3682 if (nativeCursorWantsKeyEvents() || true) { 3683 // pass the key to DOM 3684 mWebViewCore.sendMessage(EventHub.KEY_UP, event); 3685 // return true as DOM handles the key 3686 return true; 3687 } 3688 3689 // Bubble up the key event as WebView doesn't handle it 3690 return false; 3691 } 3692 3693 /** 3694 * @hide 3695 */ 3696 public void emulateShiftHeld() { 3697 mExtendSelection = false; 3698 mShiftIsPressed = true; 3699 nativeHideCursor(); 3700 } 3701 3702 private boolean commitCopy() { 3703 boolean copiedSomething = false; 3704 if (mExtendSelection) { 3705 // copy region so core operates on copy without touching orig. 3706 Region selection = new Region(nativeGetSelection()); 3707 if (selection.isEmpty() == false) { 3708 Toast.makeText(mContext 3709 , com.android.internal.R.string.text_copied 3710 , Toast.LENGTH_SHORT).show(); 3711 mWebViewCore.sendMessage(EventHub.GET_SELECTION, selection); 3712 copiedSomething = true; 3713 } 3714 mExtendSelection = false; 3715 } 3716 mShiftIsPressed = false; 3717 if (mTouchMode == TOUCH_SELECT_MODE) { 3718 mTouchMode = TOUCH_INIT_MODE; 3719 } 3720 return copiedSomething; 3721 } 3722 3723 // Set this as a hierarchy change listener so we can know when this view 3724 // is removed and still have access to our parent. 3725 @Override 3726 protected void onAttachedToWindow() { 3727 super.onAttachedToWindow(); 3728 ViewParent parent = getParent(); 3729 if (parent instanceof ViewGroup) { 3730 ViewGroup p = (ViewGroup) parent; 3731 p.setOnHierarchyChangeListener(this); 3732 } 3733 } 3734 3735 @Override 3736 protected void onDetachedFromWindow() { 3737 super.onDetachedFromWindow(); 3738 ViewParent parent = getParent(); 3739 if (parent instanceof ViewGroup) { 3740 ViewGroup p = (ViewGroup) parent; 3741 p.setOnHierarchyChangeListener(null); 3742 } 3743 3744 // Clean up the zoom controller 3745 mZoomButtonsController.setVisible(false); 3746 } 3747 3748 // Implementation for OnHierarchyChangeListener 3749 public void onChildViewAdded(View parent, View child) {} 3750 3751 public void onChildViewRemoved(View p, View child) { 3752 if (child == this) { 3753 clearTextEntry(); 3754 } 3755 } 3756 3757 /** 3758 * @deprecated WebView should not have implemented 3759 * ViewTreeObserver.OnGlobalFocusChangeListener. This method 3760 * does nothing now. 3761 */ 3762 @Deprecated 3763 public void onGlobalFocusChanged(View oldFocus, View newFocus) { 3764 } 3765 3766 // To avoid drawing the cursor ring, and remove the TextView when our window 3767 // loses focus. 3768 @Override 3769 public void onWindowFocusChanged(boolean hasWindowFocus) { 3770 if (hasWindowFocus) { 3771 if (hasFocus()) { 3772 // If our window regained focus, and we have focus, then begin 3773 // drawing the cursor ring 3774 mDrawCursorRing = true; 3775 if (mNativeClass != 0) { 3776 nativeRecordButtons(true, false, true); 3777 if (inEditingMode()) { 3778 mWebViewCore.sendMessage(EventHub.SET_ACTIVE, 1, 0); 3779 } 3780 } 3781 } else { 3782 // If our window gained focus, but we do not have it, do not 3783 // draw the cursor ring. 3784 mDrawCursorRing = false; 3785 // We do not call nativeRecordButtons here because we assume 3786 // that when we lost focus, or window focus, it got called with 3787 // false for the first parameter 3788 } 3789 } else { 3790 if (getSettings().getBuiltInZoomControls() && !mZoomButtonsController.isVisible()) { 3791 /* 3792 * The zoom controls come in their own window, so our window 3793 * loses focus. Our policy is to not draw the cursor ring if 3794 * our window is not focused, but this is an exception since 3795 * the user can still navigate the web page with the zoom 3796 * controls showing. 3797 */ 3798 // If our window has lost focus, stop drawing the cursor ring 3799 mDrawCursorRing = false; 3800 } 3801 mGotKeyDown = false; 3802 mShiftIsPressed = false; 3803 if (mNativeClass != 0) { 3804 nativeRecordButtons(false, false, true); 3805 } 3806 setFocusControllerInactive(); 3807 } 3808 invalidate(); 3809 super.onWindowFocusChanged(hasWindowFocus); 3810 } 3811 3812 /* 3813 * Pass a message to WebCore Thread, telling the WebCore::Page's 3814 * FocusController to be "inactive" so that it will 3815 * not draw the blinking cursor. It gets set to "active" to draw the cursor 3816 * in WebViewCore.cpp, when the WebCore thread receives key events/clicks. 3817 */ 3818 /* package */ void setFocusControllerInactive() { 3819 // Do not need to also check whether mWebViewCore is null, because 3820 // mNativeClass is only set if mWebViewCore is non null 3821 if (mNativeClass == 0) return; 3822 mWebViewCore.sendMessage(EventHub.SET_ACTIVE, 0, 0); 3823 } 3824 3825 @Override 3826 protected void onFocusChanged(boolean focused, int direction, 3827 Rect previouslyFocusedRect) { 3828 if (DebugFlags.WEB_VIEW) { 3829 Log.v(LOGTAG, "MT focusChanged " + focused + ", " + direction); 3830 } 3831 if (focused) { 3832 // When we regain focus, if we have window focus, resume drawing 3833 // the cursor ring 3834 if (hasWindowFocus()) { 3835 mDrawCursorRing = true; 3836 if (mNativeClass != 0) { 3837 nativeRecordButtons(true, false, true); 3838 } 3839 //} else { 3840 // The WebView has gained focus while we do not have 3841 // windowfocus. When our window lost focus, we should have 3842 // called nativeRecordButtons(false...) 3843 } 3844 } else { 3845 // When we lost focus, unless focus went to the TextView (which is 3846 // true if we are in editing mode), stop drawing the cursor ring. 3847 if (!inEditingMode()) { 3848 mDrawCursorRing = false; 3849 if (mNativeClass != 0) { 3850 nativeRecordButtons(false, false, true); 3851 } 3852 setFocusControllerInactive(); 3853 } 3854 mGotKeyDown = false; 3855 } 3856 3857 super.onFocusChanged(focused, direction, previouslyFocusedRect); 3858 } 3859 3860 @Override 3861 protected void onSizeChanged(int w, int h, int ow, int oh) { 3862 super.onSizeChanged(w, h, ow, oh); 3863 // Center zooming to the center of the screen. 3864 if (mZoomScale == 0) { // unless we're already zooming 3865 mZoomCenterX = getViewWidth() * .5f; 3866 mZoomCenterY = getViewHeight() * .5f; 3867 } 3868 3869 // update mMinZoomScale if the minimum zoom scale is not fixed 3870 if (!mMinZoomScaleFixed) { 3871 mMinZoomScale = (float) getViewWidth() 3872 / (mDrawHistory ? mHistoryPicture.getWidth() 3873 : mZoomOverviewWidth); 3874 } 3875 3876 // we always force, in case our height changed, in which case we still 3877 // want to send the notification over to webkit 3878 setNewZoomScale(mActualScale, true); 3879 } 3880 3881 @Override 3882 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 3883 super.onScrollChanged(l, t, oldl, oldt); 3884 3885 sendOurVisibleRect(); 3886 } 3887 3888 3889 @Override 3890 public boolean dispatchKeyEvent(KeyEvent event) { 3891 boolean dispatch = true; 3892 3893 if (!inEditingMode()) { 3894 if (event.getAction() == KeyEvent.ACTION_DOWN) { 3895 mGotKeyDown = true; 3896 } else { 3897 if (!mGotKeyDown) { 3898 /* 3899 * We got a key up for which we were not the recipient of 3900 * the original key down. Don't give it to the view. 3901 */ 3902 dispatch = false; 3903 } 3904 mGotKeyDown = false; 3905 } 3906 } 3907 3908 if (dispatch) { 3909 return super.dispatchKeyEvent(event); 3910 } else { 3911 // We didn't dispatch, so let something else handle the key 3912 return false; 3913 } 3914 } 3915 3916 // Here are the snap align logic: 3917 // 1. If it starts nearly horizontally or vertically, snap align; 3918 // 2. If there is a dramitic direction change, let it go; 3919 // 3. If there is a same direction back and forth, lock it. 3920 3921 // adjustable parameters 3922 private int mMinLockSnapReverseDistance; 3923 private static final float MAX_SLOPE_FOR_DIAG = 1.5f; 3924 private static final int MIN_BREAK_SNAP_CROSS_DISTANCE = 80; 3925 3926 @Override 3927 public boolean onTouchEvent(MotionEvent ev) { 3928 if (mNativeClass == 0 || !isClickable() || !isLongClickable()) { 3929 return false; 3930 } 3931 3932 if (DebugFlags.WEB_VIEW) { 3933 Log.v(LOGTAG, ev + " at " + ev.getEventTime() + " mTouchMode=" 3934 + mTouchMode); 3935 } 3936 3937 int action = ev.getAction(); 3938 float x = ev.getX(); 3939 float y = ev.getY(); 3940 long eventTime = ev.getEventTime(); 3941 3942 // Due to the touch screen edge effect, a touch closer to the edge 3943 // always snapped to the edge. As getViewWidth() can be different from 3944 // getWidth() due to the scrollbar, adjusting the point to match 3945 // getViewWidth(). Same applied to the height. 3946 if (x > getViewWidth() - 1) { 3947 x = getViewWidth() - 1; 3948 } 3949 if (y > getViewHeight() - 1) { 3950 y = getViewHeight() - 1; 3951 } 3952 3953 // pass the touch events from UI thread to WebCore thread 3954 if (mForwardTouchEvents && mTouchMode != SCROLL_ZOOM_OUT 3955 && mTouchMode != SCROLL_ZOOM_ANIMATION_IN 3956 && mTouchMode != SCROLL_ZOOM_ANIMATION_OUT 3957 && (action != MotionEvent.ACTION_MOVE || 3958 eventTime - mLastSentTouchTime > TOUCH_SENT_INTERVAL)) { 3959 WebViewCore.TouchEventData ted = new WebViewCore.TouchEventData(); 3960 ted.mAction = action; 3961 ted.mX = viewToContentX((int) x + mScrollX); 3962 ted.mY = viewToContentY((int) y + mScrollY); 3963 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 3964 mLastSentTouchTime = eventTime; 3965 } 3966 3967 int deltaX = (int) (mLastTouchX - x); 3968 int deltaY = (int) (mLastTouchY - y); 3969 3970 switch (action) { 3971 case MotionEvent.ACTION_DOWN: { 3972 if (mTouchMode == SCROLL_ZOOM_ANIMATION_IN 3973 || mTouchMode == SCROLL_ZOOM_ANIMATION_OUT) { 3974 // no interaction while animation is in progress 3975 break; 3976 } else if (mTouchMode == SCROLL_ZOOM_OUT) { 3977 mLastScrollX = mZoomScrollX; 3978 mLastScrollY = mZoomScrollY; 3979 // If two taps are close, ignore the first tap 3980 } else if (!mScroller.isFinished()) { 3981 // stop the current scroll animation, but if this is 3982 // the start of a fling, allow it to add to the current 3983 // fling's velocity 3984 mScroller.abortAnimation(); 3985 mTouchMode = TOUCH_DRAG_START_MODE; 3986 mPrivateHandler.removeMessages(RESUME_WEBCORE_UPDATE); 3987 } else if (mShiftIsPressed) { 3988 mSelectX = mScrollX + (int) x; 3989 mSelectY = mScrollY + (int) y; 3990 mTouchMode = TOUCH_SELECT_MODE; 3991 if (DebugFlags.WEB_VIEW) { 3992 Log.v(LOGTAG, "select=" + mSelectX + "," + mSelectY); 3993 } 3994 nativeMoveSelection(viewToContentX(mSelectX), 3995 viewToContentY(mSelectY), false); 3996 mTouchSelection = mExtendSelection = true; 3997 } else if (mPrivateHandler.hasMessages(RELEASE_SINGLE_TAP)) { 3998 mPrivateHandler.removeMessages(RELEASE_SINGLE_TAP); 3999 if (deltaX * deltaX + deltaY * deltaY < mDoubleTapSlopSquare) { 4000 mTouchMode = TOUCH_DOUBLE_TAP_MODE; 4001 } else { 4002 // commit the short press action for the previous tap 4003 doShortPress(); 4004 // continue, mTouchMode should be still TOUCH_INIT_MODE 4005 } 4006 } else { 4007 mTouchMode = TOUCH_INIT_MODE; 4008 mPreventDrag = mForwardTouchEvents; 4009 mWebViewCore.sendMessage( 4010 EventHub.UPDATE_FRAME_CACHE_IF_LOADING); 4011 if (mLogEvent && eventTime - mLastTouchUpTime < 1000) { 4012 EventLog.writeEvent(EVENT_LOG_DOUBLE_TAP_DURATION, 4013 (eventTime - mLastTouchUpTime), eventTime); 4014 } 4015 } 4016 // Trigger the link 4017 if (mTouchMode == TOUCH_INIT_MODE 4018 || mTouchMode == TOUCH_DOUBLE_TAP_MODE) { 4019 mPrivateHandler.sendMessageDelayed(mPrivateHandler 4020 .obtainMessage(SWITCH_TO_SHORTPRESS), TAP_TIMEOUT); 4021 } 4022 // Remember where the motion event started 4023 mLastTouchX = x; 4024 mLastTouchY = y; 4025 mLastTouchTime = eventTime; 4026 mVelocityTracker = VelocityTracker.obtain(); 4027 mSnapScrollMode = SNAP_NONE; 4028 break; 4029 } 4030 case MotionEvent.ACTION_MOVE: { 4031 if (mTouchMode == TOUCH_DONE_MODE 4032 || mTouchMode == SCROLL_ZOOM_ANIMATION_IN 4033 || mTouchMode == SCROLL_ZOOM_ANIMATION_OUT) { 4034 // no dragging during scroll zoom animation 4035 break; 4036 } 4037 if (mTouchMode == SCROLL_ZOOM_OUT) { 4038 // while fully zoomed out, move the virtual window 4039 moveZoomScrollWindow(x, y); 4040 break; 4041 } 4042 mVelocityTracker.addMovement(ev); 4043 4044 if (mTouchMode != TOUCH_DRAG_MODE) { 4045 if (mTouchMode == TOUCH_SELECT_MODE) { 4046 mSelectX = mScrollX + (int) x; 4047 mSelectY = mScrollY + (int) y; 4048 if (DebugFlags.WEB_VIEW) { 4049 Log.v(LOGTAG, "xtend=" + mSelectX + "," + mSelectY); 4050 } 4051 nativeMoveSelection(viewToContentX(mSelectX), 4052 viewToContentY(mSelectY), true); 4053 invalidate(); 4054 break; 4055 } 4056 if (mPreventDrag || (deltaX * deltaX + deltaY * deltaY) 4057 < mTouchSlopSquare) { 4058 break; 4059 } 4060 4061 if (mTouchMode == TOUCH_SHORTPRESS_MODE 4062 || mTouchMode == TOUCH_SHORTPRESS_START_MODE) { 4063 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 4064 } else if (mTouchMode == TOUCH_INIT_MODE 4065 || mTouchMode == TOUCH_DOUBLE_TAP_MODE) { 4066 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 4067 } 4068 4069 // if it starts nearly horizontal or vertical, enforce it 4070 int ax = Math.abs(deltaX); 4071 int ay = Math.abs(deltaY); 4072 if (ax > MAX_SLOPE_FOR_DIAG * ay) { 4073 mSnapScrollMode = SNAP_X; 4074 mSnapPositive = deltaX > 0; 4075 } else if (ay > MAX_SLOPE_FOR_DIAG * ax) { 4076 mSnapScrollMode = SNAP_Y; 4077 mSnapPositive = deltaY > 0; 4078 } 4079 4080 mTouchMode = TOUCH_DRAG_MODE; 4081 WebViewCore.pauseUpdate(mWebViewCore); 4082 if (!mDragFromTextInput) { 4083 nativeHideCursor(); 4084 } 4085 WebSettings settings = getSettings(); 4086 if (settings.supportZoom() 4087 && settings.getBuiltInZoomControls() 4088 && !mZoomButtonsController.isVisible() 4089 && (canZoomScrollOut() || 4090 mMinZoomScale < mMaxZoomScale)) { 4091 mZoomButtonsController.setVisible(true); 4092 } 4093 } 4094 4095 // do pan 4096 int newScrollX = pinLocX(mScrollX + deltaX); 4097 deltaX = newScrollX - mScrollX; 4098 int newScrollY = pinLocY(mScrollY + deltaY); 4099 deltaY = newScrollY - mScrollY; 4100 boolean done = false; 4101 if (deltaX == 0 && deltaY == 0) { 4102 done = true; 4103 } else { 4104 if (mSnapScrollMode == SNAP_X || mSnapScrollMode == SNAP_Y) { 4105 int ax = Math.abs(deltaX); 4106 int ay = Math.abs(deltaY); 4107 if (mSnapScrollMode == SNAP_X) { 4108 // radical change means getting out of snap mode 4109 if (ay > MAX_SLOPE_FOR_DIAG * ax 4110 && ay > MIN_BREAK_SNAP_CROSS_DISTANCE) { 4111 mSnapScrollMode = SNAP_NONE; 4112 } 4113 // reverse direction means lock in the snap mode 4114 if ((ax > MAX_SLOPE_FOR_DIAG * ay) && 4115 ((mSnapPositive && 4116 deltaX < -mMinLockSnapReverseDistance) 4117 || (!mSnapPositive && 4118 deltaX > mMinLockSnapReverseDistance))) { 4119 mSnapScrollMode = SNAP_X_LOCK; 4120 } 4121 } else { 4122 // radical change means getting out of snap mode 4123 if ((ax > MAX_SLOPE_FOR_DIAG * ay) 4124 && ax > MIN_BREAK_SNAP_CROSS_DISTANCE) { 4125 mSnapScrollMode = SNAP_NONE; 4126 } 4127 // reverse direction means lock in the snap mode 4128 if ((ay > MAX_SLOPE_FOR_DIAG * ax) && 4129 ((mSnapPositive && 4130 deltaY < -mMinLockSnapReverseDistance) 4131 || (!mSnapPositive && 4132 deltaY > mMinLockSnapReverseDistance))) { 4133 mSnapScrollMode = SNAP_Y_LOCK; 4134 } 4135 } 4136 } 4137 4138 if (mSnapScrollMode == SNAP_X 4139 || mSnapScrollMode == SNAP_X_LOCK) { 4140 scrollBy(deltaX, 0); 4141 mLastTouchX = x; 4142 } else if (mSnapScrollMode == SNAP_Y 4143 || mSnapScrollMode == SNAP_Y_LOCK) { 4144 scrollBy(0, deltaY); 4145 mLastTouchY = y; 4146 } else { 4147 scrollBy(deltaX, deltaY); 4148 mLastTouchX = x; 4149 mLastTouchY = y; 4150 } 4151 mLastTouchTime = eventTime; 4152 mUserScroll = true; 4153 } 4154 4155 if (!getSettings().getBuiltInZoomControls()) { 4156 boolean showPlusMinus = mMinZoomScale < mMaxZoomScale; 4157 boolean showMagnify = canZoomScrollOut(); 4158 if (mZoomControls != null && (showPlusMinus || showMagnify)) { 4159 if (mZoomControls.getVisibility() == View.VISIBLE) { 4160 mPrivateHandler.removeCallbacks(mZoomControlRunnable); 4161 } else { 4162 mZoomControls.show(showPlusMinus, showMagnify); 4163 } 4164 mPrivateHandler.postDelayed(mZoomControlRunnable, 4165 ZOOM_CONTROLS_TIMEOUT); 4166 } 4167 } 4168 4169 if (done) { 4170 // return false to indicate that we can't pan out of the 4171 // view space 4172 return false; 4173 } 4174 break; 4175 } 4176 case MotionEvent.ACTION_UP: { 4177 mLastTouchUpTime = eventTime; 4178 switch (mTouchMode) { 4179 case TOUCH_DOUBLE_TAP_MODE: // double tap 4180 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 4181 mTouchMode = TOUCH_DONE_MODE; 4182 doDoubleTap(); 4183 break; 4184 case TOUCH_INIT_MODE: // tap 4185 if (ENABLE_DOUBLETAP_ZOOM) { 4186 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 4187 if (!mPreventDrag) { 4188 mPrivateHandler.sendMessageDelayed( 4189 mPrivateHandler.obtainMessage( 4190 RELEASE_SINGLE_TAP), 4191 ViewConfiguration.getDoubleTapTimeout()); 4192 } 4193 break; 4194 } 4195 // fall through 4196 case TOUCH_SHORTPRESS_START_MODE: 4197 case TOUCH_SHORTPRESS_MODE: 4198 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 4199 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 4200 mTouchMode = TOUCH_DONE_MODE; 4201 doShortPress(); 4202 break; 4203 case TOUCH_SELECT_MODE: 4204 commitCopy(); 4205 mTouchSelection = false; 4206 break; 4207 case SCROLL_ZOOM_ANIMATION_IN: 4208 case SCROLL_ZOOM_ANIMATION_OUT: 4209 // no action during scroll animation 4210 break; 4211 case SCROLL_ZOOM_OUT: 4212 if (DebugFlags.WEB_VIEW) { 4213 Log.v(LOGTAG, "ACTION_UP SCROLL_ZOOM_OUT" 4214 + " eventTime - mLastTouchTime=" 4215 + (eventTime - mLastTouchTime)); 4216 } 4217 // for now, always zoom back when the drag completes 4218 if (true || eventTime - mLastTouchTime < TAP_TIMEOUT) { 4219 // but if we tap, zoom in where we tap 4220 if (eventTime - mLastTouchTime < TAP_TIMEOUT) { 4221 zoomScrollTap(x, y); 4222 } 4223 // start zooming in back to the original view 4224 setZoomScrollIn(); 4225 mTouchMode = SCROLL_ZOOM_ANIMATION_IN; 4226 invalidate(); 4227 } 4228 break; 4229 case TOUCH_DRAG_MODE: 4230 // if the user waits a while w/o moving before the 4231 // up, we don't want to do a fling 4232 if (eventTime - mLastTouchTime <= MIN_FLING_TIME) { 4233 mVelocityTracker.addMovement(ev); 4234 doFling(); 4235 break; 4236 } 4237 mLastVelocity = 0; 4238 WebViewCore.resumeUpdate(mWebViewCore); 4239 break; 4240 case TOUCH_DRAG_START_MODE: 4241 case TOUCH_DONE_MODE: 4242 // do nothing 4243 break; 4244 } 4245 // we also use mVelocityTracker == null to tell us that we are 4246 // not "moving around", so we can take the slower/prettier 4247 // mode in the drawing code 4248 if (mVelocityTracker != null) { 4249 mVelocityTracker.recycle(); 4250 mVelocityTracker = null; 4251 } 4252 break; 4253 } 4254 case MotionEvent.ACTION_CANCEL: { 4255 // we also use mVelocityTracker == null to tell us that we are 4256 // not "moving around", so we can take the slower/prettier 4257 // mode in the drawing code 4258 if (mVelocityTracker != null) { 4259 mVelocityTracker.recycle(); 4260 mVelocityTracker = null; 4261 } 4262 if (mTouchMode == SCROLL_ZOOM_OUT || 4263 mTouchMode == SCROLL_ZOOM_ANIMATION_IN) { 4264 scrollTo(mZoomScrollX, mZoomScrollY); 4265 } else if (mTouchMode == TOUCH_DRAG_MODE) { 4266 WebViewCore.resumeUpdate(mWebViewCore); 4267 } 4268 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 4269 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 4270 mTouchMode = TOUCH_DONE_MODE; 4271 nativeHideCursor(); 4272 break; 4273 } 4274 } 4275 return true; 4276 } 4277 4278 private long mTrackballFirstTime = 0; 4279 private long mTrackballLastTime = 0; 4280 private float mTrackballRemainsX = 0.0f; 4281 private float mTrackballRemainsY = 0.0f; 4282 private int mTrackballXMove = 0; 4283 private int mTrackballYMove = 0; 4284 private boolean mExtendSelection = false; 4285 private boolean mTouchSelection = false; 4286 private static final int TRACKBALL_KEY_TIMEOUT = 1000; 4287 private static final int TRACKBALL_TIMEOUT = 200; 4288 private static final int TRACKBALL_WAIT = 100; 4289 private static final int TRACKBALL_SCALE = 400; 4290 private static final int TRACKBALL_SCROLL_COUNT = 5; 4291 private static final int TRACKBALL_MOVE_COUNT = 10; 4292 private static final int TRACKBALL_MULTIPLIER = 3; 4293 private static final int SELECT_CURSOR_OFFSET = 16; 4294 private int mSelectX = 0; 4295 private int mSelectY = 0; 4296 private boolean mShiftIsPressed = false; 4297 private boolean mTrackballDown = false; 4298 private long mTrackballUpTime = 0; 4299 private long mLastCursorTime = 0; 4300 private Rect mLastCursorBounds; 4301 4302 // Set by default; BrowserActivity clears to interpret trackball data 4303 // directly for movement. Currently, the framework only passes 4304 // arrow key events, not trackball events, from one child to the next 4305 private boolean mMapTrackballToArrowKeys = true; 4306 4307 public void setMapTrackballToArrowKeys(boolean setMap) { 4308 mMapTrackballToArrowKeys = setMap; 4309 } 4310 4311 void resetTrackballTime() { 4312 mTrackballLastTime = 0; 4313 } 4314 4315 @Override 4316 public boolean onTrackballEvent(MotionEvent ev) { 4317 long time = ev.getEventTime(); 4318 if ((ev.getMetaState() & KeyEvent.META_ALT_ON) != 0) { 4319 if (ev.getY() > 0) pageDown(true); 4320 if (ev.getY() < 0) pageUp(true); 4321 return true; 4322 } 4323 if (ev.getAction() == MotionEvent.ACTION_DOWN) { 4324 mPrivateHandler.removeMessages(SWITCH_TO_CLICK); 4325 mTrackballDown = true; 4326 if (mNativeClass == 0) { 4327 return false; 4328 } 4329 nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true); 4330 if (time - mLastCursorTime <= TRACKBALL_TIMEOUT 4331 && !mLastCursorBounds.equals(nativeGetCursorRingBounds())) { 4332 nativeSelectBestAt(mLastCursorBounds); 4333 } 4334 if (DebugFlags.WEB_VIEW) { 4335 Log.v(LOGTAG, "onTrackballEvent down ev=" + ev 4336 + " time=" + time 4337 + " mLastCursorTime=" + mLastCursorTime); 4338 } 4339 if (isInTouchMode()) requestFocusFromTouch(); 4340 return false; // let common code in onKeyDown at it 4341 } 4342 if (ev.getAction() == MotionEvent.ACTION_UP) { 4343 // LONG_PRESS_CENTER is set in common onKeyDown 4344 mPrivateHandler.removeMessages(LONG_PRESS_CENTER); 4345 mTrackballDown = false; 4346 mTrackballUpTime = time; 4347 if (mShiftIsPressed) { 4348 if (mExtendSelection) { 4349 commitCopy(); 4350 } else { 4351 mExtendSelection = true; 4352 } 4353 } 4354 if (DebugFlags.WEB_VIEW) { 4355 Log.v(LOGTAG, "onTrackballEvent up ev=" + ev 4356 + " time=" + time 4357 ); 4358 } 4359 return false; // let common code in onKeyUp at it 4360 } 4361 if (mMapTrackballToArrowKeys && mShiftIsPressed == false) { 4362 if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent gmail quit"); 4363 return false; 4364 } 4365 // no move if we're still waiting on SWITCH_TO_CLICK timeout 4366 if (mTouchMode == TOUCH_DOUBLECLICK_MODE) { 4367 if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent 2 click quit"); 4368 return true; 4369 } 4370 if (mTrackballDown) { 4371 if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent down quit"); 4372 return true; // discard move if trackball is down 4373 } 4374 if (time - mTrackballUpTime < TRACKBALL_TIMEOUT) { 4375 if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent up timeout quit"); 4376 return true; 4377 } 4378 // TODO: alternatively we can do panning as touch does 4379 switchOutDrawHistory(); 4380 if (time - mTrackballLastTime > TRACKBALL_TIMEOUT) { 4381 if (DebugFlags.WEB_VIEW) { 4382 Log.v(LOGTAG, "onTrackballEvent time=" 4383 + time + " last=" + mTrackballLastTime); 4384 } 4385 mTrackballFirstTime = time; 4386 mTrackballXMove = mTrackballYMove = 0; 4387 } 4388 mTrackballLastTime = time; 4389 if (DebugFlags.WEB_VIEW) { 4390 Log.v(LOGTAG, "onTrackballEvent ev=" + ev + " time=" + time); 4391 } 4392 mTrackballRemainsX += ev.getX(); 4393 mTrackballRemainsY += ev.getY(); 4394 doTrackball(time); 4395 return true; 4396 } 4397 4398 void moveSelection(float xRate, float yRate) { 4399 if (mNativeClass == 0) 4400 return; 4401 int width = getViewWidth(); 4402 int height = getViewHeight(); 4403 mSelectX += scaleTrackballX(xRate, width); 4404 mSelectY += scaleTrackballY(yRate, height); 4405 int maxX = width + mScrollX; 4406 int maxY = height + mScrollY; 4407 mSelectX = Math.min(maxX, Math.max(mScrollX - SELECT_CURSOR_OFFSET 4408 , mSelectX)); 4409 mSelectY = Math.min(maxY, Math.max(mScrollY - SELECT_CURSOR_OFFSET 4410 , mSelectY)); 4411 if (DebugFlags.WEB_VIEW) { 4412 Log.v(LOGTAG, "moveSelection" 4413 + " mSelectX=" + mSelectX 4414 + " mSelectY=" + mSelectY 4415 + " mScrollX=" + mScrollX 4416 + " mScrollY=" + mScrollY 4417 + " xRate=" + xRate 4418 + " yRate=" + yRate 4419 ); 4420 } 4421 nativeMoveSelection(viewToContentX(mSelectX), 4422 viewToContentY(mSelectY), mExtendSelection); 4423 int scrollX = mSelectX < mScrollX ? -SELECT_CURSOR_OFFSET 4424 : mSelectX > maxX - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET 4425 : 0; 4426 int scrollY = mSelectY < mScrollY ? -SELECT_CURSOR_OFFSET 4427 : mSelectY > maxY - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET 4428 : 0; 4429 pinScrollBy(scrollX, scrollY, true, 0); 4430 Rect select = new Rect(mSelectX, mSelectY, mSelectX + 1, mSelectY + 1); 4431 requestRectangleOnScreen(select); 4432 invalidate(); 4433 } 4434 4435 private int scaleTrackballX(float xRate, int width) { 4436 int xMove = (int) (xRate / TRACKBALL_SCALE * width); 4437 int nextXMove = xMove; 4438 if (xMove > 0) { 4439 if (xMove > mTrackballXMove) { 4440 xMove -= mTrackballXMove; 4441 } 4442 } else if (xMove < mTrackballXMove) { 4443 xMove -= mTrackballXMove; 4444 } 4445 mTrackballXMove = nextXMove; 4446 return xMove; 4447 } 4448 4449 private int scaleTrackballY(float yRate, int height) { 4450 int yMove = (int) (yRate / TRACKBALL_SCALE * height); 4451 int nextYMove = yMove; 4452 if (yMove > 0) { 4453 if (yMove > mTrackballYMove) { 4454 yMove -= mTrackballYMove; 4455 } 4456 } else if (yMove < mTrackballYMove) { 4457 yMove -= mTrackballYMove; 4458 } 4459 mTrackballYMove = nextYMove; 4460 return yMove; 4461 } 4462 4463 private int keyCodeToSoundsEffect(int keyCode) { 4464 switch(keyCode) { 4465 case KeyEvent.KEYCODE_DPAD_UP: 4466 return SoundEffectConstants.NAVIGATION_UP; 4467 case KeyEvent.KEYCODE_DPAD_RIGHT: 4468 return SoundEffectConstants.NAVIGATION_RIGHT; 4469 case KeyEvent.KEYCODE_DPAD_DOWN: 4470 return SoundEffectConstants.NAVIGATION_DOWN; 4471 case KeyEvent.KEYCODE_DPAD_LEFT: 4472 return SoundEffectConstants.NAVIGATION_LEFT; 4473 } 4474 throw new IllegalArgumentException("keyCode must be one of " + 4475 "{KEYCODE_DPAD_UP, KEYCODE_DPAD_RIGHT, KEYCODE_DPAD_DOWN, " + 4476 "KEYCODE_DPAD_LEFT}."); 4477 } 4478 4479 private void doTrackball(long time) { 4480 int elapsed = (int) (mTrackballLastTime - mTrackballFirstTime); 4481 if (elapsed == 0) { 4482 elapsed = TRACKBALL_TIMEOUT; 4483 } 4484 float xRate = mTrackballRemainsX * 1000 / elapsed; 4485 float yRate = mTrackballRemainsY * 1000 / elapsed; 4486 if (mShiftIsPressed) { 4487 moveSelection(xRate, yRate); 4488 mTrackballRemainsX = mTrackballRemainsY = 0; 4489 return; 4490 } 4491 float ax = Math.abs(xRate); 4492 float ay = Math.abs(yRate); 4493 float maxA = Math.max(ax, ay); 4494 if (DebugFlags.WEB_VIEW) { 4495 Log.v(LOGTAG, "doTrackball elapsed=" + elapsed 4496 + " xRate=" + xRate 4497 + " yRate=" + yRate 4498 + " mTrackballRemainsX=" + mTrackballRemainsX 4499 + " mTrackballRemainsY=" + mTrackballRemainsY); 4500 } 4501 int width = mContentWidth - getViewWidth(); 4502 int height = mContentHeight - getViewHeight(); 4503 if (width < 0) width = 0; 4504 if (height < 0) height = 0; 4505 if (mTouchMode == SCROLL_ZOOM_OUT) { 4506 int oldX = mZoomScrollX; 4507 int oldY = mZoomScrollY; 4508 int maxWH = Math.max(width, height); 4509 mZoomScrollX += scaleTrackballX(xRate, maxWH); 4510 mZoomScrollY += scaleTrackballY(yRate, maxWH); 4511 if (DebugFlags.WEB_VIEW) { 4512 Log.v(LOGTAG, "doTrackball SCROLL_ZOOM_OUT" 4513 + " mZoomScrollX=" + mZoomScrollX 4514 + " mZoomScrollY=" + mZoomScrollY); 4515 } 4516 mZoomScrollX = Math.min(width, Math.max(0, mZoomScrollX)); 4517 mZoomScrollY = Math.min(height, Math.max(0, mZoomScrollY)); 4518 if (oldX != mZoomScrollX || oldY != mZoomScrollY) { 4519 invalidate(); 4520 } 4521 mTrackballRemainsX = mTrackballRemainsY = 0; 4522 return; 4523 } 4524 ax = Math.abs(mTrackballRemainsX * TRACKBALL_MULTIPLIER); 4525 ay = Math.abs(mTrackballRemainsY * TRACKBALL_MULTIPLIER); 4526 maxA = Math.max(ax, ay); 4527 int count = Math.max(0, (int) maxA); 4528 int oldScrollX = mScrollX; 4529 int oldScrollY = mScrollY; 4530 if (count > 0) { 4531 int selectKeyCode = ax < ay ? mTrackballRemainsY < 0 ? 4532 KeyEvent.KEYCODE_DPAD_UP : KeyEvent.KEYCODE_DPAD_DOWN : 4533 mTrackballRemainsX < 0 ? KeyEvent.KEYCODE_DPAD_LEFT : 4534 KeyEvent.KEYCODE_DPAD_RIGHT; 4535 count = Math.min(count, TRACKBALL_MOVE_COUNT); 4536 if (DebugFlags.WEB_VIEW) { 4537 Log.v(LOGTAG, "doTrackball keyCode=" + selectKeyCode 4538 + " count=" + count 4539 + " mTrackballRemainsX=" + mTrackballRemainsX 4540 + " mTrackballRemainsY=" + mTrackballRemainsY); 4541 } 4542 if (navHandledKey(selectKeyCode, count, false, time, false)) { 4543 playSoundEffect(keyCodeToSoundsEffect(selectKeyCode)); 4544 } 4545 mTrackballRemainsX = mTrackballRemainsY = 0; 4546 } 4547 if (count >= TRACKBALL_SCROLL_COUNT) { 4548 int xMove = scaleTrackballX(xRate, width); 4549 int yMove = scaleTrackballY(yRate, height); 4550 if (DebugFlags.WEB_VIEW) { 4551 Log.v(LOGTAG, "doTrackball pinScrollBy" 4552 + " count=" + count 4553 + " xMove=" + xMove + " yMove=" + yMove 4554 + " mScrollX-oldScrollX=" + (mScrollX-oldScrollX) 4555 + " mScrollY-oldScrollY=" + (mScrollY-oldScrollY) 4556 ); 4557 } 4558 if (Math.abs(mScrollX - oldScrollX) > Math.abs(xMove)) { 4559 xMove = 0; 4560 } 4561 if (Math.abs(mScrollY - oldScrollY) > Math.abs(yMove)) { 4562 yMove = 0; 4563 } 4564 if (xMove != 0 || yMove != 0) { 4565 pinScrollBy(xMove, yMove, true, 0); 4566 } 4567 mUserScroll = true; 4568 } 4569 } 4570 4571 private int computeMaxScrollY() { 4572 int maxContentH = computeVerticalScrollRange() + 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 = contentToViewDimension(mContentHeight); 5013 int contentWidth = contentToViewDimension(mContentWidth); 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