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