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