WebView.java revision af2af4e53aedb14c781d0351565fd7bec55a141a
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 int scrollY = computeVerticalScrollOffset(); 3002 int viewHeight = getHeight() - getVisibleTitleHeight(); 3003 3004 nativeDrawLayers(mRootLayer, mScrollX, scrollY, 3005 getWidth(), viewHeight, 3006 mActualScale, canvas); 3007 } 3008 } 3009 3010 private void drawCoreAndCursorRing(Canvas canvas, int color, 3011 boolean drawCursorRing) { 3012 if (mDrawHistory) { 3013 canvas.scale(mActualScale, mActualScale); 3014 canvas.drawPicture(mHistoryPicture); 3015 drawLayers(canvas); 3016 return; 3017 } 3018 3019 boolean animateZoom = mZoomScale != 0; 3020 boolean animateScroll = (!mScroller.isFinished() 3021 || mVelocityTracker != null) 3022 && (mTouchMode != TOUCH_DRAG_MODE || 3023 mHeldMotionless != MOTIONLESS_TRUE); 3024 if (mTouchMode == TOUCH_DRAG_MODE) { 3025 if (mHeldMotionless == MOTIONLESS_PENDING) { 3026 mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS); 3027 mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS); 3028 mHeldMotionless = MOTIONLESS_FALSE; 3029 } 3030 if (mHeldMotionless == MOTIONLESS_FALSE) { 3031 mPrivateHandler.sendMessageDelayed(mPrivateHandler 3032 .obtainMessage(DRAG_HELD_MOTIONLESS), MOTIONLESS_TIME); 3033 mHeldMotionless = MOTIONLESS_PENDING; 3034 } 3035 } 3036 if (animateZoom) { 3037 float zoomScale; 3038 int interval = (int) (SystemClock.uptimeMillis() - mZoomStart); 3039 if (interval < ZOOM_ANIMATION_LENGTH) { 3040 float ratio = (float) interval / ZOOM_ANIMATION_LENGTH; 3041 zoomScale = 1.0f / (mInvInitialZoomScale 3042 + (mInvFinalZoomScale - mInvInitialZoomScale) * ratio); 3043 invalidate(); 3044 } else { 3045 zoomScale = mZoomScale; 3046 // set mZoomScale to be 0 as we have done animation 3047 mZoomScale = 0; 3048 // call invalidate() again to draw with the final filters 3049 invalidate(); 3050 if (mNeedToAdjustWebTextView) { 3051 mNeedToAdjustWebTextView = false; 3052 if (didUpdateTextViewBounds(false) 3053 && nativeFocusCandidateIsPassword()) { 3054 // If it is a password field, start drawing the 3055 // WebTextView once again. 3056 mWebTextView.setInPassword(true); 3057 } 3058 } 3059 } 3060 // calculate the intermediate scroll position. As we need to use 3061 // zoomScale, we can't use pinLocX/Y directly. Copy the logic here. 3062 float scale = zoomScale * mInvInitialZoomScale; 3063 int tx = Math.round(scale * (mInitialScrollX + mZoomCenterX) 3064 - mZoomCenterX); 3065 tx = -pinLoc(tx, getViewWidth(), Math.round(mContentWidth 3066 * zoomScale)) + mScrollX; 3067 int titleHeight = getTitleHeight(); 3068 int ty = Math.round(scale 3069 * (mInitialScrollY + mZoomCenterY - titleHeight) 3070 - (mZoomCenterY - titleHeight)); 3071 ty = -(ty <= titleHeight ? Math.max(ty, 0) : pinLoc(ty 3072 - titleHeight, getViewHeight(), Math.round(mContentHeight 3073 * zoomScale)) + titleHeight) + mScrollY; 3074 canvas.translate(tx, ty); 3075 canvas.scale(zoomScale, zoomScale); 3076 if (inEditingMode() && !mNeedToAdjustWebTextView 3077 && mZoomScale != 0) { 3078 // The WebTextView is up. Keep track of this so we can adjust 3079 // its size and placement when we finish zooming 3080 mNeedToAdjustWebTextView = true; 3081 // If it is in password mode, turn it off so it does not draw 3082 // misplaced. 3083 if (nativeFocusCandidateIsPassword()) { 3084 mWebTextView.setInPassword(false); 3085 } 3086 } 3087 } else { 3088 canvas.scale(mActualScale, mActualScale); 3089 } 3090 3091 mWebViewCore.drawContentPicture(canvas, color, animateZoom, 3092 animateScroll); 3093 3094 drawLayers(canvas); 3095 3096 if (mNativeClass == 0) return; 3097 if (mShiftIsPressed && !animateZoom) { 3098 if (mTouchSelection || mExtendSelection) { 3099 nativeDrawSelectionRegion(canvas); 3100 } 3101 if (!mTouchSelection) { 3102 nativeDrawSelectionPointer(canvas, mInvActualScale, mSelectX, 3103 mSelectY - getTitleHeight(), mExtendSelection); 3104 } 3105 } else if (drawCursorRing) { 3106 if (mTouchMode == TOUCH_SHORTPRESS_START_MODE) { 3107 mTouchMode = TOUCH_SHORTPRESS_MODE; 3108 HitTestResult hitTest = getHitTestResult(); 3109 if (mPreventLongPress || (hitTest != null && 3110 hitTest.mType != HitTestResult.UNKNOWN_TYPE)) { 3111 mPrivateHandler.sendMessageDelayed(mPrivateHandler 3112 .obtainMessage(SWITCH_TO_LONGPRESS), 3113 LONG_PRESS_TIMEOUT); 3114 } 3115 } 3116 nativeDrawCursorRing(canvas); 3117 } 3118 // When the FindDialog is up, only draw the matches if we are not in 3119 // the process of scrolling them into view. 3120 if (mFindIsUp && !animateScroll) { 3121 nativeDrawMatches(canvas); 3122 } 3123 if (mFocusSizeChanged) { 3124 mFocusSizeChanged = false; 3125 // If we are zooming, this will get handled above, when the zoom 3126 // finishes. We also do not need to do this unless the WebTextView 3127 // is showing. 3128 if (!animateZoom && inEditingMode()) { 3129 didUpdateTextViewBounds(true); 3130 } 3131 } 3132 } 3133 3134 // draw history 3135 private boolean mDrawHistory = false; 3136 private Picture mHistoryPicture = null; 3137 private int mHistoryWidth = 0; 3138 private int mHistoryHeight = 0; 3139 3140 // Only check the flag, can be called from WebCore thread 3141 boolean drawHistory() { 3142 return mDrawHistory; 3143 } 3144 3145 // Should only be called in UI thread 3146 void switchOutDrawHistory() { 3147 if (null == mWebViewCore) return; // CallbackProxy may trigger this 3148 if (mDrawHistory && mWebViewCore.pictureReady()) { 3149 mDrawHistory = false; 3150 invalidate(); 3151 int oldScrollX = mScrollX; 3152 int oldScrollY = mScrollY; 3153 mScrollX = pinLocX(mScrollX); 3154 mScrollY = pinLocY(mScrollY); 3155 if (oldScrollX != mScrollX || oldScrollY != mScrollY) { 3156 mUserScroll = false; 3157 mWebViewCore.sendMessage(EventHub.SYNC_SCROLL, oldScrollX, 3158 oldScrollY); 3159 } 3160 sendOurVisibleRect(); 3161 } 3162 } 3163 3164 WebViewCore.CursorData cursorData() { 3165 WebViewCore.CursorData result = new WebViewCore.CursorData(); 3166 result.mMoveGeneration = nativeMoveGeneration(); 3167 result.mFrame = nativeCursorFramePointer(); 3168 Point position = nativeCursorPosition(); 3169 result.mX = position.x; 3170 result.mY = position.y; 3171 return result; 3172 } 3173 3174 /** 3175 * Delete text from start to end in the focused textfield. If there is no 3176 * focus, or if start == end, silently fail. If start and end are out of 3177 * order, swap them. 3178 * @param start Beginning of selection to delete. 3179 * @param end End of selection to delete. 3180 */ 3181 /* package */ void deleteSelection(int start, int end) { 3182 mTextGeneration++; 3183 WebViewCore.TextSelectionData data 3184 = new WebViewCore.TextSelectionData(start, end); 3185 mWebViewCore.sendMessage(EventHub.DELETE_SELECTION, mTextGeneration, 0, 3186 data); 3187 } 3188 3189 /** 3190 * Set the selection to (start, end) in the focused textfield. If start and 3191 * end are out of order, swap them. 3192 * @param start Beginning of selection. 3193 * @param end End of selection. 3194 */ 3195 /* package */ void setSelection(int start, int end) { 3196 mWebViewCore.sendMessage(EventHub.SET_SELECTION, start, end); 3197 } 3198 3199 /** 3200 * Called in response to a message from webkit telling us that the soft 3201 * keyboard should be launched. 3202 */ 3203 private void displaySoftKeyboard(boolean isTextView) { 3204 InputMethodManager imm = (InputMethodManager) 3205 getContext().getSystemService(Context.INPUT_METHOD_SERVICE); 3206 3207 if (isTextView) { 3208 rebuildWebTextView(); 3209 if (!inEditingMode()) return; 3210 imm.showSoftInput(mWebTextView, 0); 3211 if (mInZoomOverview) { 3212 // if in zoom overview mode, call doDoubleTap() to bring it back 3213 // to normal mode so that user can enter text. 3214 doDoubleTap(); 3215 } 3216 } 3217 else { // used by plugins 3218 imm.showSoftInput(this, 0); 3219 } 3220 } 3221 3222 // Called by WebKit to instruct the UI to hide the keyboard 3223 private void hideSoftKeyboard() { 3224 InputMethodManager imm = (InputMethodManager) 3225 getContext().getSystemService(Context.INPUT_METHOD_SERVICE); 3226 3227 imm.hideSoftInputFromWindow(this.getWindowToken(), 0); 3228 } 3229 3230 /* 3231 * This method checks the current focus and cursor and potentially rebuilds 3232 * mWebTextView to have the appropriate properties, such as password, 3233 * multiline, and what text it contains. It also removes it if necessary. 3234 */ 3235 /* package */ void rebuildWebTextView() { 3236 // If the WebView does not have focus, do nothing until it gains focus. 3237 if (!hasFocus() && (null == mWebTextView || !mWebTextView.hasFocus())) { 3238 return; 3239 } 3240 boolean alreadyThere = inEditingMode(); 3241 // inEditingMode can only return true if mWebTextView is non-null, 3242 // so we can safely call remove() if (alreadyThere) 3243 if (0 == mNativeClass || !nativeFocusCandidateIsTextInput()) { 3244 if (alreadyThere) { 3245 mWebTextView.remove(); 3246 } 3247 return; 3248 } 3249 // At this point, we know we have found an input field, so go ahead 3250 // and create the WebTextView if necessary. 3251 if (mWebTextView == null) { 3252 mWebTextView = new WebTextView(mContext, WebView.this); 3253 // Initialize our generation number. 3254 mTextGeneration = 0; 3255 } 3256 mWebTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, 3257 contentToViewDimension(nativeFocusCandidateTextSize())); 3258 Rect visibleRect = new Rect(); 3259 calcOurContentVisibleRect(visibleRect); 3260 // Note that sendOurVisibleRect calls viewToContent, so the coordinates 3261 // should be in content coordinates. 3262 Rect bounds = nativeFocusCandidateNodeBounds(); 3263 Rect vBox = contentToViewRect(bounds); 3264 mWebTextView.setRect(vBox.left, vBox.top, vBox.width(), vBox.height()); 3265 if (!Rect.intersects(bounds, visibleRect)) { 3266 mWebTextView.bringIntoView(); 3267 } 3268 String text = nativeFocusCandidateText(); 3269 int nodePointer = nativeFocusCandidatePointer(); 3270 if (alreadyThere && mWebTextView.isSameTextField(nodePointer)) { 3271 // It is possible that we have the same textfield, but it has moved, 3272 // i.e. In the case of opening/closing the screen. 3273 // In that case, we need to set the dimensions, but not the other 3274 // aspects. 3275 // If the text has been changed by webkit, update it. However, if 3276 // there has been more UI text input, ignore it. We will receive 3277 // another update when that text is recognized. 3278 if (text != null && !text.equals(mWebTextView.getText().toString()) 3279 && nativeTextGeneration() == mTextGeneration) { 3280 mWebTextView.setTextAndKeepSelection(text); 3281 } 3282 } else { 3283 mWebTextView.setGravity(nativeFocusCandidateIsRtlText() ? 3284 Gravity.RIGHT : Gravity.NO_GRAVITY); 3285 // This needs to be called before setType, which may call 3286 // requestFormData, and it needs to have the correct nodePointer. 3287 mWebTextView.setNodePointer(nodePointer); 3288 mWebTextView.setType(nativeFocusCandidateType()); 3289 if (null == text) { 3290 if (DebugFlags.WEB_VIEW) { 3291 Log.v(LOGTAG, "rebuildWebTextView null == text"); 3292 } 3293 text = ""; 3294 } 3295 mWebTextView.setTextAndKeepSelection(text); 3296 } 3297 mWebTextView.requestFocus(); 3298 } 3299 3300 /** 3301 * Called by WebTextView to find saved form data associated with the 3302 * textfield 3303 * @param name Name of the textfield. 3304 * @param nodePointer Pointer to the node of the textfield, so it can be 3305 * compared to the currently focused textfield when the data is 3306 * retrieved. 3307 */ 3308 /* package */ void requestFormData(String name, int nodePointer) { 3309 if (mWebViewCore.getSettings().getSaveFormData()) { 3310 Message update = mPrivateHandler.obtainMessage(REQUEST_FORM_DATA); 3311 update.arg1 = nodePointer; 3312 RequestFormData updater = new RequestFormData(name, getUrl(), 3313 update); 3314 Thread t = new Thread(updater); 3315 t.start(); 3316 } 3317 } 3318 3319 /** 3320 * Pass a message to find out the <label> associated with the <input> 3321 * identified by nodePointer 3322 * @param framePointer Pointer to the frame containing the <input> node 3323 * @param nodePointer Pointer to the node for which a <label> is desired. 3324 */ 3325 /* package */ void requestLabel(int framePointer, int nodePointer) { 3326 mWebViewCore.sendMessage(EventHub.REQUEST_LABEL, framePointer, 3327 nodePointer); 3328 } 3329 3330 /* 3331 * This class runs the layers animations in their own thread, 3332 * so that we do not slow down the UI. 3333 */ 3334 private class EvaluateLayersAnimations extends Thread { 3335 boolean mRunning = true; 3336 // delay corresponds to 40fps, no need to go faster. 3337 int mDelay = 25; // in ms 3338 public void run() { 3339 while (mRunning) { 3340 if (mLayersHaveAnimations && mRootLayer != 0) { 3341 // updates is a C++ pointer to a Vector of AnimationValues 3342 int updates = nativeEvaluateLayersAnimations(mRootLayer); 3343 if (updates == 0) { 3344 mRunning = false; 3345 } 3346 Message.obtain(mPrivateHandler, 3347 WebView.IMMEDIATE_REPAINT_MSG_ID, 3348 updates, 0).sendToTarget(); 3349 } else { 3350 mRunning = false; 3351 } 3352 try { 3353 Thread.currentThread().sleep(mDelay); 3354 } catch (InterruptedException e) { 3355 mRunning = false; 3356 } 3357 } 3358 } 3359 public void cancel() { 3360 mRunning = false; 3361 } 3362 } 3363 3364 /* 3365 * This class requests an Adapter for the WebTextView which shows past 3366 * entries stored in the database. It is a Runnable so that it can be done 3367 * in its own thread, without slowing down the UI. 3368 */ 3369 private class RequestFormData implements Runnable { 3370 private String mName; 3371 private String mUrl; 3372 private Message mUpdateMessage; 3373 3374 public RequestFormData(String name, String url, Message msg) { 3375 mName = name; 3376 mUrl = url; 3377 mUpdateMessage = msg; 3378 } 3379 3380 public void run() { 3381 ArrayList<String> pastEntries = mDatabase.getFormData(mUrl, mName); 3382 if (pastEntries.size() > 0) { 3383 AutoCompleteAdapter adapter = new 3384 AutoCompleteAdapter(mContext, pastEntries); 3385 mUpdateMessage.obj = adapter; 3386 mUpdateMessage.sendToTarget(); 3387 } 3388 } 3389 } 3390 3391 /** 3392 * Dump the display tree to "/sdcard/displayTree.txt" 3393 * 3394 * @hide debug only 3395 */ 3396 public void dumpDisplayTree() { 3397 nativeDumpDisplayTree(getUrl()); 3398 } 3399 3400 /** 3401 * Dump the dom tree to adb shell if "toFile" is False, otherwise dump it to 3402 * "/sdcard/domTree.txt" 3403 * 3404 * @hide debug only 3405 */ 3406 public void dumpDomTree(boolean toFile) { 3407 mWebViewCore.sendMessage(EventHub.DUMP_DOMTREE, toFile ? 1 : 0, 0); 3408 } 3409 3410 /** 3411 * Dump the render tree to adb shell if "toFile" is False, otherwise dump it 3412 * to "/sdcard/renderTree.txt" 3413 * 3414 * @hide debug only 3415 */ 3416 public void dumpRenderTree(boolean toFile) { 3417 mWebViewCore.sendMessage(EventHub.DUMP_RENDERTREE, toFile ? 1 : 0, 0); 3418 } 3419 3420 // This is used to determine long press with the center key. Does not 3421 // affect long press with the trackball/touch. 3422 private boolean mGotCenterDown = false; 3423 3424 @Override 3425 public boolean onKeyDown(int keyCode, KeyEvent event) { 3426 if (DebugFlags.WEB_VIEW) { 3427 Log.v(LOGTAG, "keyDown at " + System.currentTimeMillis() 3428 + ", " + event + ", unicode=" + event.getUnicodeChar()); 3429 } 3430 3431 if (mNativeClass == 0) { 3432 return false; 3433 } 3434 3435 // do this hack up front, so it always works, regardless of touch-mode 3436 if (AUTO_REDRAW_HACK && (keyCode == KeyEvent.KEYCODE_CALL)) { 3437 mAutoRedraw = !mAutoRedraw; 3438 if (mAutoRedraw) { 3439 invalidate(); 3440 } 3441 return true; 3442 } 3443 3444 // Bubble up the key event if 3445 // 1. it is a system key; or 3446 // 2. the host application wants to handle it; 3447 if (event.isSystem() 3448 || mCallbackProxy.uiOverrideKeyEvent(event)) { 3449 return false; 3450 } 3451 3452 if (mShiftIsPressed == false && nativeCursorWantsKeyEvents() == false 3453 && (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT 3454 || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT)) { 3455 setUpSelectXY(); 3456 } 3457 3458 if (keyCode >= KeyEvent.KEYCODE_DPAD_UP 3459 && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) { 3460 // always handle the navigation keys in the UI thread 3461 switchOutDrawHistory(); 3462 if (mShiftIsPressed) { 3463 int xRate = keyCode == KeyEvent.KEYCODE_DPAD_LEFT 3464 ? -1 : keyCode == KeyEvent.KEYCODE_DPAD_RIGHT ? 1 : 0; 3465 int yRate = keyCode == KeyEvent.KEYCODE_DPAD_UP ? 3466 -1 : keyCode == KeyEvent.KEYCODE_DPAD_DOWN ? 1 : 0; 3467 int multiplier = event.getRepeatCount() + 1; 3468 moveSelection(xRate * multiplier, yRate * multiplier); 3469 return true; 3470 } 3471 if (navHandledKey(keyCode, 1, false, event.getEventTime(), false)) { 3472 playSoundEffect(keyCodeToSoundsEffect(keyCode)); 3473 return true; 3474 } 3475 // Bubble up the key event as WebView doesn't handle it 3476 return false; 3477 } 3478 3479 if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { 3480 switchOutDrawHistory(); 3481 if (event.getRepeatCount() == 0) { 3482 if (mShiftIsPressed) { 3483 return true; // discard press if copy in progress 3484 } 3485 mGotCenterDown = true; 3486 mPrivateHandler.sendMessageDelayed(mPrivateHandler 3487 .obtainMessage(LONG_PRESS_CENTER), LONG_PRESS_TIMEOUT); 3488 // Already checked mNativeClass, so we do not need to check it 3489 // again. 3490 nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true); 3491 return true; 3492 } 3493 // Bubble up the key event as WebView doesn't handle it 3494 return false; 3495 } 3496 3497 if (keyCode != KeyEvent.KEYCODE_SHIFT_LEFT 3498 && keyCode != KeyEvent.KEYCODE_SHIFT_RIGHT) { 3499 // turn off copy select if a shift-key combo is pressed 3500 mExtendSelection = mShiftIsPressed = false; 3501 if (mTouchMode == TOUCH_SELECT_MODE) { 3502 mTouchMode = TOUCH_INIT_MODE; 3503 } 3504 } 3505 3506 if (getSettings().getNavDump()) { 3507 switch (keyCode) { 3508 case KeyEvent.KEYCODE_4: 3509 dumpDisplayTree(); 3510 break; 3511 case KeyEvent.KEYCODE_5: 3512 case KeyEvent.KEYCODE_6: 3513 dumpDomTree(keyCode == KeyEvent.KEYCODE_5); 3514 break; 3515 case KeyEvent.KEYCODE_7: 3516 case KeyEvent.KEYCODE_8: 3517 dumpRenderTree(keyCode == KeyEvent.KEYCODE_7); 3518 break; 3519 case KeyEvent.KEYCODE_9: 3520 nativeInstrumentReport(); 3521 return true; 3522 } 3523 } 3524 3525 if (nativeCursorIsTextInput()) { 3526 // This message will put the node in focus, for the DOM's notion 3527 // of focus, and make the focuscontroller active 3528 mWebViewCore.sendMessage(EventHub.CLICK, nativeCursorFramePointer(), 3529 nativeCursorNodePointer()); 3530 // This will bring up the WebTextView and put it in focus, for 3531 // our view system's notion of focus 3532 rebuildWebTextView(); 3533 // Now we need to pass the event to it 3534 if (inEditingMode()) { 3535 mWebTextView.setDefaultSelection(); 3536 return mWebTextView.dispatchKeyEvent(event); 3537 } 3538 } else if (nativeHasFocusNode()) { 3539 // In this case, the cursor is not on a text input, but the focus 3540 // might be. Check it, and if so, hand over to the WebTextView. 3541 rebuildWebTextView(); 3542 if (inEditingMode()) { 3543 return mWebTextView.dispatchKeyEvent(event); 3544 } 3545 } 3546 3547 // TODO: should we pass all the keys to DOM or check the meta tag 3548 if (nativeCursorWantsKeyEvents() || true) { 3549 // pass the key to DOM 3550 mWebViewCore.sendMessage(EventHub.KEY_DOWN, event); 3551 // return true as DOM handles the key 3552 return true; 3553 } 3554 3555 // Bubble up the key event as WebView doesn't handle it 3556 return false; 3557 } 3558 3559 @Override 3560 public boolean onKeyUp(int keyCode, KeyEvent event) { 3561 if (DebugFlags.WEB_VIEW) { 3562 Log.v(LOGTAG, "keyUp at " + System.currentTimeMillis() 3563 + ", " + event + ", unicode=" + event.getUnicodeChar()); 3564 } 3565 3566 if (mNativeClass == 0) { 3567 return false; 3568 } 3569 3570 // special CALL handling when cursor node's href is "tel:XXX" 3571 if (keyCode == KeyEvent.KEYCODE_CALL && nativeHasCursorNode()) { 3572 String text = nativeCursorText(); 3573 if (!nativeCursorIsTextInput() && text != null 3574 && text.startsWith(SCHEME_TEL)) { 3575 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(text)); 3576 getContext().startActivity(intent); 3577 return true; 3578 } 3579 } 3580 3581 // Bubble up the key event if 3582 // 1. it is a system key; or 3583 // 2. the host application wants to handle it; 3584 if (event.isSystem() || mCallbackProxy.uiOverrideKeyEvent(event)) { 3585 return false; 3586 } 3587 3588 if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT 3589 || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT) { 3590 if (commitCopy()) { 3591 return true; 3592 } 3593 } 3594 3595 if (keyCode >= KeyEvent.KEYCODE_DPAD_UP 3596 && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) { 3597 // always handle the navigation keys in the UI thread 3598 // Bubble up the key event as WebView doesn't handle it 3599 return false; 3600 } 3601 3602 if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { 3603 // remove the long press message first 3604 mPrivateHandler.removeMessages(LONG_PRESS_CENTER); 3605 mGotCenterDown = false; 3606 3607 if (mShiftIsPressed) { 3608 if (mExtendSelection) { 3609 commitCopy(); 3610 } else { 3611 mExtendSelection = true; 3612 invalidate(); // draw the i-beam instead of the arrow 3613 } 3614 return true; // discard press if copy in progress 3615 } 3616 3617 // perform the single click 3618 Rect visibleRect = sendOurVisibleRect(); 3619 // Note that sendOurVisibleRect calls viewToContent, so the 3620 // coordinates should be in content coordinates. 3621 if (!nativeCursorIntersects(visibleRect)) { 3622 return false; 3623 } 3624 WebViewCore.CursorData data = cursorData(); 3625 mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE, data); 3626 playSoundEffect(SoundEffectConstants.CLICK); 3627 if (nativeCursorIsTextInput()) { 3628 rebuildWebTextView(); 3629 centerKeyPressOnTextField(); 3630 if (inEditingMode()) { 3631 mWebTextView.setDefaultSelection(); 3632 } 3633 return true; 3634 } 3635 nativeSetFollowedLink(true); 3636 if (!mCallbackProxy.uiOverrideUrlLoading(nativeCursorText())) { 3637 mWebViewCore.sendMessage(EventHub.CLICK, data.mFrame, 3638 nativeCursorNodePointer()); 3639 } 3640 return true; 3641 } 3642 3643 // TODO: should we pass all the keys to DOM or check the meta tag 3644 if (nativeCursorWantsKeyEvents() || true) { 3645 // pass the key to DOM 3646 mWebViewCore.sendMessage(EventHub.KEY_UP, event); 3647 // return true as DOM handles the key 3648 return true; 3649 } 3650 3651 // Bubble up the key event as WebView doesn't handle it 3652 return false; 3653 } 3654 3655 private void setUpSelectXY() { 3656 mExtendSelection = false; 3657 mShiftIsPressed = true; 3658 if (nativeHasCursorNode()) { 3659 Rect rect = nativeCursorNodeBounds(); 3660 mSelectX = contentToViewX(rect.left); 3661 mSelectY = contentToViewY(rect.top); 3662 } else if (mLastTouchY > getVisibleTitleHeight()) { 3663 mSelectX = mScrollX + (int) mLastTouchX; 3664 mSelectY = mScrollY + (int) mLastTouchY; 3665 } else { 3666 mSelectX = mScrollX + getViewWidth() / 2; 3667 mSelectY = mScrollY + getViewHeightWithTitle() / 2; 3668 } 3669 nativeHideCursor(); 3670 } 3671 3672 /** 3673 * @hide 3674 */ 3675 public void emulateShiftHeld() { 3676 if (0 == mNativeClass) return; // client isn't initialized 3677 setUpSelectXY(); 3678 } 3679 3680 private boolean commitCopy() { 3681 boolean copiedSomething = false; 3682 if (mExtendSelection) { 3683 // copy region so core operates on copy without touching orig. 3684 Region selection = new Region(nativeGetSelection()); 3685 if (selection.isEmpty() == false) { 3686 Toast.makeText(mContext 3687 , com.android.internal.R.string.text_copied 3688 , Toast.LENGTH_SHORT).show(); 3689 mWebViewCore.sendMessage(EventHub.GET_SELECTION, selection); 3690 copiedSomething = true; 3691 } 3692 mExtendSelection = false; 3693 } 3694 mShiftIsPressed = false; 3695 invalidate(); // remove selection region and pointer 3696 if (mTouchMode == TOUCH_SELECT_MODE) { 3697 mTouchMode = TOUCH_INIT_MODE; 3698 } 3699 return copiedSomething; 3700 } 3701 3702 @Override 3703 protected void onAttachedToWindow() { 3704 super.onAttachedToWindow(); 3705 if (hasWindowFocus()) onWindowFocusChanged(true); 3706 } 3707 3708 @Override 3709 protected void onDetachedFromWindow() { 3710 clearTextEntry(); 3711 super.onDetachedFromWindow(); 3712 // Clean up the zoom controller 3713 mZoomButtonsController.setVisible(false); 3714 } 3715 3716 /** 3717 * @deprecated WebView no longer needs to implement 3718 * ViewGroup.OnHierarchyChangeListener. This method does nothing now. 3719 */ 3720 @Deprecated 3721 public void onChildViewAdded(View parent, View child) {} 3722 3723 /** 3724 * @deprecated WebView no longer needs to implement 3725 * ViewGroup.OnHierarchyChangeListener. This method does nothing now. 3726 */ 3727 @Deprecated 3728 public void onChildViewRemoved(View p, View child) {} 3729 3730 /** 3731 * @deprecated WebView should not have implemented 3732 * ViewTreeObserver.OnGlobalFocusChangeListener. This method 3733 * does nothing now. 3734 */ 3735 @Deprecated 3736 public void onGlobalFocusChanged(View oldFocus, View newFocus) { 3737 } 3738 3739 // To avoid drawing the cursor ring, and remove the TextView when our window 3740 // loses focus. 3741 @Override 3742 public void onWindowFocusChanged(boolean hasWindowFocus) { 3743 if (hasWindowFocus) { 3744 if (hasFocus()) { 3745 // If our window regained focus, and we have focus, then begin 3746 // drawing the cursor ring 3747 mDrawCursorRing = true; 3748 if (mNativeClass != 0) { 3749 nativeRecordButtons(true, false, true); 3750 if (inEditingMode()) { 3751 mWebViewCore.sendMessage(EventHub.SET_ACTIVE, 1, 0); 3752 } 3753 } 3754 } else { 3755 // If our window gained focus, but we do not have it, do not 3756 // draw the cursor ring. 3757 mDrawCursorRing = false; 3758 // We do not call nativeRecordButtons here because we assume 3759 // that when we lost focus, or window focus, it got called with 3760 // false for the first parameter 3761 } 3762 } else { 3763 if (getSettings().getBuiltInZoomControls() && !mZoomButtonsController.isVisible()) { 3764 /* 3765 * The zoom controls come in their own window, so our window 3766 * loses focus. Our policy is to not draw the cursor ring if 3767 * our window is not focused, but this is an exception since 3768 * the user can still navigate the web page with the zoom 3769 * controls showing. 3770 */ 3771 // If our window has lost focus, stop drawing the cursor ring 3772 mDrawCursorRing = false; 3773 } 3774 mGotKeyDown = false; 3775 mShiftIsPressed = false; 3776 if (mNativeClass != 0) { 3777 nativeRecordButtons(false, false, true); 3778 } 3779 setFocusControllerInactive(); 3780 } 3781 invalidate(); 3782 super.onWindowFocusChanged(hasWindowFocus); 3783 } 3784 3785 /* 3786 * Pass a message to WebCore Thread, telling the WebCore::Page's 3787 * FocusController to be "inactive" so that it will 3788 * not draw the blinking cursor. It gets set to "active" to draw the cursor 3789 * in WebViewCore.cpp, when the WebCore thread receives key events/clicks. 3790 */ 3791 /* package */ void setFocusControllerInactive() { 3792 // Do not need to also check whether mWebViewCore is null, because 3793 // mNativeClass is only set if mWebViewCore is non null 3794 if (mNativeClass == 0) return; 3795 mWebViewCore.sendMessage(EventHub.SET_ACTIVE, 0, 0); 3796 } 3797 3798 @Override 3799 protected void onFocusChanged(boolean focused, int direction, 3800 Rect previouslyFocusedRect) { 3801 if (DebugFlags.WEB_VIEW) { 3802 Log.v(LOGTAG, "MT focusChanged " + focused + ", " + direction); 3803 } 3804 if (focused) { 3805 // When we regain focus, if we have window focus, resume drawing 3806 // the cursor ring 3807 if (hasWindowFocus()) { 3808 mDrawCursorRing = true; 3809 if (mNativeClass != 0) { 3810 nativeRecordButtons(true, false, true); 3811 } 3812 //} else { 3813 // The WebView has gained focus while we do not have 3814 // windowfocus. When our window lost focus, we should have 3815 // called nativeRecordButtons(false...) 3816 } 3817 } else { 3818 // When we lost focus, unless focus went to the TextView (which is 3819 // true if we are in editing mode), stop drawing the cursor ring. 3820 if (!inEditingMode()) { 3821 mDrawCursorRing = false; 3822 if (mNativeClass != 0) { 3823 nativeRecordButtons(false, false, true); 3824 } 3825 setFocusControllerInactive(); 3826 } 3827 mGotKeyDown = false; 3828 } 3829 3830 super.onFocusChanged(focused, direction, previouslyFocusedRect); 3831 } 3832 3833 /** 3834 * @hide 3835 */ 3836 @Override 3837 protected boolean setFrame(int left, int top, int right, int bottom) { 3838 boolean changed = super.setFrame(left, top, right, bottom); 3839 if (!changed && mHeightCanMeasure) { 3840 // When mHeightCanMeasure is true, we will set mLastHeightSent to 0 3841 // in WebViewCore after we get the first layout. We do call 3842 // requestLayout() when we get contentSizeChanged(). But the View 3843 // system won't call onSizeChanged if the dimension is not changed. 3844 // In this case, we need to call sendViewSizeZoom() explicitly to 3845 // notify the WebKit about the new dimensions. 3846 sendViewSizeZoom(); 3847 } 3848 return changed; 3849 } 3850 3851 @Override 3852 protected void onSizeChanged(int w, int h, int ow, int oh) { 3853 super.onSizeChanged(w, h, ow, oh); 3854 // Center zooming to the center of the screen. 3855 if (mZoomScale == 0) { // unless we're already zooming 3856 mZoomCenterX = getViewWidth() * .5f; 3857 mZoomCenterY = getViewHeight() * .5f; 3858 } 3859 3860 // adjust the max viewport width depending on the view dimensions. This 3861 // is to ensure the scaling is not going insane. So do not shrink it if 3862 // the view size is temporarily smaller, e.g. when soft keyboard is up. 3863 int newMaxViewportWidth = (int) (Math.max(w, h) / DEFAULT_MIN_ZOOM_SCALE); 3864 if (newMaxViewportWidth > sMaxViewportWidth) { 3865 sMaxViewportWidth = newMaxViewportWidth; 3866 } 3867 3868 // update mMinZoomScale if the minimum zoom scale is not fixed 3869 if (!mMinZoomScaleFixed) { 3870 // when change from narrow screen to wide screen, the new viewWidth 3871 // can be wider than the old content width. We limit the minimum 3872 // scale to 1.0f. The proper minimum scale will be calculated when 3873 // the new picture shows up. 3874 mMinZoomScale = Math.min(1.0f, (float) getViewWidth() 3875 / (mDrawHistory ? mHistoryPicture.getWidth() 3876 : mZoomOverviewWidth)); 3877 if (mInitialScaleInPercent > 0) { 3878 // limit the minZoomScale to the initialScale if it is set 3879 float initialScale = mInitialScaleInPercent / 100.0f; 3880 if (mMinZoomScale > initialScale) { 3881 mMinZoomScale = initialScale; 3882 } 3883 } 3884 } 3885 3886 // onSizeChanged() is called during WebView layout. And any 3887 // requestLayout() is blocked during layout. As setNewZoomScale() will 3888 // call its child View to reposition itself through ViewManager's 3889 // scaleAll(), we need to post a Runnable to ensure requestLayout(). 3890 post(new Runnable() { 3891 public void run() { 3892 // we always force, in case our height changed, in which case we 3893 // still want to send the notification over to webkit 3894 setNewZoomScale(mActualScale, true); 3895 } 3896 }); 3897 } 3898 3899 @Override 3900 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 3901 super.onScrollChanged(l, t, oldl, oldt); 3902 3903 sendOurVisibleRect(); 3904 } 3905 3906 3907 @Override 3908 public boolean dispatchKeyEvent(KeyEvent event) { 3909 boolean dispatch = true; 3910 3911 if (!inEditingMode()) { 3912 if (event.getAction() == KeyEvent.ACTION_DOWN) { 3913 mGotKeyDown = true; 3914 } else { 3915 if (!mGotKeyDown) { 3916 /* 3917 * We got a key up for which we were not the recipient of 3918 * the original key down. Don't give it to the view. 3919 */ 3920 dispatch = false; 3921 } 3922 mGotKeyDown = false; 3923 } 3924 } 3925 3926 if (dispatch) { 3927 return super.dispatchKeyEvent(event); 3928 } else { 3929 // We didn't dispatch, so let something else handle the key 3930 return false; 3931 } 3932 } 3933 3934 // Here are the snap align logic: 3935 // 1. If it starts nearly horizontally or vertically, snap align; 3936 // 2. If there is a dramitic direction change, let it go; 3937 // 3. If there is a same direction back and forth, lock it. 3938 3939 // adjustable parameters 3940 private int mMinLockSnapReverseDistance; 3941 private static final float MAX_SLOPE_FOR_DIAG = 1.5f; 3942 private static final int MIN_BREAK_SNAP_CROSS_DISTANCE = 80; 3943 3944 private static int sign(float x) { 3945 return x > 0 ? 1 : (x < 0 ? -1 : 0); 3946 } 3947 3948 // if the page can scroll <= this value, we won't allow the drag tracker 3949 // to have any effect. 3950 private static final int MIN_SCROLL_AMOUNT_TO_DISABLE_DRAG_TRACKER = 4; 3951 3952 private class DragTrackerHandler { 3953 private final DragTracker mProxy; 3954 private final float mStartY, mStartX; 3955 private final float mMinDY, mMinDX; 3956 private final float mMaxDY, mMaxDX; 3957 private float mCurrStretchY, mCurrStretchX; 3958 private int mSX, mSY; 3959 3960 public DragTrackerHandler(float x, float y, DragTracker proxy) { 3961 mProxy = proxy; 3962 3963 int docBottom = computeVerticalScrollRange() + getTitleHeight(); 3964 int viewTop = getScrollY(); 3965 int viewBottom = viewTop + getHeight(); 3966 3967 mStartY = y; 3968 mMinDY = -viewTop; 3969 mMaxDY = docBottom - viewBottom; 3970 3971 if (DebugFlags.DRAG_TRACKER) { 3972 Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, " dragtracker y= " + y + 3973 " up/down= " + mMinDY + " " + mMaxDY); 3974 } 3975 3976 int docRight = computeHorizontalScrollRange(); 3977 int viewLeft = getScrollX(); 3978 int viewRight = viewLeft + getWidth(); 3979 mStartX = x; 3980 mMinDX = -viewLeft; 3981 mMaxDX = docRight - viewRight; 3982 3983 mProxy.onStartDrag(x, y); 3984 3985 // ensure we buildBitmap at least once 3986 mSX = -99999; 3987 } 3988 3989 private float computeStretch(float delta, float min, float max) { 3990 float stretch = 0; 3991 if (max - min > MIN_SCROLL_AMOUNT_TO_DISABLE_DRAG_TRACKER) { 3992 if (delta < min) { 3993 stretch = delta - min; 3994 } else if (delta > max) { 3995 stretch = delta - max; 3996 } 3997 } 3998 return stretch; 3999 } 4000 4001 public void dragTo(float x, float y) { 4002 float sy = computeStretch(mStartY - y, mMinDY, mMaxDY); 4003 float sx = computeStretch(mStartX - x, mMinDX, mMaxDX); 4004 4005 if (mCurrStretchX != sx || mCurrStretchY != sy) { 4006 mCurrStretchX = sx; 4007 mCurrStretchY = sy; 4008 if (DebugFlags.DRAG_TRACKER) { 4009 Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, "---- stretch " + sx + 4010 " " + sy); 4011 } 4012 if (mProxy.onStretchChange(sx, sy)) { 4013 invalidate(); 4014 } 4015 } 4016 } 4017 4018 public void stopDrag() { 4019 if (DebugFlags.DRAG_TRACKER) { 4020 Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, "----- stopDrag"); 4021 } 4022 mProxy.onStopDrag(); 4023 } 4024 4025 private int hiddenHeightOfTitleBar() { 4026 return getTitleHeight() - getVisibleTitleHeight(); 4027 } 4028 4029 // need a way to know if 565 or 8888 is the right config for 4030 // capturing the display and giving it to the drag proxy 4031 private Bitmap.Config offscreenBitmapConfig() { 4032 // hard code 565 for now 4033 return Bitmap.Config.RGB_565; 4034 } 4035 4036 /* If the tracker draws, then this returns true, otherwise it will 4037 return false, and draw nothing. 4038 */ 4039 public boolean draw(Canvas canvas) { 4040 if (mCurrStretchX != 0 || mCurrStretchY != 0) { 4041 int sx = getScrollX(); 4042 int sy = getScrollY() - hiddenHeightOfTitleBar(); 4043 4044 if (mSX != sx || mSY != sy) { 4045 buildBitmap(sx, sy); 4046 mSX = sx; 4047 mSY = sy; 4048 } 4049 4050 int count = canvas.save(Canvas.MATRIX_SAVE_FLAG); 4051 canvas.translate(sx, sy); 4052 mProxy.onDraw(canvas); 4053 canvas.restoreToCount(count); 4054 return true; 4055 } 4056 if (DebugFlags.DRAG_TRACKER) { 4057 Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, " -- draw false " + 4058 mCurrStretchX + " " + mCurrStretchY); 4059 } 4060 return false; 4061 } 4062 4063 private void buildBitmap(int sx, int sy) { 4064 int w = getWidth(); 4065 int h = getViewHeight(); 4066 Bitmap bm = Bitmap.createBitmap(w, h, offscreenBitmapConfig()); 4067 Canvas canvas = new Canvas(bm); 4068 canvas.translate(-sx, -sy); 4069 drawContent(canvas); 4070 4071 if (DebugFlags.DRAG_TRACKER) { 4072 Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, "--- buildBitmap " + sx + 4073 " " + sy + " " + w + " " + h); 4074 } 4075 mProxy.onBitmapChange(bm); 4076 } 4077 } 4078 4079 /** @hide */ 4080 public static class DragTracker { 4081 public void onStartDrag(float x, float y) {} 4082 public boolean onStretchChange(float sx, float sy) { 4083 // return true to have us inval the view 4084 return false; 4085 } 4086 public void onStopDrag() {} 4087 public void onBitmapChange(Bitmap bm) {} 4088 public void onDraw(Canvas canvas) {} 4089 } 4090 4091 /** @hide */ 4092 public DragTracker getDragTracker() { 4093 return mDragTracker; 4094 } 4095 4096 /** @hide */ 4097 public void setDragTracker(DragTracker tracker) { 4098 mDragTracker = tracker; 4099 } 4100 4101 private DragTracker mDragTracker; 4102 private DragTrackerHandler mDragTrackerHandler; 4103 4104 @Override 4105 public boolean onTouchEvent(MotionEvent ev) { 4106 if (mNativeClass == 0 || !isClickable() || !isLongClickable()) { 4107 return false; 4108 } 4109 4110 if (DebugFlags.WEB_VIEW) { 4111 Log.v(LOGTAG, ev + " at " + ev.getEventTime() + " mTouchMode=" 4112 + mTouchMode); 4113 } 4114 4115 int action = ev.getAction(); 4116 float x = ev.getX(); 4117 float y = ev.getY(); 4118 long eventTime = ev.getEventTime(); 4119 4120 // Due to the touch screen edge effect, a touch closer to the edge 4121 // always snapped to the edge. As getViewWidth() can be different from 4122 // getWidth() due to the scrollbar, adjusting the point to match 4123 // getViewWidth(). Same applied to the height. 4124 if (x > getViewWidth() - 1) { 4125 x = getViewWidth() - 1; 4126 } 4127 if (y > getViewHeightWithTitle() - 1) { 4128 y = getViewHeightWithTitle() - 1; 4129 } 4130 4131 // pass the touch events from UI thread to WebCore thread 4132 if (mForwardTouchEvents && (action != MotionEvent.ACTION_MOVE 4133 || eventTime - mLastSentTouchTime > TOUCH_SENT_INTERVAL)) { 4134 WebViewCore.TouchEventData ted = new WebViewCore.TouchEventData(); 4135 ted.mAction = action; 4136 ted.mX = viewToContentX((int) x + mScrollX); 4137 ted.mY = viewToContentY((int) y + mScrollY); 4138 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 4139 mLastSentTouchTime = eventTime; 4140 } 4141 4142 float fDeltaX = mLastTouchX - x; 4143 float fDeltaY = mLastTouchY - y; 4144 int deltaX = (int) fDeltaX; 4145 int deltaY = (int) fDeltaY; 4146 4147 switch (action) { 4148 case MotionEvent.ACTION_DOWN: { 4149 mPreventDrag = PREVENT_DRAG_NO; 4150 if (!mScroller.isFinished()) { 4151 // stop the current scroll animation, but if this is 4152 // the start of a fling, allow it to add to the current 4153 // fling's velocity 4154 mScroller.abortAnimation(); 4155 mTouchMode = TOUCH_DRAG_START_MODE; 4156 mPrivateHandler.removeMessages(RESUME_WEBCORE_UPDATE); 4157 } else if (mShiftIsPressed) { 4158 mSelectX = mScrollX + (int) x; 4159 mSelectY = mScrollY + (int) y; 4160 mTouchMode = TOUCH_SELECT_MODE; 4161 if (DebugFlags.WEB_VIEW) { 4162 Log.v(LOGTAG, "select=" + mSelectX + "," + mSelectY); 4163 } 4164 nativeMoveSelection(viewToContentX(mSelectX), 4165 viewToContentY(mSelectY), false); 4166 mTouchSelection = mExtendSelection = true; 4167 invalidate(); // draw the i-beam instead of the arrow 4168 } else if (mPrivateHandler.hasMessages(RELEASE_SINGLE_TAP)) { 4169 mPrivateHandler.removeMessages(RELEASE_SINGLE_TAP); 4170 if (deltaX * deltaX + deltaY * deltaY < mDoubleTapSlopSquare) { 4171 mTouchMode = TOUCH_DOUBLE_TAP_MODE; 4172 } else { 4173 // commit the short press action for the previous tap 4174 doShortPress(); 4175 // continue, mTouchMode should be still TOUCH_INIT_MODE 4176 } 4177 } else { 4178 mTouchMode = TOUCH_INIT_MODE; 4179 mPreventDrag = mForwardTouchEvents ? PREVENT_DRAG_MAYBE_YES 4180 : PREVENT_DRAG_NO; 4181 mPreventLongPress = false; 4182 mPreventDoubleTap = false; 4183 mWebViewCore.sendMessage( 4184 EventHub.UPDATE_FRAME_CACHE_IF_LOADING); 4185 if (mLogEvent && eventTime - mLastTouchUpTime < 1000) { 4186 EventLog.writeEvent(EVENT_LOG_DOUBLE_TAP_DURATION, 4187 (eventTime - mLastTouchUpTime), eventTime); 4188 } 4189 } 4190 // Trigger the link 4191 if (mTouchMode == TOUCH_INIT_MODE 4192 || mTouchMode == TOUCH_DOUBLE_TAP_MODE) { 4193 mPrivateHandler.sendMessageDelayed(mPrivateHandler 4194 .obtainMessage(SWITCH_TO_SHORTPRESS), TAP_TIMEOUT); 4195 } 4196 // Remember where the motion event started 4197 mLastTouchX = x; 4198 mLastTouchY = y; 4199 mLastTouchTime = eventTime; 4200 mVelocityTracker = VelocityTracker.obtain(); 4201 mSnapScrollMode = SNAP_NONE; 4202 if (mDragTracker != null) { 4203 mDragTrackerHandler = new DragTrackerHandler(x, y, 4204 mDragTracker); 4205 } 4206 break; 4207 } 4208 case MotionEvent.ACTION_MOVE: { 4209 if (mTouchMode == TOUCH_DONE_MODE) { 4210 // no dragging during scroll zoom animation 4211 break; 4212 } 4213 mVelocityTracker.addMovement(ev); 4214 4215 if (mTouchMode != TOUCH_DRAG_MODE) { 4216 if (mTouchMode == TOUCH_SELECT_MODE) { 4217 mSelectX = mScrollX + (int) x; 4218 mSelectY = mScrollY + (int) y; 4219 if (DebugFlags.WEB_VIEW) { 4220 Log.v(LOGTAG, "xtend=" + mSelectX + "," + mSelectY); 4221 } 4222 nativeMoveSelection(viewToContentX(mSelectX), 4223 viewToContentY(mSelectY), true); 4224 invalidate(); 4225 break; 4226 } 4227 if ((deltaX * deltaX + deltaY * deltaY) < mTouchSlopSquare) { 4228 break; 4229 } 4230 if (mPreventDrag == PREVENT_DRAG_MAYBE_YES) { 4231 // track mLastTouchTime as we may need to do fling at 4232 // ACTION_UP 4233 mLastTouchTime = eventTime; 4234 break; 4235 } 4236 if (mTouchMode == TOUCH_SHORTPRESS_MODE 4237 || mTouchMode == TOUCH_SHORTPRESS_START_MODE) { 4238 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 4239 } else if (mTouchMode == TOUCH_INIT_MODE 4240 || mTouchMode == TOUCH_DOUBLE_TAP_MODE) { 4241 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 4242 } 4243 if (mFullScreenHolder != null) { 4244 // in full screen mode, the WebView can't be panned. 4245 mTouchMode = TOUCH_DONE_MODE; 4246 break; 4247 } 4248 4249 // if it starts nearly horizontal or vertical, enforce it 4250 int ax = Math.abs(deltaX); 4251 int ay = Math.abs(deltaY); 4252 if (ax > MAX_SLOPE_FOR_DIAG * ay) { 4253 mSnapScrollMode = SNAP_X; 4254 mSnapPositive = deltaX > 0; 4255 } else if (ay > MAX_SLOPE_FOR_DIAG * ax) { 4256 mSnapScrollMode = SNAP_Y; 4257 mSnapPositive = deltaY > 0; 4258 } 4259 4260 mTouchMode = TOUCH_DRAG_MODE; 4261 mLastTouchX = x; 4262 mLastTouchY = y; 4263 fDeltaX = 0.0f; 4264 fDeltaY = 0.0f; 4265 deltaX = 0; 4266 deltaY = 0; 4267 4268 WebViewCore.pauseUpdate(mWebViewCore); 4269 if (!mDragFromTextInput) { 4270 nativeHideCursor(); 4271 } 4272 WebSettings settings = getSettings(); 4273 if (settings.supportZoom() 4274 && settings.getBuiltInZoomControls() 4275 && !mZoomButtonsController.isVisible() 4276 && mMinZoomScale < mMaxZoomScale) { 4277 mZoomButtonsController.setVisible(true); 4278 int count = settings.getDoubleTapToastCount(); 4279 if (mInZoomOverview && count > 0) { 4280 settings.setDoubleTapToastCount(--count); 4281 Toast.makeText(mContext, 4282 com.android.internal.R.string.double_tap_toast, 4283 Toast.LENGTH_LONG).show(); 4284 } 4285 } 4286 } 4287 4288 // do pan 4289 int newScrollX = pinLocX(mScrollX + deltaX); 4290 int newDeltaX = newScrollX - mScrollX; 4291 if (deltaX != newDeltaX) { 4292 deltaX = newDeltaX; 4293 fDeltaX = (float) newDeltaX; 4294 } 4295 int newScrollY = pinLocY(mScrollY + deltaY); 4296 int newDeltaY = newScrollY - mScrollY; 4297 if (deltaY != newDeltaY) { 4298 deltaY = newDeltaY; 4299 fDeltaY = (float) newDeltaY; 4300 } 4301 boolean done = false; 4302 boolean keepScrollBarsVisible = false; 4303 if (Math.abs(fDeltaX) < 1.0f && Math.abs(fDeltaY) < 1.0f) { 4304 keepScrollBarsVisible = done = true; 4305 } else { 4306 if (mSnapScrollMode == SNAP_X || mSnapScrollMode == SNAP_Y) { 4307 int ax = Math.abs(deltaX); 4308 int ay = Math.abs(deltaY); 4309 if (mSnapScrollMode == SNAP_X) { 4310 // radical change means getting out of snap mode 4311 if (ay > MAX_SLOPE_FOR_DIAG * ax 4312 && ay > MIN_BREAK_SNAP_CROSS_DISTANCE) { 4313 mSnapScrollMode = SNAP_NONE; 4314 } 4315 // reverse direction means lock in the snap mode 4316 if (ax > MAX_SLOPE_FOR_DIAG * ay && 4317 (mSnapPositive 4318 ? deltaX < -mMinLockSnapReverseDistance 4319 : deltaX > mMinLockSnapReverseDistance)) { 4320 mSnapScrollMode |= SNAP_LOCK; 4321 } 4322 } else { 4323 // radical change means getting out of snap mode 4324 if (ax > MAX_SLOPE_FOR_DIAG * ay 4325 && ax > MIN_BREAK_SNAP_CROSS_DISTANCE) { 4326 mSnapScrollMode = SNAP_NONE; 4327 } 4328 // reverse direction means lock in the snap mode 4329 if (ay > MAX_SLOPE_FOR_DIAG * ax && 4330 (mSnapPositive 4331 ? deltaY < -mMinLockSnapReverseDistance 4332 : deltaY > mMinLockSnapReverseDistance)) { 4333 mSnapScrollMode |= SNAP_LOCK; 4334 } 4335 } 4336 } 4337 if (mSnapScrollMode != SNAP_NONE) { 4338 if ((mSnapScrollMode & SNAP_X) == SNAP_X) { 4339 deltaY = 0; 4340 } else { 4341 deltaX = 0; 4342 } 4343 } 4344 if ((deltaX | deltaY) != 0) { 4345 scrollBy(deltaX, deltaY); 4346 if (deltaX != 0) { 4347 mLastTouchX = x; 4348 } 4349 if (deltaY != 0) { 4350 mLastTouchY = y; 4351 } 4352 mHeldMotionless = MOTIONLESS_FALSE; 4353 } else { 4354 // keep the scrollbar on the screen even there is no 4355 // scroll 4356 keepScrollBarsVisible = true; 4357 } 4358 mLastTouchTime = eventTime; 4359 mUserScroll = true; 4360 } 4361 4362 if (!getSettings().getBuiltInZoomControls()) { 4363 boolean showPlusMinus = mMinZoomScale < mMaxZoomScale; 4364 if (mZoomControls != null && showPlusMinus) { 4365 if (mZoomControls.getVisibility() == View.VISIBLE) { 4366 mPrivateHandler.removeCallbacks(mZoomControlRunnable); 4367 } else { 4368 mZoomControls.show(showPlusMinus, false); 4369 } 4370 mPrivateHandler.postDelayed(mZoomControlRunnable, 4371 ZOOM_CONTROLS_TIMEOUT); 4372 } 4373 } 4374 4375 if (mDragTrackerHandler != null) { 4376 mDragTrackerHandler.dragTo(x, y); 4377 } 4378 4379 if (keepScrollBarsVisible) { 4380 if (mHeldMotionless != MOTIONLESS_TRUE) { 4381 mHeldMotionless = MOTIONLESS_TRUE; 4382 invalidate(); 4383 } 4384 // keep the scrollbar on the screen even there is no scroll 4385 awakenScrollBars(ViewConfiguration.getScrollDefaultDelay(), 4386 false); 4387 // return false to indicate that we can't pan out of the 4388 // view space 4389 return !done; 4390 } 4391 break; 4392 } 4393 case MotionEvent.ACTION_UP: { 4394 if (mDragTrackerHandler != null) { 4395 mDragTrackerHandler.stopDrag(); 4396 mDragTrackerHandler = null; 4397 } 4398 mLastTouchUpTime = eventTime; 4399 switch (mTouchMode) { 4400 case TOUCH_DOUBLE_TAP_MODE: // double tap 4401 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 4402 mTouchMode = TOUCH_DONE_MODE; 4403 if (mPreventDoubleTap) { 4404 WebViewCore.TouchEventData ted 4405 = new WebViewCore.TouchEventData(); 4406 ted.mAction = WebViewCore.ACTION_DOUBLETAP; 4407 ted.mX = viewToContentX((int) x + mScrollX); 4408 ted.mY = viewToContentY((int) y + mScrollY); 4409 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 4410 } else if (mFullScreenHolder == null) { 4411 doDoubleTap(); 4412 } 4413 break; 4414 case TOUCH_SELECT_MODE: 4415 commitCopy(); 4416 mTouchSelection = false; 4417 break; 4418 case TOUCH_INIT_MODE: // tap 4419 case TOUCH_SHORTPRESS_START_MODE: 4420 case TOUCH_SHORTPRESS_MODE: 4421 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 4422 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 4423 if ((deltaX * deltaX + deltaY * deltaY) > mTouchSlopSquare) { 4424 Log.w(LOGTAG, "Miss a drag as we are waiting for" + 4425 " WebCore's response for touch down."); 4426 if (mFullScreenHolder == null 4427 && (computeHorizontalScrollExtent() < computeHorizontalScrollRange() 4428 || computeVerticalScrollExtent() < computeVerticalScrollRange())) { 4429 // we will not rewrite drag code here, but we 4430 // will try fling if it applies. 4431 WebViewCore.pauseUpdate(mWebViewCore); 4432 // fall through to TOUCH_DRAG_MODE 4433 } else { 4434 break; 4435 } 4436 } else { 4437 if (mPreventDrag == PREVENT_DRAG_MAYBE_YES) { 4438 // if mPreventDrag is not confirmed, treat it as 4439 // no so that it won't block tap or double tap. 4440 mPreventDrag = PREVENT_DRAG_NO; 4441 mPreventLongPress = false; 4442 mPreventDoubleTap = false; 4443 } 4444 if (mPreventDrag == PREVENT_DRAG_NO) { 4445 if (mTouchMode == TOUCH_INIT_MODE) { 4446 mPrivateHandler.sendMessageDelayed( 4447 mPrivateHandler.obtainMessage( 4448 RELEASE_SINGLE_TAP), 4449 ViewConfiguration.getDoubleTapTimeout()); 4450 } else { 4451 mTouchMode = TOUCH_DONE_MODE; 4452 doShortPress(); 4453 } 4454 } 4455 break; 4456 } 4457 case TOUCH_DRAG_MODE: 4458 mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS); 4459 mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS); 4460 mHeldMotionless = MOTIONLESS_TRUE; 4461 // redraw in high-quality, as we're done dragging 4462 invalidate(); 4463 // if the user waits a while w/o moving before the 4464 // up, we don't want to do a fling 4465 if (eventTime - mLastTouchTime <= MIN_FLING_TIME) { 4466 mVelocityTracker.addMovement(ev); 4467 doFling(); 4468 break; 4469 } 4470 mLastVelocity = 0; 4471 WebViewCore.resumeUpdate(mWebViewCore); 4472 break; 4473 case TOUCH_DRAG_START_MODE: 4474 case TOUCH_DONE_MODE: 4475 // do nothing 4476 break; 4477 } 4478 // we also use mVelocityTracker == null to tell us that we are 4479 // not "moving around", so we can take the slower/prettier 4480 // mode in the drawing code 4481 if (mVelocityTracker != null) { 4482 mVelocityTracker.recycle(); 4483 mVelocityTracker = null; 4484 } 4485 break; 4486 } 4487 case MotionEvent.ACTION_CANCEL: { 4488 if (mDragTrackerHandler != null) { 4489 mDragTrackerHandler.stopDrag(); 4490 mDragTrackerHandler = null; 4491 } 4492 // we also use mVelocityTracker == null to tell us that we are 4493 // not "moving around", so we can take the slower/prettier 4494 // mode in the drawing code 4495 if (mVelocityTracker != null) { 4496 mVelocityTracker.recycle(); 4497 mVelocityTracker = null; 4498 } 4499 if (mTouchMode == TOUCH_DRAG_MODE) { 4500 WebViewCore.resumeUpdate(mWebViewCore); 4501 } 4502 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 4503 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 4504 mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS); 4505 mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS); 4506 mHeldMotionless = MOTIONLESS_TRUE; 4507 mTouchMode = TOUCH_DONE_MODE; 4508 nativeHideCursor(); 4509 break; 4510 } 4511 } 4512 return true; 4513 } 4514 4515 private long mTrackballFirstTime = 0; 4516 private long mTrackballLastTime = 0; 4517 private float mTrackballRemainsX = 0.0f; 4518 private float mTrackballRemainsY = 0.0f; 4519 private int mTrackballXMove = 0; 4520 private int mTrackballYMove = 0; 4521 private boolean mExtendSelection = false; 4522 private boolean mTouchSelection = false; 4523 private static final int TRACKBALL_KEY_TIMEOUT = 1000; 4524 private static final int TRACKBALL_TIMEOUT = 200; 4525 private static final int TRACKBALL_WAIT = 100; 4526 private static final int TRACKBALL_SCALE = 400; 4527 private static final int TRACKBALL_SCROLL_COUNT = 5; 4528 private static final int TRACKBALL_MOVE_COUNT = 10; 4529 private static final int TRACKBALL_MULTIPLIER = 3; 4530 private static final int SELECT_CURSOR_OFFSET = 16; 4531 private int mSelectX = 0; 4532 private int mSelectY = 0; 4533 private boolean mFocusSizeChanged = false; 4534 private boolean mShiftIsPressed = false; 4535 private boolean mTrackballDown = false; 4536 private long mTrackballUpTime = 0; 4537 private long mLastCursorTime = 0; 4538 private Rect mLastCursorBounds; 4539 4540 // Set by default; BrowserActivity clears to interpret trackball data 4541 // directly for movement. Currently, the framework only passes 4542 // arrow key events, not trackball events, from one child to the next 4543 private boolean mMapTrackballToArrowKeys = true; 4544 4545 public void setMapTrackballToArrowKeys(boolean setMap) { 4546 mMapTrackballToArrowKeys = setMap; 4547 } 4548 4549 void resetTrackballTime() { 4550 mTrackballLastTime = 0; 4551 } 4552 4553 @Override 4554 public boolean onTrackballEvent(MotionEvent ev) { 4555 long time = ev.getEventTime(); 4556 if ((ev.getMetaState() & KeyEvent.META_ALT_ON) != 0) { 4557 if (ev.getY() > 0) pageDown(true); 4558 if (ev.getY() < 0) pageUp(true); 4559 return true; 4560 } 4561 if (ev.getAction() == MotionEvent.ACTION_DOWN) { 4562 if (mShiftIsPressed) { 4563 return true; // discard press if copy in progress 4564 } 4565 mTrackballDown = true; 4566 if (mNativeClass == 0) { 4567 return false; 4568 } 4569 nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true); 4570 if (time - mLastCursorTime <= TRACKBALL_TIMEOUT 4571 && !mLastCursorBounds.equals(nativeGetCursorRingBounds())) { 4572 nativeSelectBestAt(mLastCursorBounds); 4573 } 4574 if (DebugFlags.WEB_VIEW) { 4575 Log.v(LOGTAG, "onTrackballEvent down ev=" + ev 4576 + " time=" + time 4577 + " mLastCursorTime=" + mLastCursorTime); 4578 } 4579 if (isInTouchMode()) requestFocusFromTouch(); 4580 return false; // let common code in onKeyDown at it 4581 } 4582 if (ev.getAction() == MotionEvent.ACTION_UP) { 4583 // LONG_PRESS_CENTER is set in common onKeyDown 4584 mPrivateHandler.removeMessages(LONG_PRESS_CENTER); 4585 mTrackballDown = false; 4586 mTrackballUpTime = time; 4587 if (mShiftIsPressed) { 4588 if (mExtendSelection) { 4589 commitCopy(); 4590 } else { 4591 mExtendSelection = true; 4592 invalidate(); // draw the i-beam instead of the arrow 4593 } 4594 return true; // discard press if copy in progress 4595 } 4596 if (DebugFlags.WEB_VIEW) { 4597 Log.v(LOGTAG, "onTrackballEvent up ev=" + ev 4598 + " time=" + time 4599 ); 4600 } 4601 return false; // let common code in onKeyUp at it 4602 } 4603 if (mMapTrackballToArrowKeys && mShiftIsPressed == false) { 4604 if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent gmail quit"); 4605 return false; 4606 } 4607 if (mTrackballDown) { 4608 if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent down quit"); 4609 return true; // discard move if trackball is down 4610 } 4611 if (time - mTrackballUpTime < TRACKBALL_TIMEOUT) { 4612 if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent up timeout quit"); 4613 return true; 4614 } 4615 // TODO: alternatively we can do panning as touch does 4616 switchOutDrawHistory(); 4617 if (time - mTrackballLastTime > TRACKBALL_TIMEOUT) { 4618 if (DebugFlags.WEB_VIEW) { 4619 Log.v(LOGTAG, "onTrackballEvent time=" 4620 + time + " last=" + mTrackballLastTime); 4621 } 4622 mTrackballFirstTime = time; 4623 mTrackballXMove = mTrackballYMove = 0; 4624 } 4625 mTrackballLastTime = time; 4626 if (DebugFlags.WEB_VIEW) { 4627 Log.v(LOGTAG, "onTrackballEvent ev=" + ev + " time=" + time); 4628 } 4629 mTrackballRemainsX += ev.getX(); 4630 mTrackballRemainsY += ev.getY(); 4631 doTrackball(time); 4632 return true; 4633 } 4634 4635 void moveSelection(float xRate, float yRate) { 4636 if (mNativeClass == 0) 4637 return; 4638 int width = getViewWidth(); 4639 int height = getViewHeight(); 4640 mSelectX += xRate; 4641 mSelectY += yRate; 4642 int maxX = width + mScrollX; 4643 int maxY = height + mScrollY; 4644 mSelectX = Math.min(maxX, Math.max(mScrollX - SELECT_CURSOR_OFFSET 4645 , mSelectX)); 4646 mSelectY = Math.min(maxY, Math.max(mScrollY - SELECT_CURSOR_OFFSET 4647 , mSelectY)); 4648 if (DebugFlags.WEB_VIEW) { 4649 Log.v(LOGTAG, "moveSelection" 4650 + " mSelectX=" + mSelectX 4651 + " mSelectY=" + mSelectY 4652 + " mScrollX=" + mScrollX 4653 + " mScrollY=" + mScrollY 4654 + " xRate=" + xRate 4655 + " yRate=" + yRate 4656 ); 4657 } 4658 nativeMoveSelection(viewToContentX(mSelectX), 4659 viewToContentY(mSelectY), mExtendSelection); 4660 int scrollX = mSelectX < mScrollX ? -SELECT_CURSOR_OFFSET 4661 : mSelectX > maxX - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET 4662 : 0; 4663 int scrollY = mSelectY < mScrollY ? -SELECT_CURSOR_OFFSET 4664 : mSelectY > maxY - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET 4665 : 0; 4666 pinScrollBy(scrollX, scrollY, true, 0); 4667 Rect select = new Rect(mSelectX, mSelectY, mSelectX + 1, mSelectY + 1); 4668 requestRectangleOnScreen(select); 4669 invalidate(); 4670 } 4671 4672 private int scaleTrackballX(float xRate, int width) { 4673 int xMove = (int) (xRate / TRACKBALL_SCALE * width); 4674 int nextXMove = xMove; 4675 if (xMove > 0) { 4676 if (xMove > mTrackballXMove) { 4677 xMove -= mTrackballXMove; 4678 } 4679 } else if (xMove < mTrackballXMove) { 4680 xMove -= mTrackballXMove; 4681 } 4682 mTrackballXMove = nextXMove; 4683 return xMove; 4684 } 4685 4686 private int scaleTrackballY(float yRate, int height) { 4687 int yMove = (int) (yRate / TRACKBALL_SCALE * height); 4688 int nextYMove = yMove; 4689 if (yMove > 0) { 4690 if (yMove > mTrackballYMove) { 4691 yMove -= mTrackballYMove; 4692 } 4693 } else if (yMove < mTrackballYMove) { 4694 yMove -= mTrackballYMove; 4695 } 4696 mTrackballYMove = nextYMove; 4697 return yMove; 4698 } 4699 4700 private int keyCodeToSoundsEffect(int keyCode) { 4701 switch(keyCode) { 4702 case KeyEvent.KEYCODE_DPAD_UP: 4703 return SoundEffectConstants.NAVIGATION_UP; 4704 case KeyEvent.KEYCODE_DPAD_RIGHT: 4705 return SoundEffectConstants.NAVIGATION_RIGHT; 4706 case KeyEvent.KEYCODE_DPAD_DOWN: 4707 return SoundEffectConstants.NAVIGATION_DOWN; 4708 case KeyEvent.KEYCODE_DPAD_LEFT: 4709 return SoundEffectConstants.NAVIGATION_LEFT; 4710 } 4711 throw new IllegalArgumentException("keyCode must be one of " + 4712 "{KEYCODE_DPAD_UP, KEYCODE_DPAD_RIGHT, KEYCODE_DPAD_DOWN, " + 4713 "KEYCODE_DPAD_LEFT}."); 4714 } 4715 4716 private void doTrackball(long time) { 4717 int elapsed = (int) (mTrackballLastTime - mTrackballFirstTime); 4718 if (elapsed == 0) { 4719 elapsed = TRACKBALL_TIMEOUT; 4720 } 4721 float xRate = mTrackballRemainsX * 1000 / elapsed; 4722 float yRate = mTrackballRemainsY * 1000 / elapsed; 4723 int viewWidth = getViewWidth(); 4724 int viewHeight = getViewHeight(); 4725 if (mShiftIsPressed) { 4726 moveSelection(scaleTrackballX(xRate, viewWidth), 4727 scaleTrackballY(yRate, viewHeight)); 4728 mTrackballRemainsX = mTrackballRemainsY = 0; 4729 return; 4730 } 4731 float ax = Math.abs(xRate); 4732 float ay = Math.abs(yRate); 4733 float maxA = Math.max(ax, ay); 4734 if (DebugFlags.WEB_VIEW) { 4735 Log.v(LOGTAG, "doTrackball elapsed=" + elapsed 4736 + " xRate=" + xRate 4737 + " yRate=" + yRate 4738 + " mTrackballRemainsX=" + mTrackballRemainsX 4739 + " mTrackballRemainsY=" + mTrackballRemainsY); 4740 } 4741 int width = mContentWidth - viewWidth; 4742 int height = mContentHeight - viewHeight; 4743 if (width < 0) width = 0; 4744 if (height < 0) height = 0; 4745 ax = Math.abs(mTrackballRemainsX * TRACKBALL_MULTIPLIER); 4746 ay = Math.abs(mTrackballRemainsY * TRACKBALL_MULTIPLIER); 4747 maxA = Math.max(ax, ay); 4748 int count = Math.max(0, (int) maxA); 4749 int oldScrollX = mScrollX; 4750 int oldScrollY = mScrollY; 4751 if (count > 0) { 4752 int selectKeyCode = ax < ay ? mTrackballRemainsY < 0 ? 4753 KeyEvent.KEYCODE_DPAD_UP : KeyEvent.KEYCODE_DPAD_DOWN : 4754 mTrackballRemainsX < 0 ? KeyEvent.KEYCODE_DPAD_LEFT : 4755 KeyEvent.KEYCODE_DPAD_RIGHT; 4756 count = Math.min(count, TRACKBALL_MOVE_COUNT); 4757 if (DebugFlags.WEB_VIEW) { 4758 Log.v(LOGTAG, "doTrackball keyCode=" + selectKeyCode 4759 + " count=" + count 4760 + " mTrackballRemainsX=" + mTrackballRemainsX 4761 + " mTrackballRemainsY=" + mTrackballRemainsY); 4762 } 4763 if (navHandledKey(selectKeyCode, count, false, time, false)) { 4764 playSoundEffect(keyCodeToSoundsEffect(selectKeyCode)); 4765 } 4766 mTrackballRemainsX = mTrackballRemainsY = 0; 4767 } 4768 if (count >= TRACKBALL_SCROLL_COUNT) { 4769 int xMove = scaleTrackballX(xRate, width); 4770 int yMove = scaleTrackballY(yRate, height); 4771 if (DebugFlags.WEB_VIEW) { 4772 Log.v(LOGTAG, "doTrackball pinScrollBy" 4773 + " count=" + count 4774 + " xMove=" + xMove + " yMove=" + yMove 4775 + " mScrollX-oldScrollX=" + (mScrollX-oldScrollX) 4776 + " mScrollY-oldScrollY=" + (mScrollY-oldScrollY) 4777 ); 4778 } 4779 if (Math.abs(mScrollX - oldScrollX) > Math.abs(xMove)) { 4780 xMove = 0; 4781 } 4782 if (Math.abs(mScrollY - oldScrollY) > Math.abs(yMove)) { 4783 yMove = 0; 4784 } 4785 if (xMove != 0 || yMove != 0) { 4786 pinScrollBy(xMove, yMove, true, 0); 4787 } 4788 mUserScroll = true; 4789 } 4790 } 4791 4792 private int computeMaxScrollY() { 4793 int maxContentH = computeVerticalScrollRange() + getTitleHeight(); 4794 return Math.max(maxContentH - getViewHeightWithTitle(), getTitleHeight()); 4795 } 4796 4797 public void flingScroll(int vx, int vy) { 4798 int maxX = Math.max(computeHorizontalScrollRange() - getViewWidth(), 0); 4799 int maxY = computeMaxScrollY(); 4800 4801 mScroller.fling(mScrollX, mScrollY, vx, vy, 0, maxX, 0, maxY); 4802 invalidate(); 4803 } 4804 4805 private void doFling() { 4806 if (mVelocityTracker == null) { 4807 return; 4808 } 4809 int maxX = Math.max(computeHorizontalScrollRange() - getViewWidth(), 0); 4810 int maxY = computeMaxScrollY(); 4811 4812 mVelocityTracker.computeCurrentVelocity(1000, mMaximumFling); 4813 int vx = (int) mVelocityTracker.getXVelocity(); 4814 int vy = (int) mVelocityTracker.getYVelocity(); 4815 4816 if (mSnapScrollMode != SNAP_NONE) { 4817 if ((mSnapScrollMode & SNAP_X) == SNAP_X) { 4818 vy = 0; 4819 } else { 4820 vx = 0; 4821 } 4822 } 4823 4824 if (true /* EMG release: make our fling more like Maps' */) { 4825 // maps cuts their velocity in half 4826 vx = vx * 3 / 4; 4827 vy = vy * 3 / 4; 4828 } 4829 if ((maxX == 0 && vy == 0) || (maxY == 0 && vx == 0)) { 4830 WebViewCore.resumeUpdate(mWebViewCore); 4831 return; 4832 } 4833 float currentVelocity = mScroller.getCurrVelocity(); 4834 if (mLastVelocity > 0 && currentVelocity > 0) { 4835 float deltaR = (float) (Math.abs(Math.atan2(mLastVelY, mLastVelX) 4836 - Math.atan2(vy, vx))); 4837 final float circle = (float) (Math.PI) * 2.0f; 4838 if (deltaR > circle * 0.9f || deltaR < circle * 0.1f) { 4839 vx += currentVelocity * mLastVelX / mLastVelocity; 4840 vy += currentVelocity * mLastVelY / mLastVelocity; 4841 if (DebugFlags.WEB_VIEW) { 4842 Log.v(LOGTAG, "doFling vx= " + vx + " vy=" + vy); 4843 } 4844 } else if (DebugFlags.WEB_VIEW) { 4845 Log.v(LOGTAG, "doFling missed " + deltaR / circle); 4846 } 4847 } else if (DebugFlags.WEB_VIEW) { 4848 Log.v(LOGTAG, "doFling start last=" + mLastVelocity 4849 + " current=" + currentVelocity 4850 + " vx=" + vx + " vy=" + vy 4851 + " maxX=" + maxX + " maxY=" + maxY 4852 + " mScrollX=" + mScrollX + " mScrollY=" + mScrollY); 4853 } 4854 mLastVelX = vx; 4855 mLastVelY = vy; 4856 mLastVelocity = (float) Math.hypot(vx, vy); 4857 4858 mScroller.fling(mScrollX, mScrollY, -vx, -vy, 0, maxX, 0, maxY); 4859 // TODO: duration is calculated based on velocity, if the range is 4860 // small, the animation will stop before duration is up. We may 4861 // want to calculate how long the animation is going to run to precisely 4862 // resume the webcore update. 4863 final int time = mScroller.getDuration(); 4864 mPrivateHandler.sendEmptyMessageDelayed(RESUME_WEBCORE_UPDATE, time); 4865 awakenScrollBars(time); 4866 invalidate(); 4867 } 4868 4869 private boolean zoomWithPreview(float scale) { 4870 float oldScale = mActualScale; 4871 mInitialScrollX = mScrollX; 4872 mInitialScrollY = mScrollY; 4873 4874 // snap to DEFAULT_SCALE if it is close 4875 if (scale > (mDefaultScale - 0.05) && scale < (mDefaultScale + 0.05)) { 4876 scale = mDefaultScale; 4877 } 4878 4879 setNewZoomScale(scale, false); 4880 4881 if (oldScale != mActualScale) { 4882 // use mZoomPickerScale to see zoom preview first 4883 mZoomStart = SystemClock.uptimeMillis(); 4884 mInvInitialZoomScale = 1.0f / oldScale; 4885 mInvFinalZoomScale = 1.0f / mActualScale; 4886 mZoomScale = mActualScale; 4887 if (!mInZoomOverview) { 4888 mLastScale = scale; 4889 } 4890 invalidate(); 4891 return true; 4892 } else { 4893 return false; 4894 } 4895 } 4896 4897 /** 4898 * Returns a view containing zoom controls i.e. +/- buttons. The caller is 4899 * in charge of installing this view to the view hierarchy. This view will 4900 * become visible when the user starts scrolling via touch and fade away if 4901 * the user does not interact with it. 4902 * <p/> 4903 * API version 3 introduces a built-in zoom mechanism that is shown 4904 * automatically by the MapView. This is the preferred approach for 4905 * showing the zoom UI. 4906 * 4907 * @deprecated The built-in zoom mechanism is preferred, see 4908 * {@link WebSettings#setBuiltInZoomControls(boolean)}. 4909 */ 4910 @Deprecated 4911 public View getZoomControls() { 4912 if (!getSettings().supportZoom()) { 4913 Log.w(LOGTAG, "This WebView doesn't support zoom."); 4914 return null; 4915 } 4916 if (mZoomControls == null) { 4917 mZoomControls = createZoomControls(); 4918 4919 /* 4920 * need to be set to VISIBLE first so that getMeasuredHeight() in 4921 * {@link #onSizeChanged()} can return the measured value for proper 4922 * layout. 4923 */ 4924 mZoomControls.setVisibility(View.VISIBLE); 4925 mZoomControlRunnable = new Runnable() { 4926 public void run() { 4927 4928 /* Don't dismiss the controls if the user has 4929 * focus on them. Wait and check again later. 4930 */ 4931 if (!mZoomControls.hasFocus()) { 4932 mZoomControls.hide(); 4933 } else { 4934 mPrivateHandler.removeCallbacks(mZoomControlRunnable); 4935 mPrivateHandler.postDelayed(mZoomControlRunnable, 4936 ZOOM_CONTROLS_TIMEOUT); 4937 } 4938 } 4939 }; 4940 } 4941 return mZoomControls; 4942 } 4943 4944 private ExtendedZoomControls createZoomControls() { 4945 ExtendedZoomControls zoomControls = new ExtendedZoomControls(mContext 4946 , null); 4947 zoomControls.setOnZoomInClickListener(new OnClickListener() { 4948 public void onClick(View v) { 4949 // reset time out 4950 mPrivateHandler.removeCallbacks(mZoomControlRunnable); 4951 mPrivateHandler.postDelayed(mZoomControlRunnable, 4952 ZOOM_CONTROLS_TIMEOUT); 4953 zoomIn(); 4954 } 4955 }); 4956 zoomControls.setOnZoomOutClickListener(new OnClickListener() { 4957 public void onClick(View v) { 4958 // reset time out 4959 mPrivateHandler.removeCallbacks(mZoomControlRunnable); 4960 mPrivateHandler.postDelayed(mZoomControlRunnable, 4961 ZOOM_CONTROLS_TIMEOUT); 4962 zoomOut(); 4963 } 4964 }); 4965 return zoomControls; 4966 } 4967 4968 /** 4969 * Gets the {@link ZoomButtonsController} which can be used to add 4970 * additional buttons to the zoom controls window. 4971 * 4972 * @return The instance of {@link ZoomButtonsController} used by this class, 4973 * or null if it is unavailable. 4974 * @hide 4975 */ 4976 public ZoomButtonsController getZoomButtonsController() { 4977 return mZoomButtonsController; 4978 } 4979 4980 /** 4981 * Perform zoom in in the webview 4982 * @return TRUE if zoom in succeeds. FALSE if no zoom changes. 4983 */ 4984 public boolean zoomIn() { 4985 // TODO: alternatively we can disallow this during draw history mode 4986 switchOutDrawHistory(); 4987 // Center zooming to the center of the screen. 4988 if (mInZoomOverview) { 4989 // if in overview mode, bring it back to normal mode 4990 mLastTouchX = getViewWidth() * .5f; 4991 mLastTouchY = getViewHeight() * .5f; 4992 doDoubleTap(); 4993 return true; 4994 } else { 4995 mZoomCenterX = getViewWidth() * .5f; 4996 mZoomCenterY = getViewHeight() * .5f; 4997 return zoomWithPreview(mActualScale * 1.25f); 4998 } 4999 } 5000 5001 /** 5002 * Perform zoom out in the webview 5003 * @return TRUE if zoom out succeeds. FALSE if no zoom changes. 5004 */ 5005 public boolean zoomOut() { 5006 // TODO: alternatively we can disallow this during draw history mode 5007 switchOutDrawHistory(); 5008 float scale = mActualScale * 0.8f; 5009 if (scale < (mMinZoomScale + 0.1f) 5010 && mWebViewCore.getSettings().getUseWideViewPort() 5011 && mZoomOverviewWidth > Math.ceil(getViewWidth() 5012 * mInvActualScale)) { 5013 // when zoom out to min scale, switch to overview mode 5014 doDoubleTap(); 5015 return true; 5016 } else { 5017 // Center zooming to the center of the screen. 5018 mZoomCenterX = getViewWidth() * .5f; 5019 mZoomCenterY = getViewHeight() * .5f; 5020 return zoomWithPreview(scale); 5021 } 5022 } 5023 5024 private void updateSelection() { 5025 if (mNativeClass == 0) { 5026 return; 5027 } 5028 // mLastTouchX and mLastTouchY are the point in the current viewport 5029 int contentX = viewToContentX((int) mLastTouchX + mScrollX); 5030 int contentY = viewToContentY((int) mLastTouchY + mScrollY); 5031 Rect rect = new Rect(contentX - mNavSlop, contentY - mNavSlop, 5032 contentX + mNavSlop, contentY + mNavSlop); 5033 nativeSelectBestAt(rect); 5034 } 5035 5036 /** 5037 * Scroll the focused text field/area to match the WebTextView 5038 * @param xPercent New x position of the WebTextView from 0 to 1. 5039 * @param y New y position of the WebTextView in view coordinates 5040 */ 5041 /*package*/ void scrollFocusedTextInput(float xPercent, int y) { 5042 if (!inEditingMode() || mWebViewCore == null) { 5043 return; 5044 } 5045 mWebViewCore.sendMessage(EventHub.SCROLL_TEXT_INPUT, 5046 // Since this position is relative to the top of the text input 5047 // field, we do not need to take the title bar's height into 5048 // consideration. 5049 viewToContentDimension(y), 5050 new Float(xPercent)); 5051 } 5052 5053 /** 5054 * Set our starting point and time for a drag from the WebTextView. 5055 */ 5056 /*package*/ void initiateTextFieldDrag(float x, float y, long eventTime) { 5057 if (!inEditingMode()) { 5058 return; 5059 } 5060 mLastTouchX = x + (float) (mWebTextView.getLeft() - mScrollX); 5061 mLastTouchY = y + (float) (mWebTextView.getTop() - mScrollY); 5062 mLastTouchTime = eventTime; 5063 if (!mScroller.isFinished()) { 5064 abortAnimation(); 5065 mPrivateHandler.removeMessages(RESUME_WEBCORE_UPDATE); 5066 } 5067 mSnapScrollMode = SNAP_NONE; 5068 mVelocityTracker = VelocityTracker.obtain(); 5069 mTouchMode = TOUCH_DRAG_START_MODE; 5070 } 5071 5072 /** 5073 * Given a motion event from the WebTextView, set its location to our 5074 * coordinates, and handle the event. 5075 */ 5076 /*package*/ boolean textFieldDrag(MotionEvent event) { 5077 if (!inEditingMode()) { 5078 return false; 5079 } 5080 mDragFromTextInput = true; 5081 event.offsetLocation((float) (mWebTextView.getLeft() - mScrollX), 5082 (float) (mWebTextView.getTop() - mScrollY)); 5083 boolean result = onTouchEvent(event); 5084 mDragFromTextInput = false; 5085 return result; 5086 } 5087 5088 /** 5089 * Due a touch up from a WebTextView. This will be handled by webkit to 5090 * change the selection. 5091 * @param event MotionEvent in the WebTextView's coordinates. 5092 */ 5093 /*package*/ void touchUpOnTextField(MotionEvent event) { 5094 if (!inEditingMode()) { 5095 return; 5096 } 5097 int x = viewToContentX((int) event.getX() + mWebTextView.getLeft()); 5098 int y = viewToContentY((int) event.getY() + mWebTextView.getTop()); 5099 nativeMotionUp(x, y, mNavSlop); 5100 } 5101 5102 /** 5103 * Called when pressing the center key or trackball on a textfield. 5104 */ 5105 /*package*/ void centerKeyPressOnTextField() { 5106 mWebViewCore.sendMessage(EventHub.CLICK, nativeCursorFramePointer(), 5107 nativeCursorNodePointer()); 5108 } 5109 5110 private void doShortPress() { 5111 if (mNativeClass == 0) { 5112 return; 5113 } 5114 switchOutDrawHistory(); 5115 // mLastTouchX and mLastTouchY are the point in the current viewport 5116 int contentX = viewToContentX((int) mLastTouchX + mScrollX); 5117 int contentY = viewToContentY((int) mLastTouchY + mScrollY); 5118 if (nativePointInNavCache(contentX, contentY, mNavSlop)) { 5119 WebViewCore.MotionUpData motionUpData = new WebViewCore 5120 .MotionUpData(); 5121 motionUpData.mFrame = nativeCacheHitFramePointer(); 5122 motionUpData.mNode = nativeCacheHitNodePointer(); 5123 motionUpData.mBounds = nativeCacheHitNodeBounds(); 5124 motionUpData.mX = contentX; 5125 motionUpData.mY = contentY; 5126 mWebViewCore.sendMessageAtFrontOfQueue(EventHub.VALID_NODE_BOUNDS, 5127 motionUpData); 5128 } else { 5129 doMotionUp(contentX, contentY, false); 5130 } 5131 } 5132 5133 private void doMotionUp(int contentX, int contentY, boolean useNavCache) { 5134 if (nativeMotionUp(contentX, contentY, useNavCache ? mNavSlop : 0)) { 5135 if (mLogEvent) { 5136 Checkin.updateStats(mContext.getContentResolver(), 5137 Checkin.Stats.Tag.BROWSER_SNAP_CENTER, 1, 0.0); 5138 } 5139 } 5140 if (nativeHasCursorNode() && !nativeCursorIsTextInput()) { 5141 playSoundEffect(SoundEffectConstants.CLICK); 5142 } 5143 } 5144 5145 private void doDoubleTap() { 5146 if (mWebViewCore.getSettings().getUseWideViewPort() == false) { 5147 return; 5148 } 5149 mZoomCenterX = mLastTouchX; 5150 mZoomCenterY = mLastTouchY; 5151 mInZoomOverview = !mInZoomOverview; 5152 // remove the zoom control after double tap 5153 WebSettings settings = getSettings(); 5154 if (settings.getBuiltInZoomControls()) { 5155 if (mZoomButtonsController.isVisible()) { 5156 mZoomButtonsController.setVisible(false); 5157 } 5158 } else { 5159 if (mZoomControlRunnable != null) { 5160 mPrivateHandler.removeCallbacks(mZoomControlRunnable); 5161 } 5162 if (mZoomControls != null) { 5163 mZoomControls.hide(); 5164 } 5165 } 5166 settings.setDoubleTapToastCount(0); 5167 if (mInZoomOverview) { 5168 float newScale = (float) getViewWidth() / mZoomOverviewWidth; 5169 if (Math.abs(mActualScale - newScale) < 0.01f) { 5170 // reset mInZoomOverview to false if scale doesn't change 5171 mInZoomOverview = false; 5172 } else { 5173 // Force the titlebar fully reveal in overview mode 5174 if (mScrollY < getTitleHeight()) mScrollY = 0; 5175 zoomWithPreview(newScale); 5176 } 5177 } else { 5178 // mLastTouchX and mLastTouchY are the point in the current viewport 5179 int contentX = viewToContentX((int) mLastTouchX + mScrollX); 5180 int contentY = viewToContentY((int) mLastTouchY + mScrollY); 5181 int left = nativeGetBlockLeftEdge(contentX, contentY, mActualScale); 5182 if (left != NO_LEFTEDGE) { 5183 // add a 5pt padding to the left edge. Re-calculate the zoom 5184 // center so that the new scroll x will be on the left edge. 5185 mZoomCenterX = left < 5 ? 0 : (left - 5) * mLastScale 5186 * mActualScale / (mLastScale - mActualScale); 5187 } 5188 zoomWithPreview(mLastScale); 5189 } 5190 } 5191 5192 // Called by JNI to handle a touch on a node representing an email address, 5193 // address, or phone number 5194 private void overrideLoading(String url) { 5195 mCallbackProxy.uiOverrideUrlLoading(url); 5196 } 5197 5198 @Override 5199 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 5200 boolean result = false; 5201 if (inEditingMode()) { 5202 result = mWebTextView.requestFocus(direction, 5203 previouslyFocusedRect); 5204 } else { 5205 result = super.requestFocus(direction, previouslyFocusedRect); 5206 if (mWebViewCore.getSettings().getNeedInitialFocus()) { 5207 // For cases such as GMail, where we gain focus from a direction, 5208 // we want to move to the first available link. 5209 // FIXME: If there are no visible links, we may not want to 5210 int fakeKeyDirection = 0; 5211 switch(direction) { 5212 case View.FOCUS_UP: 5213 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_UP; 5214 break; 5215 case View.FOCUS_DOWN: 5216 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_DOWN; 5217 break; 5218 case View.FOCUS_LEFT: 5219 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_LEFT; 5220 break; 5221 case View.FOCUS_RIGHT: 5222 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_RIGHT; 5223 break; 5224 default: 5225 return result; 5226 } 5227 if (mNativeClass != 0 && !nativeHasCursorNode()) { 5228 navHandledKey(fakeKeyDirection, 1, true, 0, true); 5229 } 5230 } 5231 } 5232 return result; 5233 } 5234 5235 @Override 5236 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 5237 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 5238 5239 int heightMode = MeasureSpec.getMode(heightMeasureSpec); 5240 int heightSize = MeasureSpec.getSize(heightMeasureSpec); 5241 int widthMode = MeasureSpec.getMode(widthMeasureSpec); 5242 int widthSize = MeasureSpec.getSize(widthMeasureSpec); 5243 5244 int measuredHeight = heightSize; 5245 int measuredWidth = widthSize; 5246 5247 // Grab the content size from WebViewCore. 5248 int contentHeight = contentToViewDimension(mContentHeight); 5249 int contentWidth = contentToViewDimension(mContentWidth); 5250 5251// Log.d(LOGTAG, "------- measure " + heightMode); 5252 5253 if (heightMode != MeasureSpec.EXACTLY) { 5254 mHeightCanMeasure = true; 5255 measuredHeight = contentHeight; 5256 if (heightMode == MeasureSpec.AT_MOST) { 5257 // If we are larger than the AT_MOST height, then our height can 5258 // no longer be measured and we should scroll internally. 5259 if (measuredHeight > heightSize) { 5260 measuredHeight = heightSize; 5261 mHeightCanMeasure = false; 5262 } 5263 } 5264 } else { 5265 mHeightCanMeasure = false; 5266 } 5267 if (mNativeClass != 0) { 5268 nativeSetHeightCanMeasure(mHeightCanMeasure); 5269 } 5270 // For the width, always use the given size unless unspecified. 5271 if (widthMode == MeasureSpec.UNSPECIFIED) { 5272 mWidthCanMeasure = true; 5273 measuredWidth = contentWidth; 5274 } else { 5275 mWidthCanMeasure = false; 5276 } 5277 5278 synchronized (this) { 5279 setMeasuredDimension(measuredWidth, measuredHeight); 5280 } 5281 } 5282 5283 @Override 5284 public boolean requestChildRectangleOnScreen(View child, 5285 Rect rect, 5286 boolean immediate) { 5287 rect.offset(child.getLeft() - child.getScrollX(), 5288 child.getTop() - child.getScrollY()); 5289 5290 int height = getViewHeightWithTitle(); 5291 int screenTop = mScrollY; 5292 int screenBottom = screenTop + height; 5293 5294 int scrollYDelta = 0; 5295 5296 if (rect.bottom > screenBottom) { 5297 int oneThirdOfScreenHeight = height / 3; 5298 if (rect.height() > 2 * oneThirdOfScreenHeight) { 5299 // If the rectangle is too tall to fit in the bottom two thirds 5300 // of the screen, place it at the top. 5301 scrollYDelta = rect.top - screenTop; 5302 } else { 5303 // If the rectangle will still fit on screen, we want its 5304 // top to be in the top third of the screen. 5305 scrollYDelta = rect.top - (screenTop + oneThirdOfScreenHeight); 5306 } 5307 } else if (rect.top < screenTop) { 5308 scrollYDelta = rect.top - screenTop; 5309 } 5310 5311 int width = getWidth() - getVerticalScrollbarWidth(); 5312 int screenLeft = mScrollX; 5313 int screenRight = screenLeft + width; 5314 5315 int scrollXDelta = 0; 5316 5317 if (rect.right > screenRight && rect.left > screenLeft) { 5318 if (rect.width() > width) { 5319 scrollXDelta += (rect.left - screenLeft); 5320 } else { 5321 scrollXDelta += (rect.right - screenRight); 5322 } 5323 } else if (rect.left < screenLeft) { 5324 scrollXDelta -= (screenLeft - rect.left); 5325 } 5326 5327 if ((scrollYDelta | scrollXDelta) != 0) { 5328 return pinScrollBy(scrollXDelta, scrollYDelta, !immediate, 0); 5329 } 5330 5331 return false; 5332 } 5333 5334 /* package */ void replaceTextfieldText(int oldStart, int oldEnd, 5335 String replace, int newStart, int newEnd) { 5336 WebViewCore.ReplaceTextData arg = new WebViewCore.ReplaceTextData(); 5337 arg.mReplace = replace; 5338 arg.mNewStart = newStart; 5339 arg.mNewEnd = newEnd; 5340 mTextGeneration++; 5341 arg.mTextGeneration = mTextGeneration; 5342 mWebViewCore.sendMessage(EventHub.REPLACE_TEXT, oldStart, oldEnd, arg); 5343 } 5344 5345 /* package */ void passToJavaScript(String currentText, KeyEvent event) { 5346 WebViewCore.JSKeyData arg = new WebViewCore.JSKeyData(); 5347 arg.mEvent = event; 5348 arg.mCurrentText = currentText; 5349 // Increase our text generation number, and pass it to webcore thread 5350 mTextGeneration++; 5351 mWebViewCore.sendMessage(EventHub.PASS_TO_JS, mTextGeneration, 0, arg); 5352 // WebKit's document state is not saved until about to leave the page. 5353 // To make sure the host application, like Browser, has the up to date 5354 // document state when it goes to background, we force to save the 5355 // document state. 5356 mWebViewCore.removeMessages(EventHub.SAVE_DOCUMENT_STATE); 5357 mWebViewCore.sendMessageDelayed(EventHub.SAVE_DOCUMENT_STATE, 5358 cursorData(), 1000); 5359 } 5360 5361 /* package */ WebViewCore getWebViewCore() { 5362 return mWebViewCore; 5363 } 5364 5365 //------------------------------------------------------------------------- 5366 // Methods can be called from a separate thread, like WebViewCore 5367 // If it needs to call the View system, it has to send message. 5368 //------------------------------------------------------------------------- 5369 5370 /** 5371 * General handler to receive message coming from webkit thread 5372 */ 5373 class PrivateHandler extends Handler { 5374 @Override 5375 public void handleMessage(Message msg) { 5376 // exclude INVAL_RECT_MSG_ID since it is frequently output 5377 if (DebugFlags.WEB_VIEW && msg.what != INVAL_RECT_MSG_ID) { 5378 Log.v(LOGTAG, msg.what < REMEMBER_PASSWORD || msg.what 5379 > RETURN_LABEL ? Integer.toString(msg.what) 5380 : HandlerDebugString[msg.what - REMEMBER_PASSWORD]); 5381 } 5382 if (mWebViewCore == null) { 5383 // after WebView's destroy() is called, skip handling messages. 5384 return; 5385 } 5386 switch (msg.what) { 5387 case REMEMBER_PASSWORD: { 5388 mDatabase.setUsernamePassword( 5389 msg.getData().getString("host"), 5390 msg.getData().getString("username"), 5391 msg.getData().getString("password")); 5392 ((Message) msg.obj).sendToTarget(); 5393 break; 5394 } 5395 case NEVER_REMEMBER_PASSWORD: { 5396 mDatabase.setUsernamePassword( 5397 msg.getData().getString("host"), null, null); 5398 ((Message) msg.obj).sendToTarget(); 5399 break; 5400 } 5401 case SWITCH_TO_SHORTPRESS: { 5402 // if mPreventDrag is not confirmed, treat it as no so that 5403 // it won't block panning the page. 5404 if (mPreventDrag == PREVENT_DRAG_MAYBE_YES) { 5405 mPreventDrag = PREVENT_DRAG_NO; 5406 mPreventLongPress = false; 5407 mPreventDoubleTap = false; 5408 } 5409 if (mTouchMode == TOUCH_INIT_MODE) { 5410 mTouchMode = mFullScreenHolder == null 5411 ? TOUCH_SHORTPRESS_START_MODE 5412 : TOUCH_SHORTPRESS_MODE; 5413 updateSelection(); 5414 } else if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) { 5415 mTouchMode = TOUCH_DONE_MODE; 5416 } 5417 break; 5418 } 5419 case SWITCH_TO_LONGPRESS: { 5420 if (mPreventLongPress) { 5421 mTouchMode = TOUCH_DONE_MODE; 5422 WebViewCore.TouchEventData ted 5423 = new WebViewCore.TouchEventData(); 5424 ted.mAction = WebViewCore.ACTION_LONGPRESS; 5425 ted.mX = viewToContentX((int) mLastTouchX + mScrollX); 5426 ted.mY = viewToContentY((int) mLastTouchY + mScrollY); 5427 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 5428 } else if (mPreventDrag == PREVENT_DRAG_NO) { 5429 mTouchMode = TOUCH_DONE_MODE; 5430 if (mFullScreenHolder == null) { 5431 performLongClick(); 5432 rebuildWebTextView(); 5433 } 5434 } 5435 break; 5436 } 5437 case RELEASE_SINGLE_TAP: { 5438 if (mPreventDrag == PREVENT_DRAG_NO) { 5439 mTouchMode = TOUCH_DONE_MODE; 5440 doShortPress(); 5441 } 5442 break; 5443 } 5444 case SCROLL_BY_MSG_ID: 5445 setContentScrollBy(msg.arg1, msg.arg2, (Boolean) msg.obj); 5446 break; 5447 case SYNC_SCROLL_TO_MSG_ID: 5448 if (mUserScroll) { 5449 // if user has scrolled explicitly, don't sync the 5450 // scroll position any more 5451 mUserScroll = false; 5452 break; 5453 } 5454 // fall through 5455 case SCROLL_TO_MSG_ID: 5456 if (setContentScrollTo(msg.arg1, msg.arg2)) { 5457 // if we can't scroll to the exact position due to pin, 5458 // send a message to WebCore to re-scroll when we get a 5459 // new picture 5460 mUserScroll = false; 5461 mWebViewCore.sendMessage(EventHub.SYNC_SCROLL, 5462 msg.arg1, msg.arg2); 5463 } 5464 break; 5465 case SPAWN_SCROLL_TO_MSG_ID: 5466 spawnContentScrollTo(msg.arg1, msg.arg2); 5467 break; 5468 case NEW_PICTURE_MSG_ID: { 5469 WebSettings settings = mWebViewCore.getSettings(); 5470 // called for new content 5471 final int viewWidth = getViewWidth(); 5472 final WebViewCore.DrawData draw = 5473 (WebViewCore.DrawData) msg.obj; 5474 final Point viewSize = draw.mViewPoint; 5475 boolean useWideViewport = settings.getUseWideViewPort(); 5476 WebViewCore.RestoreState restoreState = draw.mRestoreState; 5477 boolean hasRestoreState = restoreState != null; 5478 if (hasRestoreState) { 5479 mInZoomOverview = false; 5480 mLastScale = mInitialScaleInPercent > 0 5481 ? mInitialScaleInPercent / 100.0f 5482 : restoreState.mTextWrapScale; 5483 if (restoreState.mMinScale == 0) { 5484 if (restoreState.mMobileSite) { 5485 if (draw.mMinPrefWidth > 5486 Math.max(0, draw.mViewPoint.x)) { 5487 mMinZoomScale = (float) viewWidth 5488 / draw.mMinPrefWidth; 5489 mMinZoomScaleFixed = false; 5490 } else { 5491 mMinZoomScale = restoreState.mDefaultScale; 5492 mMinZoomScaleFixed = true; 5493 } 5494 } else { 5495 mMinZoomScale = DEFAULT_MIN_ZOOM_SCALE; 5496 mMinZoomScaleFixed = false; 5497 } 5498 } else { 5499 mMinZoomScale = restoreState.mMinScale; 5500 mMinZoomScaleFixed = true; 5501 } 5502 if (restoreState.mMaxScale == 0) { 5503 mMaxZoomScale = DEFAULT_MAX_ZOOM_SCALE; 5504 } else { 5505 mMaxZoomScale = restoreState.mMaxScale; 5506 } 5507 setNewZoomScale(mLastScale, false); 5508 setContentScrollTo(restoreState.mScrollX, 5509 restoreState.mScrollY); 5510 if (useWideViewport 5511 && settings.getLoadWithOverviewMode()) { 5512 if (restoreState.mViewScale == 0 5513 || (restoreState.mMobileSite 5514 && mMinZoomScale < restoreState.mDefaultScale)) { 5515 mInZoomOverview = true; 5516 } 5517 } 5518 // As we are on a new page, remove the WebTextView. This 5519 // is necessary for page loads driven by webkit, and in 5520 // particular when the user was on a password field, so 5521 // the WebTextView was visible. 5522 clearTextEntry(); 5523 // update the zoom buttons as the scale can be changed 5524 if (getSettings().getBuiltInZoomControls()) { 5525 updateZoomButtonsEnabled(); 5526 } 5527 } 5528 // We update the layout (i.e. request a layout from the 5529 // view system) if the last view size that we sent to 5530 // WebCore matches the view size of the picture we just 5531 // received in the fixed dimension. 5532 final boolean updateLayout = viewSize.x == mLastWidthSent 5533 && viewSize.y == mLastHeightSent; 5534 recordNewContentSize(draw.mWidthHeight.x, 5535 draw.mWidthHeight.y 5536 + (mFindIsUp ? mFindHeight : 0), updateLayout); 5537 if (DebugFlags.WEB_VIEW) { 5538 Rect b = draw.mInvalRegion.getBounds(); 5539 Log.v(LOGTAG, "NEW_PICTURE_MSG_ID {" + 5540 b.left+","+b.top+","+b.right+","+b.bottom+"}"); 5541 } 5542 invalidateContentRect(draw.mInvalRegion.getBounds()); 5543 if (mPictureListener != null) { 5544 mPictureListener.onNewPicture(WebView.this, capturePicture()); 5545 } 5546 if (useWideViewport) { 5547 // limit mZoomOverviewWidth to sMaxViewportWidth so that 5548 // if the page doesn't behave well, the WebView won't go 5549 // insane. 5550 mZoomOverviewWidth = Math.min(sMaxViewportWidth, Math 5551 .max(draw.mMinPrefWidth, draw.mViewPoint.x)); 5552 } 5553 if (!mMinZoomScaleFixed) { 5554 mMinZoomScale = (float) viewWidth / mZoomOverviewWidth; 5555 } 5556 if (!mDrawHistory && mInZoomOverview) { 5557 // fit the content width to the current view. Ignore 5558 // the rounding error case. 5559 if (Math.abs((viewWidth * mInvActualScale) 5560 - mZoomOverviewWidth) > 1) { 5561 setNewZoomScale((float) viewWidth 5562 / mZoomOverviewWidth, false); 5563 } 5564 } 5565 if (draw.mFocusSizeChanged && inEditingMode()) { 5566 mFocusSizeChanged = true; 5567 } 5568 if (hasRestoreState) { 5569 mViewManager.postReadyToDrawAll(); 5570 } 5571 break; 5572 } 5573 case WEBCORE_INITIALIZED_MSG_ID: 5574 // nativeCreate sets mNativeClass to a non-zero value 5575 nativeCreate(msg.arg1); 5576 break; 5577 case UPDATE_TEXTFIELD_TEXT_MSG_ID: 5578 // Make sure that the textfield is currently focused 5579 // and representing the same node as the pointer. 5580 if (inEditingMode() && 5581 mWebTextView.isSameTextField(msg.arg1)) { 5582 if (msg.getData().getBoolean("password")) { 5583 Spannable text = (Spannable) mWebTextView.getText(); 5584 int start = Selection.getSelectionStart(text); 5585 int end = Selection.getSelectionEnd(text); 5586 mWebTextView.setInPassword(true); 5587 // Restore the selection, which may have been 5588 // ruined by setInPassword. 5589 Spannable pword = 5590 (Spannable) mWebTextView.getText(); 5591 Selection.setSelection(pword, start, end); 5592 // If the text entry has created more events, ignore 5593 // this one. 5594 } else if (msg.arg2 == mTextGeneration) { 5595 mWebTextView.setTextAndKeepSelection( 5596 (String) msg.obj); 5597 } 5598 } 5599 break; 5600 case UPDATE_TEXT_SELECTION_MSG_ID: 5601 if (inEditingMode() 5602 && mWebTextView.isSameTextField(msg.arg1) 5603 && msg.arg2 == mTextGeneration) { 5604 WebViewCore.TextSelectionData tData 5605 = (WebViewCore.TextSelectionData) msg.obj; 5606 mWebTextView.setSelectionFromWebKit(tData.mStart, 5607 tData.mEnd); 5608 } 5609 break; 5610 case RETURN_LABEL: 5611 if (inEditingMode() 5612 && mWebTextView.isSameTextField(msg.arg1)) { 5613 mWebTextView.setHint((String) msg.obj); 5614 InputMethodManager imm 5615 = InputMethodManager.peekInstance(); 5616 // The hint is propagated to the IME in 5617 // onCreateInputConnection. If the IME is already 5618 // active, restart it so that its hint text is updated. 5619 if (imm != null && imm.isActive(mWebTextView)) { 5620 imm.restartInput(mWebTextView); 5621 } 5622 } 5623 break; 5624 case MOVE_OUT_OF_PLUGIN: 5625 navHandledKey(msg.arg1, 1, false, 0, true); 5626 break; 5627 case UPDATE_TEXT_ENTRY_MSG_ID: 5628 // this is sent after finishing resize in WebViewCore. Make 5629 // sure the text edit box is still on the screen. 5630 if (inEditingMode() && nativeCursorIsTextInput()) { 5631 mWebTextView.bringIntoView(); 5632 rebuildWebTextView(); 5633 } 5634 break; 5635 case CLEAR_TEXT_ENTRY: 5636 clearTextEntry(); 5637 break; 5638 case INVAL_RECT_MSG_ID: { 5639 Rect r = (Rect)msg.obj; 5640 if (r == null) { 5641 invalidate(); 5642 } else { 5643 // we need to scale r from content into view coords, 5644 // which viewInvalidate() does for us 5645 viewInvalidate(r.left, r.top, r.right, r.bottom); 5646 } 5647 break; 5648 } 5649 case IMMEDIATE_REPAINT_MSG_ID: { 5650 int updates = msg.arg1; 5651 if (updates != 0) { 5652 // updates is a C++ pointer to a Vector of 5653 // AnimationValues that we apply to the layers. 5654 // The Vector is deallocated in nativeUpdateLayers(). 5655 nativeUpdateLayers(mRootLayer, updates); 5656 } 5657 invalidate(); 5658 break; 5659 } 5660 case SET_ROOT_LAYER_MSG_ID: { 5661 int oldLayer = mRootLayer; 5662 mRootLayer = msg.arg1; 5663 if (oldLayer > 0) { 5664 nativeDestroyLayer(oldLayer); 5665 } 5666 if (mRootLayer == 0) { 5667 mLayersHaveAnimations = false; 5668 } 5669 if (mEvaluateThread != null) { 5670 mEvaluateThread.cancel(); 5671 mEvaluateThread = null; 5672 } 5673 if (nativeLayersHaveAnimations(mRootLayer)) { 5674 mLayersHaveAnimations = true; 5675 mEvaluateThread = new EvaluateLayersAnimations(); 5676 mEvaluateThread.start(); 5677 } 5678 invalidate(); 5679 break; 5680 } 5681 case REQUEST_FORM_DATA: 5682 AutoCompleteAdapter adapter = (AutoCompleteAdapter) msg.obj; 5683 if (mWebTextView.isSameTextField(msg.arg1)) { 5684 mWebTextView.setAdapterCustom(adapter); 5685 } 5686 break; 5687 case UPDATE_CLIPBOARD: 5688 String str = (String) msg.obj; 5689 if (DebugFlags.WEB_VIEW) { 5690 Log.v(LOGTAG, "UPDATE_CLIPBOARD " + str); 5691 } 5692 try { 5693 IClipboard clip = IClipboard.Stub.asInterface( 5694 ServiceManager.getService("clipboard")); 5695 clip.setClipboardText(str); 5696 } catch (android.os.RemoteException e) { 5697 Log.e(LOGTAG, "Clipboard failed", e); 5698 } 5699 break; 5700 case RESUME_WEBCORE_UPDATE: 5701 WebViewCore.resumeUpdate(mWebViewCore); 5702 break; 5703 5704 case LONG_PRESS_CENTER: 5705 // as this is shared by keydown and trackballdown, reset all 5706 // the states 5707 mGotCenterDown = false; 5708 mTrackballDown = false; 5709 // LONG_PRESS_CENTER is sent as a delayed message. If we 5710 // switch to windows overview, the WebView will be 5711 // temporarily removed from the view system. In that case, 5712 // do nothing. 5713 if (getParent() != null) { 5714 performLongClick(); 5715 } 5716 break; 5717 5718 case WEBCORE_NEED_TOUCH_EVENTS: 5719 mForwardTouchEvents = (msg.arg1 != 0); 5720 break; 5721 5722 case PREVENT_TOUCH_ID: 5723 if (msg.arg1 == MotionEvent.ACTION_DOWN) { 5724 // dont override if mPreventDrag has been set to no due 5725 // to time out 5726 if (mPreventDrag == PREVENT_DRAG_MAYBE_YES) { 5727 mPreventDrag = (msg.arg2 & TOUCH_PREVENT_DRAG) 5728 == TOUCH_PREVENT_DRAG ? PREVENT_DRAG_YES 5729 : PREVENT_DRAG_NO; 5730 if (mPreventDrag == PREVENT_DRAG_YES) { 5731 mTouchMode = TOUCH_DONE_MODE; 5732 } else { 5733 mPreventLongPress = 5734 (msg.arg2 & TOUCH_PREVENT_LONGPRESS) 5735 == TOUCH_PREVENT_LONGPRESS; 5736 mPreventDoubleTap = 5737 (msg.arg2 & TOUCH_PREVENT_DOUBLETAP) 5738 == TOUCH_PREVENT_DOUBLETAP; 5739 } 5740 } 5741 } 5742 break; 5743 5744 case REQUEST_KEYBOARD: 5745 if (msg.arg1 == 0) { 5746 hideSoftKeyboard(); 5747 } else { 5748 displaySoftKeyboard(1 == msg.arg2); 5749 } 5750 break; 5751 5752 case FIND_AGAIN: 5753 // Ignore if find has been dismissed. 5754 if (mFindIsUp) { 5755 findAll(mLastFind); 5756 } 5757 break; 5758 5759 case DRAG_HELD_MOTIONLESS: 5760 mHeldMotionless = MOTIONLESS_TRUE; 5761 invalidate(); 5762 // fall through to keep scrollbars awake 5763 5764 case AWAKEN_SCROLL_BARS: 5765 if (mTouchMode == TOUCH_DRAG_MODE 5766 && mHeldMotionless == MOTIONLESS_TRUE) { 5767 awakenScrollBars(ViewConfiguration 5768 .getScrollDefaultDelay(), false); 5769 mPrivateHandler.sendMessageDelayed(mPrivateHandler 5770 .obtainMessage(AWAKEN_SCROLL_BARS), 5771 ViewConfiguration.getScrollDefaultDelay()); 5772 } 5773 break; 5774 5775 case DO_MOTION_UP: 5776 doMotionUp(msg.arg1, msg.arg2, (Boolean) msg.obj); 5777 break; 5778 5779 case SHOW_FULLSCREEN: 5780 WebViewCore.PluginFullScreenData data 5781 = (WebViewCore.PluginFullScreenData) msg.obj; 5782 if (data.mNpp != 0 && data.mView != null) { 5783 if (mFullScreenHolder != null) { 5784 Log.w(LOGTAG, 5785 "Should not have another full screen."); 5786 mFullScreenHolder.dismiss(); 5787 } 5788 mFullScreenHolder = new PluginFullScreenHolder( 5789 WebView.this, data.mNpp); 5790 mFullScreenHolder.setContentView(data.mView); 5791 mFullScreenHolder.setCancelable(false); 5792 mFullScreenHolder.setCanceledOnTouchOutside(false); 5793 mFullScreenHolder.show(); 5794 } 5795 // move the matching embedded view fully into the view so 5796 // that touch will be valid instead of rejected due to out 5797 // of the visible bounds 5798 // TODO: do we need to preserve the original position and 5799 // scale so that we can revert it when leaving the full 5800 // screen mode? 5801 int x = contentToViewX(data.mDocX); 5802 int y = contentToViewY(data.mDocY); 5803 int width = contentToViewDimension(data.mDocWidth); 5804 int height = contentToViewDimension(data.mDocHeight); 5805 int viewWidth = getViewWidth(); 5806 int viewHeight = getViewHeight(); 5807 int newX = mScrollX; 5808 int newY = mScrollY; 5809 if (x < mScrollX) { 5810 newX = x + (width > viewWidth 5811 ? (width - viewWidth) / 2 : 0); 5812 } else if (x + width > mScrollX + viewWidth) { 5813 newX = x + width - viewWidth - (width > viewWidth 5814 ? (width - viewWidth) / 2 : 0); 5815 } 5816 if (y < mScrollY) { 5817 newY = y + (height > viewHeight 5818 ? (height - viewHeight) / 2 : 0); 5819 } else if (y + height > mScrollY + viewHeight) { 5820 newY = y + height - viewHeight - (height > viewHeight 5821 ? (height - viewHeight) / 2 : 0); 5822 } 5823 scrollTo(newX, newY); 5824 if (width > viewWidth || height > viewHeight) { 5825 mZoomCenterX = viewWidth * .5f; 5826 mZoomCenterY = viewHeight * .5f; 5827 setNewZoomScale(mActualScale 5828 / Math.max((float) width / viewWidth, 5829 (float) height / viewHeight), false); 5830 } 5831 // Now update the bound 5832 mFullScreenHolder.updateBound(contentToViewX(data.mDocX) 5833 - mScrollX, contentToViewY(data.mDocY) - mScrollY, 5834 contentToViewDimension(data.mDocWidth), 5835 contentToViewDimension(data.mDocHeight)); 5836 break; 5837 5838 case HIDE_FULLSCREEN: 5839 if (mFullScreenHolder != null) { 5840 mFullScreenHolder.dismiss(); 5841 mFullScreenHolder = null; 5842 } 5843 break; 5844 5845 case DOM_FOCUS_CHANGED: 5846 if (inEditingMode()) { 5847 nativeClearCursor(); 5848 rebuildWebTextView(); 5849 } 5850 break; 5851 5852 default: 5853 super.handleMessage(msg); 5854 break; 5855 } 5856 } 5857 } 5858 5859 // Class used to use a dropdown for a <select> element 5860 private class InvokeListBox implements Runnable { 5861 // Whether the listbox allows multiple selection. 5862 private boolean mMultiple; 5863 // Passed in to a list with multiple selection to tell 5864 // which items are selected. 5865 private int[] mSelectedArray; 5866 // Passed in to a list with single selection to tell 5867 // where the initial selection is. 5868 private int mSelection; 5869 5870 private Container[] mContainers; 5871 5872 // Need these to provide stable ids to my ArrayAdapter, 5873 // which normally does not have stable ids. (Bug 1250098) 5874 private class Container extends Object { 5875 /** 5876 * Possible values for mEnabled. Keep in sync with OptionStatus in 5877 * WebViewCore.cpp 5878 */ 5879 final static int OPTGROUP = -1; 5880 final static int OPTION_DISABLED = 0; 5881 final static int OPTION_ENABLED = 1; 5882 5883 String mString; 5884 int mEnabled; 5885 int mId; 5886 5887 public String toString() { 5888 return mString; 5889 } 5890 } 5891 5892 /** 5893 * Subclass ArrayAdapter so we can disable OptionGroupLabels, 5894 * and allow filtering. 5895 */ 5896 private class MyArrayListAdapter extends ArrayAdapter<Container> { 5897 public MyArrayListAdapter(Context context, Container[] objects, boolean multiple) { 5898 super(context, 5899 multiple ? com.android.internal.R.layout.select_dialog_multichoice : 5900 com.android.internal.R.layout.select_dialog_singlechoice, 5901 objects); 5902 } 5903 5904 @Override 5905 public View getView(int position, View convertView, 5906 ViewGroup parent) { 5907 // Always pass in null so that we will get a new CheckedTextView 5908 // Otherwise, an item which was previously used as an <optgroup> 5909 // element (i.e. has no check), could get used as an <option> 5910 // element, which needs a checkbox/radio, but it would not have 5911 // one. 5912 convertView = super.getView(position, null, parent); 5913 Container c = item(position); 5914 if (c != null && Container.OPTION_ENABLED != c.mEnabled) { 5915 // ListView does not draw dividers between disabled and 5916 // enabled elements. Use a LinearLayout to provide dividers 5917 LinearLayout layout = new LinearLayout(mContext); 5918 layout.setOrientation(LinearLayout.VERTICAL); 5919 if (position > 0) { 5920 View dividerTop = new View(mContext); 5921 dividerTop.setBackgroundResource( 5922 android.R.drawable.divider_horizontal_bright); 5923 layout.addView(dividerTop); 5924 } 5925 5926 if (Container.OPTGROUP == c.mEnabled) { 5927 // Currently select_dialog_multichoice and 5928 // select_dialog_singlechoice are CheckedTextViews. If 5929 // that changes, the class cast will no longer be valid. 5930 Assert.assertTrue( 5931 convertView instanceof CheckedTextView); 5932 ((CheckedTextView) convertView).setCheckMarkDrawable( 5933 null); 5934 } else { 5935 // c.mEnabled == Container.OPTION_DISABLED 5936 // Draw the disabled element in a disabled state. 5937 convertView.setEnabled(false); 5938 } 5939 5940 layout.addView(convertView); 5941 if (position < getCount() - 1) { 5942 View dividerBottom = new View(mContext); 5943 dividerBottom.setBackgroundResource( 5944 android.R.drawable.divider_horizontal_bright); 5945 layout.addView(dividerBottom); 5946 } 5947 return layout; 5948 } 5949 return convertView; 5950 } 5951 5952 @Override 5953 public boolean hasStableIds() { 5954 // AdapterView's onChanged method uses this to determine whether 5955 // to restore the old state. Return false so that the old (out 5956 // of date) state does not replace the new, valid state. 5957 return false; 5958 } 5959 5960 private Container item(int position) { 5961 if (position < 0 || position >= getCount()) { 5962 return null; 5963 } 5964 return (Container) getItem(position); 5965 } 5966 5967 @Override 5968 public long getItemId(int position) { 5969 Container item = item(position); 5970 if (item == null) { 5971 return -1; 5972 } 5973 return item.mId; 5974 } 5975 5976 @Override 5977 public boolean areAllItemsEnabled() { 5978 return false; 5979 } 5980 5981 @Override 5982 public boolean isEnabled(int position) { 5983 Container item = item(position); 5984 if (item == null) { 5985 return false; 5986 } 5987 return Container.OPTION_ENABLED == item.mEnabled; 5988 } 5989 } 5990 5991 private InvokeListBox(String[] array, int[] enabled, int[] selected) { 5992 mMultiple = true; 5993 mSelectedArray = selected; 5994 5995 int length = array.length; 5996 mContainers = new Container[length]; 5997 for (int i = 0; i < length; i++) { 5998 mContainers[i] = new Container(); 5999 mContainers[i].mString = array[i]; 6000 mContainers[i].mEnabled = enabled[i]; 6001 mContainers[i].mId = i; 6002 } 6003 } 6004 6005 private InvokeListBox(String[] array, int[] enabled, int selection) { 6006 mSelection = selection; 6007 mMultiple = false; 6008 6009 int length = array.length; 6010 mContainers = new Container[length]; 6011 for (int i = 0; i < length; i++) { 6012 mContainers[i] = new Container(); 6013 mContainers[i].mString = array[i]; 6014 mContainers[i].mEnabled = enabled[i]; 6015 mContainers[i].mId = i; 6016 } 6017 } 6018 6019 /* 6020 * Whenever the data set changes due to filtering, this class ensures 6021 * that the checked item remains checked. 6022 */ 6023 private class SingleDataSetObserver extends DataSetObserver { 6024 private long mCheckedId; 6025 private ListView mListView; 6026 private Adapter mAdapter; 6027 6028 /* 6029 * Create a new observer. 6030 * @param id The ID of the item to keep checked. 6031 * @param l ListView for getting and clearing the checked states 6032 * @param a Adapter for getting the IDs 6033 */ 6034 public SingleDataSetObserver(long id, ListView l, Adapter a) { 6035 mCheckedId = id; 6036 mListView = l; 6037 mAdapter = a; 6038 } 6039 6040 public void onChanged() { 6041 // The filter may have changed which item is checked. Find the 6042 // item that the ListView thinks is checked. 6043 int position = mListView.getCheckedItemPosition(); 6044 long id = mAdapter.getItemId(position); 6045 if (mCheckedId != id) { 6046 // Clear the ListView's idea of the checked item, since 6047 // it is incorrect 6048 mListView.clearChoices(); 6049 // Search for mCheckedId. If it is in the filtered list, 6050 // mark it as checked 6051 int count = mAdapter.getCount(); 6052 for (int i = 0; i < count; i++) { 6053 if (mAdapter.getItemId(i) == mCheckedId) { 6054 mListView.setItemChecked(i, true); 6055 break; 6056 } 6057 } 6058 } 6059 } 6060 6061 public void onInvalidate() {} 6062 } 6063 6064 public void run() { 6065 final ListView listView = (ListView) LayoutInflater.from(mContext) 6066 .inflate(com.android.internal.R.layout.select_dialog, null); 6067 final MyArrayListAdapter adapter = new 6068 MyArrayListAdapter(mContext, mContainers, mMultiple); 6069 AlertDialog.Builder b = new AlertDialog.Builder(mContext) 6070 .setView(listView).setCancelable(true) 6071 .setInverseBackgroundForced(true); 6072 6073 if (mMultiple) { 6074 b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { 6075 public void onClick(DialogInterface dialog, int which) { 6076 mWebViewCore.sendMessage( 6077 EventHub.LISTBOX_CHOICES, 6078 adapter.getCount(), 0, 6079 listView.getCheckedItemPositions()); 6080 }}); 6081 b.setNegativeButton(android.R.string.cancel, 6082 new DialogInterface.OnClickListener() { 6083 public void onClick(DialogInterface dialog, int which) { 6084 mWebViewCore.sendMessage( 6085 EventHub.SINGLE_LISTBOX_CHOICE, -2, 0); 6086 }}); 6087 } 6088 final AlertDialog dialog = b.create(); 6089 listView.setAdapter(adapter); 6090 listView.setFocusableInTouchMode(true); 6091 // There is a bug (1250103) where the checks in a ListView with 6092 // multiple items selected are associated with the positions, not 6093 // the ids, so the items do not properly retain their checks when 6094 // filtered. Do not allow filtering on multiple lists until 6095 // that bug is fixed. 6096 6097 listView.setTextFilterEnabled(!mMultiple); 6098 if (mMultiple) { 6099 listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); 6100 int length = mSelectedArray.length; 6101 for (int i = 0; i < length; i++) { 6102 listView.setItemChecked(mSelectedArray[i], true); 6103 } 6104 } else { 6105 listView.setOnItemClickListener(new OnItemClickListener() { 6106 public void onItemClick(AdapterView parent, View v, 6107 int position, long id) { 6108 mWebViewCore.sendMessage( 6109 EventHub.SINGLE_LISTBOX_CHOICE, (int)id, 0); 6110 dialog.dismiss(); 6111 } 6112 }); 6113 if (mSelection != -1) { 6114 listView.setSelection(mSelection); 6115 listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 6116 listView.setItemChecked(mSelection, true); 6117 DataSetObserver observer = new SingleDataSetObserver( 6118 adapter.getItemId(mSelection), listView, adapter); 6119 adapter.registerDataSetObserver(observer); 6120 } 6121 } 6122 dialog.setOnCancelListener(new DialogInterface.OnCancelListener() { 6123 public void onCancel(DialogInterface dialog) { 6124 mWebViewCore.sendMessage( 6125 EventHub.SINGLE_LISTBOX_CHOICE, -2, 0); 6126 } 6127 }); 6128 dialog.show(); 6129 } 6130 } 6131 6132 /* 6133 * Request a dropdown menu for a listbox with multiple selection. 6134 * 6135 * @param array Labels for the listbox. 6136 * @param enabledArray State for each element in the list. See static 6137 * integers in Container class. 6138 * @param selectedArray Which positions are initally selected. 6139 */ 6140 void requestListBox(String[] array, int[] enabledArray, int[] 6141 selectedArray) { 6142 mPrivateHandler.post( 6143 new InvokeListBox(array, enabledArray, selectedArray)); 6144 } 6145 6146 /* 6147 * Request a dropdown menu for a listbox with single selection or a single 6148 * <select> element. 6149 * 6150 * @param array Labels for the listbox. 6151 * @param enabledArray State for each element in the list. See static 6152 * integers in Container class. 6153 * @param selection Which position is initally selected. 6154 */ 6155 void requestListBox(String[] array, int[] enabledArray, int selection) { 6156 mPrivateHandler.post( 6157 new InvokeListBox(array, enabledArray, selection)); 6158 } 6159 6160 // called by JNI 6161 private void sendMoveFocus(int frame, int node) { 6162 mWebViewCore.sendMessage(EventHub.SET_MOVE_FOCUS, 6163 new WebViewCore.CursorData(frame, node, 0, 0)); 6164 } 6165 6166 // called by JNI 6167 private void sendMoveMouse(int frame, int node, int x, int y) { 6168 mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE, 6169 new WebViewCore.CursorData(frame, node, x, y)); 6170 } 6171 6172 /* 6173 * Send a mouse move event to the webcore thread. 6174 * 6175 * @param removeFocus Pass true if the "mouse" cursor is now over a node 6176 * which wants key events, but it is not the focus. This 6177 * will make the visual appear as though nothing is in 6178 * focus. Remove the WebTextView, if present, and stop 6179 * drawing the blinking caret. 6180 * called by JNI 6181 */ 6182 private void sendMoveMouseIfLatest(boolean removeFocus) { 6183 if (removeFocus) { 6184 clearTextEntry(); 6185 setFocusControllerInactive(); 6186 } 6187 mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE_IF_LATEST, 6188 cursorData()); 6189 } 6190 6191 // called by JNI 6192 private void sendMotionUp(int touchGeneration, 6193 int frame, int node, int x, int y) { 6194 WebViewCore.TouchUpData touchUpData = new WebViewCore.TouchUpData(); 6195 touchUpData.mMoveGeneration = touchGeneration; 6196 touchUpData.mFrame = frame; 6197 touchUpData.mNode = node; 6198 touchUpData.mX = x; 6199 touchUpData.mY = y; 6200 mWebViewCore.sendMessage(EventHub.TOUCH_UP, touchUpData); 6201 } 6202 6203 6204 private int getScaledMaxXScroll() { 6205 int width; 6206 if (mHeightCanMeasure == false) { 6207 width = getViewWidth() / 4; 6208 } else { 6209 Rect visRect = new Rect(); 6210 calcOurVisibleRect(visRect); 6211 width = visRect.width() / 2; 6212 } 6213 // FIXME the divisor should be retrieved from somewhere 6214 return viewToContentX(width); 6215 } 6216 6217 private int getScaledMaxYScroll() { 6218 int height; 6219 if (mHeightCanMeasure == false) { 6220 height = getViewHeight() / 4; 6221 } else { 6222 Rect visRect = new Rect(); 6223 calcOurVisibleRect(visRect); 6224 height = visRect.height() / 2; 6225 } 6226 // FIXME the divisor should be retrieved from somewhere 6227 // the closest thing today is hard-coded into ScrollView.java 6228 // (from ScrollView.java, line 363) int maxJump = height/2; 6229 return Math.round(height * mInvActualScale); 6230 } 6231 6232 /** 6233 * Called by JNI to invalidate view 6234 */ 6235 private void viewInvalidate() { 6236 invalidate(); 6237 } 6238 6239 // return true if the key was handled 6240 private boolean navHandledKey(int keyCode, int count, boolean noScroll, 6241 long time, boolean ignorePlugin) { 6242 if (mNativeClass == 0) { 6243 return false; 6244 } 6245 if (ignorePlugin == false && nativeFocusIsPlugin()) { 6246 KeyEvent event = new KeyEvent(time, time, KeyEvent.ACTION_DOWN 6247 , keyCode, count, (mShiftIsPressed ? KeyEvent.META_SHIFT_ON : 0) 6248 | (false ? KeyEvent.META_ALT_ON : 0) // FIXME 6249 | (false ? KeyEvent.META_SYM_ON : 0) // FIXME 6250 , 0, 0, 0); 6251 mWebViewCore.sendMessage(EventHub.KEY_DOWN, event); 6252 mWebViewCore.sendMessage(EventHub.KEY_UP, event); 6253 return true; 6254 } 6255 mLastCursorTime = time; 6256 mLastCursorBounds = nativeGetCursorRingBounds(); 6257 boolean keyHandled 6258 = nativeMoveCursor(keyCode, count, noScroll) == false; 6259 if (DebugFlags.WEB_VIEW) { 6260 Log.v(LOGTAG, "navHandledKey mLastCursorBounds=" + mLastCursorBounds 6261 + " mLastCursorTime=" + mLastCursorTime 6262 + " handled=" + keyHandled); 6263 } 6264 if (keyHandled == false || mHeightCanMeasure == false) { 6265 return keyHandled; 6266 } 6267 Rect contentCursorRingBounds = nativeGetCursorRingBounds(); 6268 if (contentCursorRingBounds.isEmpty()) return keyHandled; 6269 Rect viewCursorRingBounds = contentToViewRect(contentCursorRingBounds); 6270 Rect visRect = new Rect(); 6271 calcOurVisibleRect(visRect); 6272 Rect outset = new Rect(visRect); 6273 int maxXScroll = visRect.width() / 2; 6274 int maxYScroll = visRect.height() / 2; 6275 outset.inset(-maxXScroll, -maxYScroll); 6276 if (Rect.intersects(outset, viewCursorRingBounds) == false) { 6277 return keyHandled; 6278 } 6279 // FIXME: Necessary because ScrollView/ListView do not scroll left/right 6280 int maxH = Math.min(viewCursorRingBounds.right - visRect.right, 6281 maxXScroll); 6282 if (maxH > 0) { 6283 pinScrollBy(maxH, 0, true, 0); 6284 } else { 6285 maxH = Math.max(viewCursorRingBounds.left - visRect.left, 6286 -maxXScroll); 6287 if (maxH < 0) { 6288 pinScrollBy(maxH, 0, true, 0); 6289 } 6290 } 6291 if (mLastCursorBounds.isEmpty()) return keyHandled; 6292 if (mLastCursorBounds.equals(contentCursorRingBounds)) { 6293 return keyHandled; 6294 } 6295 if (DebugFlags.WEB_VIEW) { 6296 Log.v(LOGTAG, "navHandledKey contentCursorRingBounds=" 6297 + contentCursorRingBounds); 6298 } 6299 requestRectangleOnScreen(viewCursorRingBounds); 6300 mUserScroll = true; 6301 return keyHandled; 6302 } 6303 6304 /** 6305 * Set the background color. It's white by default. Pass 6306 * zero to make the view transparent. 6307 * @param color the ARGB color described by Color.java 6308 */ 6309 public void setBackgroundColor(int color) { 6310 mBackgroundColor = color; 6311 mWebViewCore.sendMessage(EventHub.SET_BACKGROUND_COLOR, color); 6312 } 6313 6314 public void debugDump() { 6315 nativeDebugDump(); 6316 mWebViewCore.sendMessage(EventHub.DUMP_NAVTREE); 6317 } 6318 6319 /** 6320 * Draw the HTML page into the specified canvas. This call ignores any 6321 * view-specific zoom, scroll offset, or other changes. It does not draw 6322 * any view-specific chrome, such as progress or URL bars. 6323 * 6324 * @hide only needs to be accessible to Browser and testing 6325 */ 6326 public void drawPage(Canvas canvas) { 6327 mWebViewCore.drawContentPicture(canvas, 0, false, false); 6328 } 6329 6330 /** 6331 * Update our cache with updatedText. 6332 * @param updatedText The new text to put in our cache. 6333 */ 6334 /* package */ void updateCachedTextfield(String updatedText) { 6335 // Also place our generation number so that when we look at the cache 6336 // we recognize that it is up to date. 6337 nativeUpdateCachedTextfield(updatedText, mTextGeneration); 6338 } 6339 6340 private native int nativeCacheHitFramePointer(); 6341 private native Rect nativeCacheHitNodeBounds(); 6342 private native int nativeCacheHitNodePointer(); 6343 /* package */ native void nativeClearCursor(); 6344 private native void nativeCreate(int ptr); 6345 private native int nativeCursorFramePointer(); 6346 private native Rect nativeCursorNodeBounds(); 6347 private native int nativeCursorNodePointer(); 6348 /* package */ native boolean nativeCursorMatchesFocus(); 6349 private native boolean nativeCursorIntersects(Rect visibleRect); 6350 private native boolean nativeCursorIsAnchor(); 6351 private native boolean nativeCursorIsTextInput(); 6352 private native Point nativeCursorPosition(); 6353 private native String nativeCursorText(); 6354 /** 6355 * Returns true if the native cursor node says it wants to handle key events 6356 * (ala plugins). This can only be called if mNativeClass is non-zero! 6357 */ 6358 private native boolean nativeCursorWantsKeyEvents(); 6359 private native void nativeDebugDump(); 6360 private native void nativeDestroy(); 6361 private native void nativeDrawCursorRing(Canvas content); 6362 private native void nativeDestroyLayer(int layer); 6363 private native int nativeEvaluateLayersAnimations(int layer); 6364 private native boolean nativeLayersHaveAnimations(int layer); 6365 private native void nativeUpdateLayers(int layer, int updates); 6366 private native void nativeDrawLayers(int layer, 6367 int scrollX, int scrollY, 6368 int width, int height, 6369 float scale, Canvas canvas); 6370 private native void nativeDrawMatches(Canvas canvas); 6371 private native void nativeDrawSelectionPointer(Canvas content, 6372 float scale, int x, int y, boolean extendSelection); 6373 private native void nativeDrawSelectionRegion(Canvas content); 6374 private native void nativeDumpDisplayTree(String urlOrNull); 6375 private native int nativeFindAll(String findLower, String findUpper); 6376 private native void nativeFindNext(boolean forward); 6377 /* package */ native int nativeFocusCandidateFramePointer(); 6378 private native boolean nativeFocusCandidateIsPassword(); 6379 private native boolean nativeFocusCandidateIsRtlText(); 6380 private native boolean nativeFocusCandidateIsTextInput(); 6381 /* package */ native int nativeFocusCandidateMaxLength(); 6382 /* package */ native String nativeFocusCandidateName(); 6383 private native Rect nativeFocusCandidateNodeBounds(); 6384 private native int nativeFocusCandidatePointer(); 6385 private native String nativeFocusCandidateText(); 6386 private native int nativeFocusCandidateTextSize(); 6387 /** 6388 * Returns an integer corresponding to WebView.cpp::type. 6389 * See WebTextView.setType() 6390 */ 6391 private native int nativeFocusCandidateType(); 6392 private native boolean nativeFocusIsPlugin(); 6393 /* package */ native int nativeFocusNodePointer(); 6394 private native Rect nativeGetCursorRingBounds(); 6395 private native Region nativeGetSelection(); 6396 private native boolean nativeHasCursorNode(); 6397 private native boolean nativeHasFocusNode(); 6398 private native void nativeHideCursor(); 6399 private native String nativeImageURI(int x, int y); 6400 private native void nativeInstrumentReport(); 6401 /* package */ native void nativeMoveCursorToNextTextInput(); 6402 // return true if the page has been scrolled 6403 private native boolean nativeMotionUp(int x, int y, int slop); 6404 // returns false if it handled the key 6405 private native boolean nativeMoveCursor(int keyCode, int count, 6406 boolean noScroll); 6407 private native int nativeMoveGeneration(); 6408 private native void nativeMoveSelection(int x, int y, 6409 boolean extendSelection); 6410 private native boolean nativePointInNavCache(int x, int y, int slop); 6411 // Like many other of our native methods, you must make sure that 6412 // mNativeClass is not null before calling this method. 6413 private native void nativeRecordButtons(boolean focused, 6414 boolean pressed, boolean invalidate); 6415 private native void nativeSelectBestAt(Rect rect); 6416 private native void nativeSetFindIsUp(); 6417 private native void nativeSetFollowedLink(boolean followed); 6418 private native void nativeSetHeightCanMeasure(boolean measure); 6419 // Returns a value corresponding to CachedFrame::ImeAction 6420 /* package */ native int nativeTextFieldAction(); 6421 private native int nativeTextGeneration(); 6422 // Never call this version except by updateCachedTextfield(String) - 6423 // we always want to pass in our generation number. 6424 private native void nativeUpdateCachedTextfield(String updatedText, 6425 int generation); 6426 // return NO_LEFTEDGE means failure. 6427 private static final int NO_LEFTEDGE = -1; 6428 private native int nativeGetBlockLeftEdge(int x, int y, float scale); 6429} 6430