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