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