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