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