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