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