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