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