WebView.java revision 7a37587664baf274633db415c4a2589288b653b0
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 (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT 3695 || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT) { 3696 if (nativeFocusIsPlugin()) { 3697 mShiftIsPressed = true; 3698 } else if (!nativeCursorWantsKeyEvents() && !mShiftIsPressed) { 3699 setUpSelectXY(); 3700 } 3701 } 3702 3703 if (keyCode >= KeyEvent.KEYCODE_DPAD_UP 3704 && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) { 3705 switchOutDrawHistory(); 3706 if (nativeFocusIsPlugin()) { 3707 letPluginHandleNavKey(keyCode, event.getEventTime(), true); 3708 return true; 3709 } 3710 if (mShiftIsPressed) { 3711 int xRate = keyCode == KeyEvent.KEYCODE_DPAD_LEFT 3712 ? -1 : keyCode == KeyEvent.KEYCODE_DPAD_RIGHT ? 1 : 0; 3713 int yRate = keyCode == KeyEvent.KEYCODE_DPAD_UP ? 3714 -1 : keyCode == KeyEvent.KEYCODE_DPAD_DOWN ? 1 : 0; 3715 int multiplier = event.getRepeatCount() + 1; 3716 moveSelection(xRate * multiplier, yRate * multiplier); 3717 return true; 3718 } 3719 if (navHandledKey(keyCode, 1, false, event.getEventTime())) { 3720 playSoundEffect(keyCodeToSoundsEffect(keyCode)); 3721 return true; 3722 } 3723 // Bubble up the key event as WebView doesn't handle it 3724 return false; 3725 } 3726 3727 if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { 3728 switchOutDrawHistory(); 3729 if (event.getRepeatCount() == 0) { 3730 if (mShiftIsPressed && !nativeFocusIsPlugin()) { 3731 return true; // discard press if copy in progress 3732 } 3733 mGotCenterDown = true; 3734 mPrivateHandler.sendMessageDelayed(mPrivateHandler 3735 .obtainMessage(LONG_PRESS_CENTER), LONG_PRESS_TIMEOUT); 3736 // Already checked mNativeClass, so we do not need to check it 3737 // again. 3738 nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true); 3739 return true; 3740 } 3741 // Bubble up the key event as WebView doesn't handle it 3742 return false; 3743 } 3744 3745 if (keyCode != KeyEvent.KEYCODE_SHIFT_LEFT 3746 && keyCode != KeyEvent.KEYCODE_SHIFT_RIGHT) { 3747 // turn off copy select if a shift-key combo is pressed 3748 mExtendSelection = mShiftIsPressed = false; 3749 if (mTouchMode == TOUCH_SELECT_MODE) { 3750 mTouchMode = TOUCH_INIT_MODE; 3751 } 3752 } 3753 3754 if (getSettings().getNavDump()) { 3755 switch (keyCode) { 3756 case KeyEvent.KEYCODE_4: 3757 dumpDisplayTree(); 3758 break; 3759 case KeyEvent.KEYCODE_5: 3760 case KeyEvent.KEYCODE_6: 3761 dumpDomTree(keyCode == KeyEvent.KEYCODE_5); 3762 break; 3763 case KeyEvent.KEYCODE_7: 3764 case KeyEvent.KEYCODE_8: 3765 dumpRenderTree(keyCode == KeyEvent.KEYCODE_7); 3766 break; 3767 case KeyEvent.KEYCODE_9: 3768 nativeInstrumentReport(); 3769 return true; 3770 } 3771 } 3772 3773 if (nativeCursorIsTextInput()) { 3774 // This message will put the node in focus, for the DOM's notion 3775 // of focus, and make the focuscontroller active 3776 mWebViewCore.sendMessage(EventHub.CLICK, nativeCursorFramePointer(), 3777 nativeCursorNodePointer()); 3778 // This will bring up the WebTextView and put it in focus, for 3779 // our view system's notion of focus 3780 rebuildWebTextView(); 3781 // Now we need to pass the event to it 3782 if (inEditingMode()) { 3783 mWebTextView.setDefaultSelection(); 3784 return mWebTextView.dispatchKeyEvent(event); 3785 } 3786 } else if (nativeHasFocusNode()) { 3787 // In this case, the cursor is not on a text input, but the focus 3788 // might be. Check it, and if so, hand over to the WebTextView. 3789 rebuildWebTextView(); 3790 if (inEditingMode()) { 3791 mWebTextView.setDefaultSelection(); 3792 return mWebTextView.dispatchKeyEvent(event); 3793 } 3794 } 3795 3796 // TODO: should we pass all the keys to DOM or check the meta tag 3797 if (nativeCursorWantsKeyEvents() || true) { 3798 // pass the key to DOM 3799 mWebViewCore.sendMessage(EventHub.KEY_DOWN, event); 3800 // return true as DOM handles the key 3801 return true; 3802 } 3803 3804 // Bubble up the key event as WebView doesn't handle it 3805 return false; 3806 } 3807 3808 @Override 3809 public boolean onKeyUp(int keyCode, KeyEvent event) { 3810 if (DebugFlags.WEB_VIEW) { 3811 Log.v(LOGTAG, "keyUp at " + System.currentTimeMillis() 3812 + ", " + event + ", unicode=" + event.getUnicodeChar()); 3813 } 3814 3815 if (mNativeClass == 0) { 3816 return false; 3817 } 3818 3819 // special CALL handling when cursor node's href is "tel:XXX" 3820 if (keyCode == KeyEvent.KEYCODE_CALL && nativeHasCursorNode()) { 3821 String text = nativeCursorText(); 3822 if (!nativeCursorIsTextInput() && text != null 3823 && text.startsWith(SCHEME_TEL)) { 3824 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(text)); 3825 getContext().startActivity(intent); 3826 return true; 3827 } 3828 } 3829 3830 // Bubble up the key event if 3831 // 1. it is a system key; or 3832 // 2. the host application wants to handle it; 3833 if (event.isSystem() || mCallbackProxy.uiOverrideKeyEvent(event)) { 3834 return false; 3835 } 3836 3837 if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT 3838 || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT) { 3839 if (nativeFocusIsPlugin()) { 3840 mShiftIsPressed = false; 3841 return true; 3842 } else if (commitCopy()) { 3843 return true; 3844 } 3845 } 3846 3847 if (keyCode >= KeyEvent.KEYCODE_DPAD_UP 3848 && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) { 3849 if (nativeFocusIsPlugin()) { 3850 letPluginHandleNavKey(keyCode, event.getEventTime(), false); 3851 return true; 3852 } 3853 // always handle the navigation keys in the UI thread 3854 // Bubble up the key event as WebView doesn't handle it 3855 return false; 3856 } 3857 3858 if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { 3859 // remove the long press message first 3860 mPrivateHandler.removeMessages(LONG_PRESS_CENTER); 3861 mGotCenterDown = false; 3862 3863 if (mShiftIsPressed && !nativeFocusIsPlugin()) { 3864 if (mExtendSelection) { 3865 commitCopy(); 3866 } else { 3867 mExtendSelection = true; 3868 invalidate(); // draw the i-beam instead of the arrow 3869 } 3870 return true; // discard press if copy in progress 3871 } 3872 3873 // perform the single click 3874 Rect visibleRect = sendOurVisibleRect(); 3875 // Note that sendOurVisibleRect calls viewToContent, so the 3876 // coordinates should be in content coordinates. 3877 if (!nativeCursorIntersects(visibleRect)) { 3878 return false; 3879 } 3880 WebViewCore.CursorData data = cursorData(); 3881 mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE, data); 3882 playSoundEffect(SoundEffectConstants.CLICK); 3883 if (nativeCursorIsTextInput()) { 3884 rebuildWebTextView(); 3885 centerKeyPressOnTextField(); 3886 if (inEditingMode()) { 3887 mWebTextView.setDefaultSelection(); 3888 } 3889 return true; 3890 } 3891 clearTextEntry(true); 3892 nativeSetFollowedLink(true); 3893 if (!mCallbackProxy.uiOverrideUrlLoading(nativeCursorText())) { 3894 mWebViewCore.sendMessage(EventHub.CLICK, data.mFrame, 3895 nativeCursorNodePointer()); 3896 } 3897 return true; 3898 } 3899 3900 // TODO: should we pass all the keys to DOM or check the meta tag 3901 if (nativeCursorWantsKeyEvents() || true) { 3902 // pass the key to DOM 3903 mWebViewCore.sendMessage(EventHub.KEY_UP, event); 3904 // return true as DOM handles the key 3905 return true; 3906 } 3907 3908 // Bubble up the key event as WebView doesn't handle it 3909 return false; 3910 } 3911 3912 private void setUpSelectXY() { 3913 mExtendSelection = false; 3914 mShiftIsPressed = true; 3915 if (nativeHasCursorNode()) { 3916 Rect rect = nativeCursorNodeBounds(); 3917 mSelectX = contentToViewX(rect.left); 3918 mSelectY = contentToViewY(rect.top); 3919 } else if (mLastTouchY > getVisibleTitleHeight()) { 3920 mSelectX = mScrollX + (int) mLastTouchX; 3921 mSelectY = mScrollY + (int) mLastTouchY; 3922 } else { 3923 mSelectX = mScrollX + getViewWidth() / 2; 3924 mSelectY = mScrollY + getViewHeightWithTitle() / 2; 3925 } 3926 nativeHideCursor(); 3927 } 3928 3929 /** 3930 * Use this method to put the WebView into text selection mode. 3931 * Do not rely on this functionality; it will be deprecated in the future. 3932 */ 3933 public void emulateShiftHeld() { 3934 if (0 == mNativeClass) return; // client isn't initialized 3935 setUpSelectXY(); 3936 } 3937 3938 private boolean commitCopy() { 3939 boolean copiedSomething = false; 3940 if (mExtendSelection) { 3941 String selection = nativeGetSelection(); 3942 if (selection != "") { 3943 if (DebugFlags.WEB_VIEW) { 3944 Log.v(LOGTAG, "commitCopy \"" + selection + "\""); 3945 } 3946 Toast.makeText(mContext 3947 , com.android.internal.R.string.text_copied 3948 , Toast.LENGTH_SHORT).show(); 3949 copiedSomething = true; 3950 try { 3951 IClipboard clip = IClipboard.Stub.asInterface( 3952 ServiceManager.getService("clipboard")); 3953 clip.setClipboardText(selection); 3954 } catch (android.os.RemoteException e) { 3955 Log.e(LOGTAG, "Clipboard failed", e); 3956 } 3957 } 3958 mExtendSelection = false; 3959 } 3960 mShiftIsPressed = false; 3961 invalidate(); // remove selection region and pointer 3962 if (mTouchMode == TOUCH_SELECT_MODE) { 3963 mTouchMode = TOUCH_INIT_MODE; 3964 } 3965 return copiedSomething; 3966 } 3967 3968 @Override 3969 protected void onAttachedToWindow() { 3970 super.onAttachedToWindow(); 3971 if (hasWindowFocus()) onWindowFocusChanged(true); 3972 } 3973 3974 @Override 3975 protected void onDetachedFromWindow() { 3976 clearTextEntry(false); 3977 super.onDetachedFromWindow(); 3978 // Clean up the zoom controller 3979 mZoomButtonsController.setVisible(false); 3980 } 3981 3982 /** 3983 * @deprecated WebView no longer needs to implement 3984 * ViewGroup.OnHierarchyChangeListener. This method does nothing now. 3985 */ 3986 @Deprecated 3987 public void onChildViewAdded(View parent, View child) {} 3988 3989 /** 3990 * @deprecated WebView no longer needs to implement 3991 * ViewGroup.OnHierarchyChangeListener. This method does nothing now. 3992 */ 3993 @Deprecated 3994 public void onChildViewRemoved(View p, View child) {} 3995 3996 /** 3997 * @deprecated WebView should not have implemented 3998 * ViewTreeObserver.OnGlobalFocusChangeListener. This method 3999 * does nothing now. 4000 */ 4001 @Deprecated 4002 public void onGlobalFocusChanged(View oldFocus, View newFocus) { 4003 } 4004 4005 // To avoid drawing the cursor ring, and remove the TextView when our window 4006 // loses focus. 4007 @Override 4008 public void onWindowFocusChanged(boolean hasWindowFocus) { 4009 if (hasWindowFocus) { 4010 if (hasFocus()) { 4011 // If our window regained focus, and we have focus, then begin 4012 // drawing the cursor ring 4013 mDrawCursorRing = true; 4014 if (mNativeClass != 0) { 4015 nativeRecordButtons(true, false, true); 4016 if (inEditingMode()) { 4017 mWebViewCore.sendMessage(EventHub.SET_ACTIVE, 1, 0); 4018 } 4019 } 4020 } else { 4021 // If our window gained focus, but we do not have it, do not 4022 // draw the cursor ring. 4023 mDrawCursorRing = false; 4024 // We do not call nativeRecordButtons here because we assume 4025 // that when we lost focus, or window focus, it got called with 4026 // false for the first parameter 4027 } 4028 } else { 4029 if (getSettings().getBuiltInZoomControls() && !mZoomButtonsController.isVisible()) { 4030 /* 4031 * The zoom controls come in their own window, so our window 4032 * loses focus. Our policy is to not draw the cursor ring if 4033 * our window is not focused, but this is an exception since 4034 * the user can still navigate the web page with the zoom 4035 * controls showing. 4036 */ 4037 // If our window has lost focus, stop drawing the cursor ring 4038 mDrawCursorRing = false; 4039 } 4040 mGotKeyDown = false; 4041 mShiftIsPressed = false; 4042 if (mNativeClass != 0) { 4043 nativeRecordButtons(false, false, true); 4044 } 4045 setFocusControllerInactive(); 4046 } 4047 invalidate(); 4048 super.onWindowFocusChanged(hasWindowFocus); 4049 } 4050 4051 /* 4052 * Pass a message to WebCore Thread, telling the WebCore::Page's 4053 * FocusController to be "inactive" so that it will 4054 * not draw the blinking cursor. It gets set to "active" to draw the cursor 4055 * in WebViewCore.cpp, when the WebCore thread receives key events/clicks. 4056 */ 4057 /* package */ void setFocusControllerInactive() { 4058 // Do not need to also check whether mWebViewCore is null, because 4059 // mNativeClass is only set if mWebViewCore is non null 4060 if (mNativeClass == 0) return; 4061 mWebViewCore.sendMessage(EventHub.SET_ACTIVE, 0, 0); 4062 } 4063 4064 @Override 4065 protected void onFocusChanged(boolean focused, int direction, 4066 Rect previouslyFocusedRect) { 4067 if (DebugFlags.WEB_VIEW) { 4068 Log.v(LOGTAG, "MT focusChanged " + focused + ", " + direction); 4069 } 4070 if (focused) { 4071 // When we regain focus, if we have window focus, resume drawing 4072 // the cursor ring 4073 if (hasWindowFocus()) { 4074 mDrawCursorRing = true; 4075 if (mNativeClass != 0) { 4076 nativeRecordButtons(true, false, true); 4077 } 4078 //} else { 4079 // The WebView has gained focus while we do not have 4080 // windowfocus. When our window lost focus, we should have 4081 // called nativeRecordButtons(false...) 4082 } 4083 } else { 4084 // When we lost focus, unless focus went to the TextView (which is 4085 // true if we are in editing mode), stop drawing the cursor ring. 4086 if (!inEditingMode()) { 4087 mDrawCursorRing = false; 4088 if (mNativeClass != 0) { 4089 nativeRecordButtons(false, false, true); 4090 } 4091 setFocusControllerInactive(); 4092 } 4093 mGotKeyDown = false; 4094 } 4095 4096 super.onFocusChanged(focused, direction, previouslyFocusedRect); 4097 } 4098 4099 /** 4100 * @hide 4101 */ 4102 @Override 4103 protected boolean setFrame(int left, int top, int right, int bottom) { 4104 boolean changed = super.setFrame(left, top, right, bottom); 4105 if (!changed && mHeightCanMeasure) { 4106 // When mHeightCanMeasure is true, we will set mLastHeightSent to 0 4107 // in WebViewCore after we get the first layout. We do call 4108 // requestLayout() when we get contentSizeChanged(). But the View 4109 // system won't call onSizeChanged if the dimension is not changed. 4110 // In this case, we need to call sendViewSizeZoom() explicitly to 4111 // notify the WebKit about the new dimensions. 4112 sendViewSizeZoom(); 4113 } 4114 return changed; 4115 } 4116 4117 private static class PostScale implements Runnable { 4118 final WebView mWebView; 4119 final boolean mUpdateTextWrap; 4120 4121 public PostScale(WebView webView, boolean updateTextWrap) { 4122 mWebView = webView; 4123 mUpdateTextWrap = updateTextWrap; 4124 } 4125 4126 public void run() { 4127 if (mWebView.mWebViewCore != null) { 4128 // we always force, in case our height changed, in which case we 4129 // still want to send the notification over to webkit. 4130 mWebView.setNewZoomScale(mWebView.mActualScale, 4131 mUpdateTextWrap, true); 4132 // update the zoom buttons as the scale can be changed 4133 if (mWebView.getSettings().getBuiltInZoomControls()) { 4134 mWebView.updateZoomButtonsEnabled(); 4135 } 4136 } 4137 } 4138 } 4139 4140 @Override 4141 protected void onSizeChanged(int w, int h, int ow, int oh) { 4142 super.onSizeChanged(w, h, ow, oh); 4143 // Center zooming to the center of the screen. 4144 if (mZoomScale == 0) { // unless we're already zooming 4145 // To anchor at top left corner. 4146 mZoomCenterX = 0; 4147 mZoomCenterY = getVisibleTitleHeight(); 4148 mAnchorX = viewToContentX((int) mZoomCenterX + mScrollX); 4149 mAnchorY = viewToContentY((int) mZoomCenterY + mScrollY); 4150 } 4151 4152 // adjust the max viewport width depending on the view dimensions. This 4153 // is to ensure the scaling is not going insane. So do not shrink it if 4154 // the view size is temporarily smaller, e.g. when soft keyboard is up. 4155 int newMaxViewportWidth = (int) (Math.max(w, h) / DEFAULT_MIN_ZOOM_SCALE); 4156 if (newMaxViewportWidth > sMaxViewportWidth) { 4157 sMaxViewportWidth = newMaxViewportWidth; 4158 } 4159 4160 // update mMinZoomScale if the minimum zoom scale is not fixed 4161 if (!mMinZoomScaleFixed) { 4162 // when change from narrow screen to wide screen, the new viewWidth 4163 // can be wider than the old content width. We limit the minimum 4164 // scale to 1.0f. The proper minimum scale will be calculated when 4165 // the new picture shows up. 4166 mMinZoomScale = Math.min(1.0f, (float) getViewWidth() 4167 / (mDrawHistory ? mHistoryPicture.getWidth() 4168 : mZoomOverviewWidth)); 4169 if (mInitialScaleInPercent > 0) { 4170 // limit the minZoomScale to the initialScale if it is set 4171 float initialScale = mInitialScaleInPercent / 100.0f; 4172 if (mMinZoomScale > initialScale) { 4173 mMinZoomScale = initialScale; 4174 } 4175 } 4176 } 4177 4178 // onSizeChanged() is called during WebView layout. And any 4179 // requestLayout() is blocked during layout. As setNewZoomScale() will 4180 // call its child View to reposition itself through ViewManager's 4181 // scaleAll(), we need to post a Runnable to ensure requestLayout(). 4182 // <b/> 4183 // only update the text wrap scale if width changed. 4184 post(new PostScale(this, w != ow)); 4185 } 4186 4187 @Override 4188 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 4189 super.onScrollChanged(l, t, oldl, oldt); 4190 sendOurVisibleRect(); 4191 // update WebKit if visible title bar height changed. The logic is same 4192 // as getVisibleTitleHeight. 4193 int titleHeight = getTitleHeight(); 4194 if (Math.max(titleHeight - t, 0) != Math.max(titleHeight - oldt, 0)) { 4195 sendViewSizeZoom(); 4196 } 4197 } 4198 4199 @Override 4200 public boolean dispatchKeyEvent(KeyEvent event) { 4201 boolean dispatch = true; 4202 4203 // Textfields and plugins need to receive the shift up key even if 4204 // another key was released while the shift key was held down. 4205 if (!inEditingMode() && !nativeFocusIsPlugin()) { 4206 if (event.getAction() == KeyEvent.ACTION_DOWN) { 4207 mGotKeyDown = true; 4208 } else { 4209 if (!mGotKeyDown) { 4210 /* 4211 * We got a key up for which we were not the recipient of 4212 * the original key down. Don't give it to the view. 4213 */ 4214 dispatch = false; 4215 } 4216 mGotKeyDown = false; 4217 } 4218 } 4219 4220 if (dispatch) { 4221 return super.dispatchKeyEvent(event); 4222 } else { 4223 // We didn't dispatch, so let something else handle the key 4224 return false; 4225 } 4226 } 4227 4228 // Here are the snap align logic: 4229 // 1. If it starts nearly horizontally or vertically, snap align; 4230 // 2. If there is a dramitic direction change, let it go; 4231 // 3. If there is a same direction back and forth, lock it. 4232 4233 // adjustable parameters 4234 private int mMinLockSnapReverseDistance; 4235 private static final float MAX_SLOPE_FOR_DIAG = 1.5f; 4236 private static final int MIN_BREAK_SNAP_CROSS_DISTANCE = 80; 4237 4238 private static int sign(float x) { 4239 return x > 0 ? 1 : (x < 0 ? -1 : 0); 4240 } 4241 4242 // if the page can scroll <= this value, we won't allow the drag tracker 4243 // to have any effect. 4244 private static final int MIN_SCROLL_AMOUNT_TO_DISABLE_DRAG_TRACKER = 4; 4245 4246 private class DragTrackerHandler { 4247 private final DragTracker mProxy; 4248 private final float mStartY, mStartX; 4249 private final float mMinDY, mMinDX; 4250 private final float mMaxDY, mMaxDX; 4251 private float mCurrStretchY, mCurrStretchX; 4252 private int mSX, mSY; 4253 private Interpolator mInterp; 4254 private float[] mXY = new float[2]; 4255 4256 // inner (non-state) classes can't have enums :( 4257 private static final int DRAGGING_STATE = 0; 4258 private static final int ANIMATING_STATE = 1; 4259 private static final int FINISHED_STATE = 2; 4260 private int mState; 4261 4262 public DragTrackerHandler(float x, float y, DragTracker proxy) { 4263 mProxy = proxy; 4264 4265 int docBottom = computeVerticalScrollRange() + getTitleHeight(); 4266 int viewTop = getScrollY(); 4267 int viewBottom = viewTop + getHeight(); 4268 4269 mStartY = y; 4270 mMinDY = -viewTop; 4271 mMaxDY = docBottom - viewBottom; 4272 4273 if (DebugFlags.DRAG_TRACKER || DEBUG_DRAG_TRACKER) { 4274 Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, " dragtracker y= " + y + 4275 " up/down= " + mMinDY + " " + mMaxDY); 4276 } 4277 4278 int docRight = computeHorizontalScrollRange(); 4279 int viewLeft = getScrollX(); 4280 int viewRight = viewLeft + getWidth(); 4281 mStartX = x; 4282 mMinDX = -viewLeft; 4283 mMaxDX = docRight - viewRight; 4284 4285 mState = DRAGGING_STATE; 4286 mProxy.onStartDrag(x, y); 4287 4288 // ensure we buildBitmap at least once 4289 mSX = -99999; 4290 } 4291 4292 private float computeStretch(float delta, float min, float max) { 4293 float stretch = 0; 4294 if (max - min > MIN_SCROLL_AMOUNT_TO_DISABLE_DRAG_TRACKER) { 4295 if (delta < min) { 4296 stretch = delta - min; 4297 } else if (delta > max) { 4298 stretch = delta - max; 4299 } 4300 } 4301 return stretch; 4302 } 4303 4304 public void dragTo(float x, float y) { 4305 float sy = computeStretch(mStartY - y, mMinDY, mMaxDY); 4306 float sx = computeStretch(mStartX - x, mMinDX, mMaxDX); 4307 4308 if ((mSnapScrollMode & SNAP_X) != 0) { 4309 sy = 0; 4310 } else if ((mSnapScrollMode & SNAP_Y) != 0) { 4311 sx = 0; 4312 } 4313 4314 if (mCurrStretchX != sx || mCurrStretchY != sy) { 4315 mCurrStretchX = sx; 4316 mCurrStretchY = sy; 4317 if (DebugFlags.DRAG_TRACKER || DEBUG_DRAG_TRACKER) { 4318 Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, "---- stretch " + sx + 4319 " " + sy); 4320 } 4321 if (mProxy.onStretchChange(sx, sy)) { 4322 invalidate(); 4323 } 4324 } 4325 } 4326 4327 public void stopDrag() { 4328 final int DURATION = 200; 4329 int now = (int)SystemClock.uptimeMillis(); 4330 mInterp = new Interpolator(2); 4331 mXY[0] = mCurrStretchX; 4332 mXY[1] = mCurrStretchY; 4333 // float[] blend = new float[] { 0.5f, 0, 0.75f, 1 }; 4334 float[] blend = new float[] { 0, 0.5f, 0.75f, 1 }; 4335 mInterp.setKeyFrame(0, now, mXY, blend); 4336 float[] zerozero = new float[] { 0, 0 }; 4337 mInterp.setKeyFrame(1, now + DURATION, zerozero, null); 4338 mState = ANIMATING_STATE; 4339 4340 if (DebugFlags.DRAG_TRACKER || DEBUG_DRAG_TRACKER) { 4341 Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, "----- stopDrag, starting animation"); 4342 } 4343 } 4344 4345 // Call this after each draw. If it ruturns null, the tracker is done 4346 public boolean isFinished() { 4347 return mState == FINISHED_STATE; 4348 } 4349 4350 private int hiddenHeightOfTitleBar() { 4351 return getTitleHeight() - getVisibleTitleHeight(); 4352 } 4353 4354 // need a way to know if 565 or 8888 is the right config for 4355 // capturing the display and giving it to the drag proxy 4356 private Bitmap.Config offscreenBitmapConfig() { 4357 // hard code 565 for now 4358 return Bitmap.Config.RGB_565; 4359 } 4360 4361 /* If the tracker draws, then this returns true, otherwise it will 4362 return false, and draw nothing. 4363 */ 4364 public boolean draw(Canvas canvas) { 4365 if (mCurrStretchX != 0 || mCurrStretchY != 0) { 4366 int sx = getScrollX(); 4367 int sy = getScrollY() - hiddenHeightOfTitleBar(); 4368 if (mSX != sx || mSY != sy) { 4369 buildBitmap(sx, sy); 4370 mSX = sx; 4371 mSY = sy; 4372 } 4373 4374 if (mState == ANIMATING_STATE) { 4375 Interpolator.Result result = mInterp.timeToValues(mXY); 4376 if (result == Interpolator.Result.FREEZE_END) { 4377 mState = FINISHED_STATE; 4378 return false; 4379 } else { 4380 mProxy.onStretchChange(mXY[0], mXY[1]); 4381 invalidate(); 4382 // fall through to the draw 4383 } 4384 } 4385 int count = canvas.save(Canvas.MATRIX_SAVE_FLAG); 4386 canvas.translate(sx, sy); 4387 mProxy.onDraw(canvas); 4388 canvas.restoreToCount(count); 4389 return true; 4390 } 4391 if (DebugFlags.DRAG_TRACKER || DEBUG_DRAG_TRACKER) { 4392 Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, " -- draw false " + 4393 mCurrStretchX + " " + mCurrStretchY); 4394 } 4395 return false; 4396 } 4397 4398 private void buildBitmap(int sx, int sy) { 4399 int w = getWidth(); 4400 int h = getViewHeight(); 4401 Bitmap bm = Bitmap.createBitmap(w, h, offscreenBitmapConfig()); 4402 Canvas canvas = new Canvas(bm); 4403 canvas.translate(-sx, -sy); 4404 drawContent(canvas); 4405 4406 if (DebugFlags.DRAG_TRACKER || DEBUG_DRAG_TRACKER) { 4407 Log.d(DebugFlags.DRAG_TRACKER_LOGTAG, "--- buildBitmap " + sx + 4408 " " + sy + " " + w + " " + h); 4409 } 4410 mProxy.onBitmapChange(bm); 4411 } 4412 } 4413 4414 /** @hide */ 4415 public static class DragTracker { 4416 public void onStartDrag(float x, float y) {} 4417 public boolean onStretchChange(float sx, float sy) { 4418 // return true to have us inval the view 4419 return false; 4420 } 4421 public void onStopDrag() {} 4422 public void onBitmapChange(Bitmap bm) {} 4423 public void onDraw(Canvas canvas) {} 4424 } 4425 4426 /** @hide */ 4427 public DragTracker getDragTracker() { 4428 return mDragTracker; 4429 } 4430 4431 /** @hide */ 4432 public void setDragTracker(DragTracker tracker) { 4433 mDragTracker = tracker; 4434 } 4435 4436 private DragTracker mDragTracker; 4437 private DragTrackerHandler mDragTrackerHandler; 4438 4439 private class ScaleDetectorListener implements 4440 ScaleGestureDetector.OnScaleGestureListener { 4441 4442 public boolean onScaleBegin(ScaleGestureDetector detector) { 4443 // cancel the single touch handling 4444 cancelTouch(); 4445 if (mZoomButtonsController.isVisible()) { 4446 mZoomButtonsController.setVisible(false); 4447 } 4448 // reset the zoom overview mode so that the page won't auto grow 4449 mInZoomOverview = false; 4450 // If it is in password mode, turn it off so it does not draw 4451 // misplaced. 4452 if (inEditingMode() && nativeFocusCandidateIsPassword()) { 4453 mWebTextView.setInPassword(false); 4454 } 4455 return true; 4456 } 4457 4458 public void onScaleEnd(ScaleGestureDetector detector) { 4459 if (mPreviewZoomOnly) { 4460 mPreviewZoomOnly = false; 4461 mAnchorX = viewToContentX((int) mZoomCenterX + mScrollX); 4462 mAnchorY = viewToContentY((int) mZoomCenterY + mScrollY); 4463 // don't reflow when zoom in; when zoom out, do reflow if the 4464 // new scale is almost minimum scale; 4465 boolean reflowNow = (mActualScale - mMinZoomScale <= 0.01f) 4466 || ((mActualScale <= 0.8 * mTextWrapScale)); 4467 // force zoom after mPreviewZoomOnly is set to false so that the 4468 // new view size will be passed to the WebKit 4469 setNewZoomScale(mActualScale, reflowNow, true); 4470 // call invalidate() to draw without zoom filter 4471 invalidate(); 4472 } 4473 // adjust the edit text view if needed 4474 if (inEditingMode() && didUpdateTextViewBounds(false) 4475 && nativeFocusCandidateIsPassword()) { 4476 // If it is a password field, start drawing the 4477 // WebTextView once again. 4478 mWebTextView.setInPassword(true); 4479 } 4480 // start a drag, TOUCH_PINCH_DRAG, can't use TOUCH_INIT_MODE as it 4481 // may trigger the unwanted click, can't use TOUCH_DRAG_MODE as it 4482 // may trigger the unwanted fling. 4483 mTouchMode = TOUCH_PINCH_DRAG; 4484 mConfirmMove = true; 4485 startTouch(detector.getFocusX(), detector.getFocusY(), 4486 mLastTouchTime); 4487 } 4488 4489 public boolean onScale(ScaleGestureDetector detector) { 4490 float scale = (float) (Math.round(detector.getScaleFactor() 4491 * mActualScale * 100) / 100.0); 4492 if (Math.abs(scale - mActualScale) >= PREVIEW_SCALE_INCREMENT) { 4493 mPreviewZoomOnly = true; 4494 // limit the scale change per step 4495 if (scale > mActualScale) { 4496 scale = Math.min(scale, mActualScale * 1.25f); 4497 } else { 4498 scale = Math.max(scale, mActualScale * 0.8f); 4499 } 4500 mZoomCenterX = detector.getFocusX(); 4501 mZoomCenterY = detector.getFocusY(); 4502 setNewZoomScale(scale, false, false); 4503 invalidate(); 4504 return true; 4505 } 4506 return false; 4507 } 4508 } 4509 4510 private boolean hitFocusedPlugin(int contentX, int contentY) { 4511 return nativeFocusIsPlugin() 4512 && nativePointInNavCache(contentX, contentY, mNavSlop) 4513 && nativeCacheHitNodePointer() == nativeFocusNodePointer(); 4514 } 4515 4516 private boolean shouldForwardTouchEvent() { 4517 return mFullScreenHolder != null || (mForwardTouchEvents 4518 && mTouchMode != TOUCH_SELECT_MODE 4519 && mPreventDefault != PREVENT_DEFAULT_IGNORE); 4520 } 4521 4522 private boolean inFullScreenMode() { 4523 return mFullScreenHolder != null; 4524 } 4525 4526 @Override 4527 public boolean onTouchEvent(MotionEvent ev) { 4528 if (mNativeClass == 0 || !isClickable() || !isLongClickable()) { 4529 return false; 4530 } 4531 4532 if (DebugFlags.WEB_VIEW) { 4533 Log.v(LOGTAG, ev + " at " + ev.getEventTime() + " mTouchMode=" 4534 + mTouchMode); 4535 } 4536 4537 int action; 4538 float x, y; 4539 long eventTime = ev.getEventTime(); 4540 4541 // FIXME: we may consider to give WebKit an option to handle multi-touch 4542 // events later. 4543 if (mSupportMultiTouch && ev.getPointerCount() > 1) { 4544 if (mMinZoomScale < mMaxZoomScale) { 4545 mScaleDetector.onTouchEvent(ev); 4546 if (mScaleDetector.isInProgress()) { 4547 mLastTouchTime = eventTime; 4548 return true; 4549 } 4550 x = mScaleDetector.getFocusX(); 4551 y = mScaleDetector.getFocusY(); 4552 action = ev.getAction() & MotionEvent.ACTION_MASK; 4553 if (action == MotionEvent.ACTION_POINTER_DOWN) { 4554 cancelTouch(); 4555 action = MotionEvent.ACTION_DOWN; 4556 } else if (action == MotionEvent.ACTION_POINTER_UP) { 4557 // set mLastTouchX/Y to the remaining point 4558 mLastTouchX = x; 4559 mLastTouchY = y; 4560 } else if (action == MotionEvent.ACTION_MOVE) { 4561 // negative x or y indicate it is on the edge, skip it. 4562 if (x < 0 || y < 0) { 4563 return true; 4564 } 4565 } 4566 } else { 4567 // if the page disallow zoom, skip multi-pointer action 4568 return true; 4569 } 4570 } else { 4571 action = ev.getAction(); 4572 x = ev.getX(); 4573 y = ev.getY(); 4574 } 4575 4576 // Due to the touch screen edge effect, a touch closer to the edge 4577 // always snapped to the edge. As getViewWidth() can be different from 4578 // getWidth() due to the scrollbar, adjusting the point to match 4579 // getViewWidth(). Same applied to the height. 4580 if (x > getViewWidth() - 1) { 4581 x = getViewWidth() - 1; 4582 } 4583 if (y > getViewHeightWithTitle() - 1) { 4584 y = getViewHeightWithTitle() - 1; 4585 } 4586 4587 float fDeltaX = mLastTouchX - x; 4588 float fDeltaY = mLastTouchY - y; 4589 int deltaX = (int) fDeltaX; 4590 int deltaY = (int) fDeltaY; 4591 int contentX = viewToContentX((int) x + mScrollX); 4592 int contentY = viewToContentY((int) y + mScrollY); 4593 4594 switch (action) { 4595 case MotionEvent.ACTION_DOWN: { 4596 mPreventDefault = PREVENT_DEFAULT_NO; 4597 mConfirmMove = false; 4598 if (!mScroller.isFinished()) { 4599 // stop the current scroll animation, but if this is 4600 // the start of a fling, allow it to add to the current 4601 // fling's velocity 4602 mScroller.abortAnimation(); 4603 mTouchMode = TOUCH_DRAG_START_MODE; 4604 mConfirmMove = true; 4605 mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY); 4606 } else if (!inFullScreenMode() && mShiftIsPressed) { 4607 mSelectX = mScrollX + (int) x; 4608 mSelectY = mScrollY + (int) y; 4609 mTouchMode = TOUCH_SELECT_MODE; 4610 if (DebugFlags.WEB_VIEW) { 4611 Log.v(LOGTAG, "select=" + mSelectX + "," + mSelectY); 4612 } 4613 nativeMoveSelection(contentX, contentY, false); 4614 mTouchSelection = mExtendSelection = true; 4615 invalidate(); // draw the i-beam instead of the arrow 4616 } else if (mPrivateHandler.hasMessages(RELEASE_SINGLE_TAP)) { 4617 mPrivateHandler.removeMessages(RELEASE_SINGLE_TAP); 4618 if (deltaX * deltaX + deltaY * deltaY < mDoubleTapSlopSquare) { 4619 mTouchMode = TOUCH_DOUBLE_TAP_MODE; 4620 } else { 4621 // commit the short press action for the previous tap 4622 doShortPress(); 4623 mTouchMode = TOUCH_INIT_MODE; 4624 mDeferTouchProcess = (!inFullScreenMode() 4625 && mForwardTouchEvents) ? hitFocusedPlugin( 4626 contentX, contentY) : false; 4627 } 4628 } else { // the normal case 4629 mPreviewZoomOnly = false; 4630 mTouchMode = TOUCH_INIT_MODE; 4631 mDeferTouchProcess = (!inFullScreenMode() 4632 && mForwardTouchEvents) ? hitFocusedPlugin( 4633 contentX, contentY) : false; 4634 mWebViewCore.sendMessage( 4635 EventHub.UPDATE_FRAME_CACHE_IF_LOADING); 4636 if (mLogEvent && eventTime - mLastTouchUpTime < 1000) { 4637 EventLog.writeEvent(EventLogTags.BROWSER_DOUBLE_TAP_DURATION, 4638 (eventTime - mLastTouchUpTime), eventTime); 4639 } 4640 } 4641 // Trigger the link 4642 if (mTouchMode == TOUCH_INIT_MODE 4643 || mTouchMode == TOUCH_DOUBLE_TAP_MODE) { 4644 mPrivateHandler.sendEmptyMessageDelayed( 4645 SWITCH_TO_SHORTPRESS, TAP_TIMEOUT); 4646 mPrivateHandler.sendEmptyMessageDelayed( 4647 SWITCH_TO_LONGPRESS, LONG_PRESS_TIMEOUT); 4648 if (inFullScreenMode() || mDeferTouchProcess) { 4649 mPreventDefault = PREVENT_DEFAULT_YES; 4650 } else if (mForwardTouchEvents) { 4651 mPreventDefault = PREVENT_DEFAULT_MAYBE_YES; 4652 } else { 4653 mPreventDefault = PREVENT_DEFAULT_NO; 4654 } 4655 // pass the touch events from UI thread to WebCore thread 4656 if (shouldForwardTouchEvent()) { 4657 TouchEventData ted = new TouchEventData(); 4658 ted.mAction = action; 4659 ted.mX = contentX; 4660 ted.mY = contentY; 4661 ted.mMetaState = ev.getMetaState(); 4662 ted.mReprocess = mDeferTouchProcess; 4663 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 4664 if (mDeferTouchProcess) { 4665 // still needs to set them for compute deltaX/Y 4666 mLastTouchX = x; 4667 mLastTouchY = y; 4668 break; 4669 } 4670 if (!inFullScreenMode()) { 4671 mPrivateHandler.sendMessageDelayed(mPrivateHandler 4672 .obtainMessage(PREVENT_DEFAULT_TIMEOUT, 4673 action, 0), TAP_TIMEOUT); 4674 } 4675 } 4676 } 4677 startTouch(x, y, eventTime); 4678 break; 4679 } 4680 case MotionEvent.ACTION_MOVE: { 4681 boolean firstMove = false; 4682 if (!mConfirmMove && (deltaX * deltaX + deltaY * deltaY) 4683 >= mTouchSlopSquare) { 4684 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 4685 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 4686 mConfirmMove = true; 4687 firstMove = true; 4688 if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) { 4689 mTouchMode = TOUCH_INIT_MODE; 4690 } 4691 } 4692 // pass the touch events from UI thread to WebCore thread 4693 if (shouldForwardTouchEvent() && mConfirmMove && (firstMove 4694 || eventTime - mLastSentTouchTime > mCurrentTouchInterval)) { 4695 TouchEventData ted = new TouchEventData(); 4696 ted.mAction = action; 4697 ted.mX = contentX; 4698 ted.mY = contentY; 4699 ted.mMetaState = ev.getMetaState(); 4700 ted.mReprocess = mDeferTouchProcess; 4701 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 4702 mLastSentTouchTime = eventTime; 4703 if (mDeferTouchProcess) { 4704 break; 4705 } 4706 if (firstMove && !inFullScreenMode()) { 4707 mPrivateHandler.sendMessageDelayed(mPrivateHandler 4708 .obtainMessage(PREVENT_DEFAULT_TIMEOUT, 4709 action, 0), TAP_TIMEOUT); 4710 } 4711 } 4712 if (mTouchMode == TOUCH_DONE_MODE 4713 || mPreventDefault == PREVENT_DEFAULT_YES) { 4714 // no dragging during scroll zoom animation, or when prevent 4715 // default is yes 4716 break; 4717 } 4718 if (mVelocityTracker == null) { 4719 Log.e(LOGTAG, "Got null mVelocityTracker when " 4720 + "mPreventDefault = " + mPreventDefault 4721 + " mDeferTouchProcess = " + mDeferTouchProcess 4722 + " mTouchMode = " + mTouchMode); 4723 } 4724 mVelocityTracker.addMovement(ev); 4725 if (mTouchMode != TOUCH_DRAG_MODE) { 4726 if (mTouchMode == TOUCH_SELECT_MODE) { 4727 mSelectX = mScrollX + (int) x; 4728 mSelectY = mScrollY + (int) y; 4729 if (DebugFlags.WEB_VIEW) { 4730 Log.v(LOGTAG, "xtend=" + mSelectX + "," + mSelectY); 4731 } 4732 nativeMoveSelection(contentX, contentY, true); 4733 invalidate(); 4734 break; 4735 } 4736 if (!mConfirmMove) { 4737 break; 4738 } 4739 if (mPreventDefault == PREVENT_DEFAULT_MAYBE_YES 4740 || mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN) { 4741 // track mLastTouchTime as we may need to do fling at 4742 // ACTION_UP 4743 mLastTouchTime = eventTime; 4744 break; 4745 } 4746 // if it starts nearly horizontal or vertical, enforce it 4747 int ax = Math.abs(deltaX); 4748 int ay = Math.abs(deltaY); 4749 if (ax > MAX_SLOPE_FOR_DIAG * ay) { 4750 mSnapScrollMode = SNAP_X; 4751 mSnapPositive = deltaX > 0; 4752 } else if (ay > MAX_SLOPE_FOR_DIAG * ax) { 4753 mSnapScrollMode = SNAP_Y; 4754 mSnapPositive = deltaY > 0; 4755 } 4756 4757 mTouchMode = TOUCH_DRAG_MODE; 4758 mLastTouchX = x; 4759 mLastTouchY = y; 4760 fDeltaX = 0.0f; 4761 fDeltaY = 0.0f; 4762 deltaX = 0; 4763 deltaY = 0; 4764 4765 startDrag(); 4766 } 4767 4768 if (mDragTrackerHandler != null) { 4769 mDragTrackerHandler.dragTo(x, y); 4770 } 4771 4772 // do pan 4773 boolean done = false; 4774 boolean keepScrollBarsVisible = false; 4775 if (Math.abs(fDeltaX) < 1.0f && Math.abs(fDeltaY) < 1.0f) { 4776 keepScrollBarsVisible = done = true; 4777 } else { 4778 if (mSnapScrollMode == SNAP_X || mSnapScrollMode == SNAP_Y) { 4779 int ax = Math.abs(deltaX); 4780 int ay = Math.abs(deltaY); 4781 if (mSnapScrollMode == SNAP_X) { 4782 // radical change means getting out of snap mode 4783 if (ay > MAX_SLOPE_FOR_DIAG * ax 4784 && ay > MIN_BREAK_SNAP_CROSS_DISTANCE) { 4785 mSnapScrollMode = SNAP_NONE; 4786 } 4787 // reverse direction means lock in the snap mode 4788 if (ax > MAX_SLOPE_FOR_DIAG * ay && 4789 (mSnapPositive 4790 ? deltaX < -mMinLockSnapReverseDistance 4791 : deltaX > mMinLockSnapReverseDistance)) { 4792 mSnapScrollMode |= SNAP_LOCK; 4793 } 4794 } else { 4795 // radical change means getting out of snap mode 4796 if (ax > MAX_SLOPE_FOR_DIAG * ay 4797 && ax > MIN_BREAK_SNAP_CROSS_DISTANCE) { 4798 mSnapScrollMode = SNAP_NONE; 4799 } 4800 // reverse direction means lock in the snap mode 4801 if (ay > MAX_SLOPE_FOR_DIAG * ax && 4802 (mSnapPositive 4803 ? deltaY < -mMinLockSnapReverseDistance 4804 : deltaY > mMinLockSnapReverseDistance)) { 4805 mSnapScrollMode |= SNAP_LOCK; 4806 } 4807 } 4808 } 4809 if (mSnapScrollMode != SNAP_NONE) { 4810 if ((mSnapScrollMode & SNAP_X) == SNAP_X) { 4811 deltaY = 0; 4812 } else { 4813 deltaX = 0; 4814 } 4815 } 4816 if ((deltaX | deltaY) != 0) { 4817 if (deltaX != 0) { 4818 mLastTouchX = x; 4819 } 4820 if (deltaY != 0) { 4821 mLastTouchY = y; 4822 } 4823 mHeldMotionless = MOTIONLESS_FALSE; 4824 } else { 4825 // keep the scrollbar on the screen even there is no 4826 // scroll 4827 keepScrollBarsVisible = true; 4828 } 4829 mLastTouchTime = eventTime; 4830 mUserScroll = true; 4831 } 4832 4833 doDrag(deltaX, deltaY); 4834 4835 if (keepScrollBarsVisible) { 4836 if (mHeldMotionless != MOTIONLESS_TRUE) { 4837 mHeldMotionless = MOTIONLESS_TRUE; 4838 invalidate(); 4839 } 4840 // keep the scrollbar on the screen even there is no scroll 4841 awakenScrollBars(ViewConfiguration.getScrollDefaultDelay(), 4842 false); 4843 // return false to indicate that we can't pan out of the 4844 // view space 4845 return !done; 4846 } 4847 break; 4848 } 4849 case MotionEvent.ACTION_UP: { 4850 // pass the touch events from UI thread to WebCore thread 4851 if (shouldForwardTouchEvent()) { 4852 TouchEventData ted = new TouchEventData(); 4853 ted.mAction = action; 4854 ted.mX = contentX; 4855 ted.mY = contentY; 4856 ted.mMetaState = ev.getMetaState(); 4857 ted.mReprocess = mDeferTouchProcess; 4858 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 4859 } 4860 mLastTouchUpTime = eventTime; 4861 switch (mTouchMode) { 4862 case TOUCH_DOUBLE_TAP_MODE: // double tap 4863 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 4864 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 4865 if (inFullScreenMode() || mDeferTouchProcess) { 4866 TouchEventData ted = new TouchEventData(); 4867 ted.mAction = WebViewCore.ACTION_DOUBLETAP; 4868 ted.mX = contentX; 4869 ted.mY = contentY; 4870 ted.mMetaState = ev.getMetaState(); 4871 ted.mReprocess = mDeferTouchProcess; 4872 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 4873 } else if (mPreventDefault != PREVENT_DEFAULT_YES){ 4874 doDoubleTap(); 4875 mTouchMode = TOUCH_DONE_MODE; 4876 } 4877 break; 4878 case TOUCH_SELECT_MODE: 4879 commitCopy(); 4880 mTouchSelection = false; 4881 break; 4882 case TOUCH_INIT_MODE: // tap 4883 case TOUCH_SHORTPRESS_START_MODE: 4884 case TOUCH_SHORTPRESS_MODE: 4885 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 4886 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 4887 if (mConfirmMove) { 4888 Log.w(LOGTAG, "Miss a drag as we are waiting for" + 4889 " WebCore's response for touch down."); 4890 if (mPreventDefault != PREVENT_DEFAULT_YES 4891 && (computeMaxScrollX() > 0 4892 || computeMaxScrollY() > 0)) { 4893 // UI takes control back, cancel WebCore touch 4894 cancelWebCoreTouchEvent(contentX, contentY, 4895 true); 4896 // we will not rewrite drag code here, but we 4897 // will try fling if it applies. 4898 WebViewCore.reducePriority(); 4899 // fall through to TOUCH_DRAG_MODE 4900 } else { 4901 break; 4902 } 4903 } else { 4904 if (mTouchMode == TOUCH_INIT_MODE) { 4905 mPrivateHandler.sendEmptyMessageDelayed( 4906 RELEASE_SINGLE_TAP, ViewConfiguration 4907 .getDoubleTapTimeout()); 4908 } else { 4909 doShortPress(); 4910 } 4911 break; 4912 } 4913 case TOUCH_DRAG_MODE: 4914 mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS); 4915 mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS); 4916 mHeldMotionless = MOTIONLESS_TRUE; 4917 // redraw in high-quality, as we're done dragging 4918 invalidate(); 4919 // if the user waits a while w/o moving before the 4920 // up, we don't want to do a fling 4921 if (eventTime - mLastTouchTime <= MIN_FLING_TIME) { 4922 if (mVelocityTracker == null) { 4923 Log.e(LOGTAG, "Got null mVelocityTracker when " 4924 + "mPreventDefault = " 4925 + mPreventDefault 4926 + " mDeferTouchProcess = " 4927 + mDeferTouchProcess); 4928 } 4929 mVelocityTracker.addMovement(ev); 4930 doFling(); 4931 break; 4932 } else { 4933 if (mScroller.springback(mScrollX, mScrollY, 0, 4934 computeMaxScrollX(), 0, 4935 computeMaxScrollY())) { 4936 invalidate(); 4937 } 4938 } 4939 mLastVelocity = 0; 4940 WebViewCore.resumePriority(); 4941 break; 4942 } 4943 stopTouch(); 4944 break; 4945 } 4946 case MotionEvent.ACTION_CANCEL: { 4947 if (mTouchMode == TOUCH_DRAG_MODE) { 4948 mScroller.springback(mScrollX, mScrollY, 0, 4949 computeMaxScrollX(), 0, computeMaxScrollY()); 4950 invalidate(); 4951 } 4952 cancelWebCoreTouchEvent(contentX, contentY, false); 4953 cancelTouch(); 4954 break; 4955 } 4956 } 4957 return true; 4958 } 4959 4960 private void cancelWebCoreTouchEvent(int x, int y, boolean removeEvents) { 4961 if (shouldForwardTouchEvent()) { 4962 if (removeEvents) { 4963 mWebViewCore.removeMessages(EventHub.TOUCH_EVENT); 4964 } 4965 TouchEventData ted = new TouchEventData(); 4966 ted.mX = x; 4967 ted.mY = y; 4968 ted.mAction = MotionEvent.ACTION_CANCEL; 4969 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 4970 mPreventDefault = PREVENT_DEFAULT_IGNORE; 4971 } 4972 } 4973 4974 private void startTouch(float x, float y, long eventTime) { 4975 // Remember where the motion event started 4976 mLastTouchX = x; 4977 mLastTouchY = y; 4978 mLastTouchTime = eventTime; 4979 mVelocityTracker = VelocityTracker.obtain(); 4980 mSnapScrollMode = SNAP_NONE; 4981 if (mDragTracker != null) { 4982 mDragTrackerHandler = new DragTrackerHandler(x, y, mDragTracker); 4983 } 4984 } 4985 4986 private void startDrag() { 4987 WebViewCore.reducePriority(); 4988 if (!mDragFromTextInput) { 4989 nativeHideCursor(); 4990 } 4991 WebSettings settings = getSettings(); 4992 if (settings.supportZoom() 4993 && settings.getBuiltInZoomControls() 4994 && !mZoomButtonsController.isVisible() 4995 && mMinZoomScale < mMaxZoomScale) { 4996 mZoomButtonsController.setVisible(true); 4997 int count = settings.getDoubleTapToastCount(); 4998 if (mInZoomOverview && count > 0) { 4999 settings.setDoubleTapToastCount(--count); 5000 Toast.makeText(mContext, 5001 com.android.internal.R.string.double_tap_toast, 5002 Toast.LENGTH_LONG).show(); 5003 } 5004 } 5005 } 5006 5007 private void doDrag(int deltaX, int deltaY) { 5008 if ((deltaX | deltaY) != 0) { 5009 overscrollBy(deltaX, deltaY, mScrollX, mScrollY, 5010 computeMaxScrollX(), computeMaxScrollY(), 5011 getViewWidth() / 3, getViewHeight() / 3); 5012 } 5013 if (!getSettings().getBuiltInZoomControls()) { 5014 boolean showPlusMinus = mMinZoomScale < mMaxZoomScale; 5015 if (mZoomControls != null && showPlusMinus) { 5016 if (mZoomControls.getVisibility() == View.VISIBLE) { 5017 mPrivateHandler.removeCallbacks(mZoomControlRunnable); 5018 } else { 5019 mZoomControls.show(showPlusMinus, false); 5020 } 5021 mPrivateHandler.postDelayed(mZoomControlRunnable, 5022 ZOOM_CONTROLS_TIMEOUT); 5023 } 5024 } 5025 } 5026 5027 private void stopTouch() { 5028 if (mDragTrackerHandler != null) { 5029 mDragTrackerHandler.stopDrag(); 5030 } 5031 // we also use mVelocityTracker == null to tell us that we are 5032 // not "moving around", so we can take the slower/prettier 5033 // mode in the drawing code 5034 if (mVelocityTracker != null) { 5035 mVelocityTracker.recycle(); 5036 mVelocityTracker = null; 5037 } 5038 } 5039 5040 private void cancelTouch() { 5041 if (mDragTrackerHandler != null) { 5042 mDragTrackerHandler.stopDrag(); 5043 } 5044 // we also use mVelocityTracker == null to tell us that we are 5045 // not "moving around", so we can take the slower/prettier 5046 // mode in the drawing code 5047 if (mVelocityTracker != null) { 5048 mVelocityTracker.recycle(); 5049 mVelocityTracker = null; 5050 } 5051 if (mTouchMode == TOUCH_DRAG_MODE) { 5052 WebViewCore.resumePriority(); 5053 } 5054 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 5055 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 5056 mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS); 5057 mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS); 5058 mHeldMotionless = MOTIONLESS_TRUE; 5059 mTouchMode = TOUCH_DONE_MODE; 5060 nativeHideCursor(); 5061 } 5062 5063 private long mTrackballFirstTime = 0; 5064 private long mTrackballLastTime = 0; 5065 private float mTrackballRemainsX = 0.0f; 5066 private float mTrackballRemainsY = 0.0f; 5067 private int mTrackballXMove = 0; 5068 private int mTrackballYMove = 0; 5069 private boolean mExtendSelection = false; 5070 private boolean mTouchSelection = false; 5071 private static final int TRACKBALL_KEY_TIMEOUT = 1000; 5072 private static final int TRACKBALL_TIMEOUT = 200; 5073 private static final int TRACKBALL_WAIT = 100; 5074 private static final int TRACKBALL_SCALE = 400; 5075 private static final int TRACKBALL_SCROLL_COUNT = 5; 5076 private static final int TRACKBALL_MOVE_COUNT = 10; 5077 private static final int TRACKBALL_MULTIPLIER = 3; 5078 private static final int SELECT_CURSOR_OFFSET = 16; 5079 private int mSelectX = 0; 5080 private int mSelectY = 0; 5081 private boolean mFocusSizeChanged = false; 5082 private boolean mShiftIsPressed = false; 5083 private boolean mTrackballDown = false; 5084 private long mTrackballUpTime = 0; 5085 private long mLastCursorTime = 0; 5086 private Rect mLastCursorBounds; 5087 5088 // Set by default; BrowserActivity clears to interpret trackball data 5089 // directly for movement. Currently, the framework only passes 5090 // arrow key events, not trackball events, from one child to the next 5091 private boolean mMapTrackballToArrowKeys = true; 5092 5093 public void setMapTrackballToArrowKeys(boolean setMap) { 5094 mMapTrackballToArrowKeys = setMap; 5095 } 5096 5097 void resetTrackballTime() { 5098 mTrackballLastTime = 0; 5099 } 5100 5101 @Override 5102 public boolean onTrackballEvent(MotionEvent ev) { 5103 long time = ev.getEventTime(); 5104 if ((ev.getMetaState() & KeyEvent.META_ALT_ON) != 0) { 5105 if (ev.getY() > 0) pageDown(true); 5106 if (ev.getY() < 0) pageUp(true); 5107 return true; 5108 } 5109 if (ev.getAction() == MotionEvent.ACTION_DOWN) { 5110 if (mShiftIsPressed && !nativeFocusIsPlugin()) { 5111 return true; // discard press if copy in progress 5112 } 5113 mTrackballDown = true; 5114 if (mNativeClass == 0) { 5115 return false; 5116 } 5117 nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true); 5118 if (time - mLastCursorTime <= TRACKBALL_TIMEOUT 5119 && !mLastCursorBounds.equals(nativeGetCursorRingBounds())) { 5120 nativeSelectBestAt(mLastCursorBounds); 5121 } 5122 if (DebugFlags.WEB_VIEW) { 5123 Log.v(LOGTAG, "onTrackballEvent down ev=" + ev 5124 + " time=" + time 5125 + " mLastCursorTime=" + mLastCursorTime); 5126 } 5127 if (isInTouchMode()) requestFocusFromTouch(); 5128 return false; // let common code in onKeyDown at it 5129 } 5130 if (ev.getAction() == MotionEvent.ACTION_UP) { 5131 // LONG_PRESS_CENTER is set in common onKeyDown 5132 mPrivateHandler.removeMessages(LONG_PRESS_CENTER); 5133 mTrackballDown = false; 5134 mTrackballUpTime = time; 5135 if (mShiftIsPressed && !nativeFocusIsPlugin()) { 5136 if (mExtendSelection) { 5137 commitCopy(); 5138 } else { 5139 mExtendSelection = true; 5140 invalidate(); // draw the i-beam instead of the arrow 5141 } 5142 return true; // discard press if copy in progress 5143 } 5144 if (DebugFlags.WEB_VIEW) { 5145 Log.v(LOGTAG, "onTrackballEvent up ev=" + ev 5146 + " time=" + time 5147 ); 5148 } 5149 return false; // let common code in onKeyUp at it 5150 } 5151 if (mMapTrackballToArrowKeys && mShiftIsPressed == false) { 5152 if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent gmail quit"); 5153 return false; 5154 } 5155 if (mTrackballDown) { 5156 if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent down quit"); 5157 return true; // discard move if trackball is down 5158 } 5159 if (time - mTrackballUpTime < TRACKBALL_TIMEOUT) { 5160 if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent up timeout quit"); 5161 return true; 5162 } 5163 // TODO: alternatively we can do panning as touch does 5164 switchOutDrawHistory(); 5165 if (time - mTrackballLastTime > TRACKBALL_TIMEOUT) { 5166 if (DebugFlags.WEB_VIEW) { 5167 Log.v(LOGTAG, "onTrackballEvent time=" 5168 + time + " last=" + mTrackballLastTime); 5169 } 5170 mTrackballFirstTime = time; 5171 mTrackballXMove = mTrackballYMove = 0; 5172 } 5173 mTrackballLastTime = time; 5174 if (DebugFlags.WEB_VIEW) { 5175 Log.v(LOGTAG, "onTrackballEvent ev=" + ev + " time=" + time); 5176 } 5177 mTrackballRemainsX += ev.getX(); 5178 mTrackballRemainsY += ev.getY(); 5179 doTrackball(time); 5180 return true; 5181 } 5182 5183 void moveSelection(float xRate, float yRate) { 5184 if (mNativeClass == 0) 5185 return; 5186 int width = getViewWidth(); 5187 int height = getViewHeight(); 5188 mSelectX += xRate; 5189 mSelectY += yRate; 5190 int maxX = width + mScrollX; 5191 int maxY = height + mScrollY; 5192 mSelectX = Math.min(maxX, Math.max(mScrollX - SELECT_CURSOR_OFFSET 5193 , mSelectX)); 5194 mSelectY = Math.min(maxY, Math.max(mScrollY - SELECT_CURSOR_OFFSET 5195 , mSelectY)); 5196 if (DebugFlags.WEB_VIEW) { 5197 Log.v(LOGTAG, "moveSelection" 5198 + " mSelectX=" + mSelectX 5199 + " mSelectY=" + mSelectY 5200 + " mScrollX=" + mScrollX 5201 + " mScrollY=" + mScrollY 5202 + " xRate=" + xRate 5203 + " yRate=" + yRate 5204 ); 5205 } 5206 nativeMoveSelection(viewToContentX(mSelectX), 5207 viewToContentY(mSelectY), mExtendSelection); 5208 int scrollX = mSelectX < mScrollX ? -SELECT_CURSOR_OFFSET 5209 : mSelectX > maxX - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET 5210 : 0; 5211 int scrollY = mSelectY < mScrollY ? -SELECT_CURSOR_OFFSET 5212 : mSelectY > maxY - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET 5213 : 0; 5214 pinScrollBy(scrollX, scrollY, true, 0); 5215 Rect select = new Rect(mSelectX, mSelectY, mSelectX + 1, mSelectY + 1); 5216 requestRectangleOnScreen(select); 5217 invalidate(); 5218 } 5219 5220 private int scaleTrackballX(float xRate, int width) { 5221 int xMove = (int) (xRate / TRACKBALL_SCALE * width); 5222 int nextXMove = xMove; 5223 if (xMove > 0) { 5224 if (xMove > mTrackballXMove) { 5225 xMove -= mTrackballXMove; 5226 } 5227 } else if (xMove < mTrackballXMove) { 5228 xMove -= mTrackballXMove; 5229 } 5230 mTrackballXMove = nextXMove; 5231 return xMove; 5232 } 5233 5234 private int scaleTrackballY(float yRate, int height) { 5235 int yMove = (int) (yRate / TRACKBALL_SCALE * height); 5236 int nextYMove = yMove; 5237 if (yMove > 0) { 5238 if (yMove > mTrackballYMove) { 5239 yMove -= mTrackballYMove; 5240 } 5241 } else if (yMove < mTrackballYMove) { 5242 yMove -= mTrackballYMove; 5243 } 5244 mTrackballYMove = nextYMove; 5245 return yMove; 5246 } 5247 5248 private int keyCodeToSoundsEffect(int keyCode) { 5249 switch(keyCode) { 5250 case KeyEvent.KEYCODE_DPAD_UP: 5251 return SoundEffectConstants.NAVIGATION_UP; 5252 case KeyEvent.KEYCODE_DPAD_RIGHT: 5253 return SoundEffectConstants.NAVIGATION_RIGHT; 5254 case KeyEvent.KEYCODE_DPAD_DOWN: 5255 return SoundEffectConstants.NAVIGATION_DOWN; 5256 case KeyEvent.KEYCODE_DPAD_LEFT: 5257 return SoundEffectConstants.NAVIGATION_LEFT; 5258 } 5259 throw new IllegalArgumentException("keyCode must be one of " + 5260 "{KEYCODE_DPAD_UP, KEYCODE_DPAD_RIGHT, KEYCODE_DPAD_DOWN, " + 5261 "KEYCODE_DPAD_LEFT}."); 5262 } 5263 5264 private void doTrackball(long time) { 5265 int elapsed = (int) (mTrackballLastTime - mTrackballFirstTime); 5266 if (elapsed == 0) { 5267 elapsed = TRACKBALL_TIMEOUT; 5268 } 5269 float xRate = mTrackballRemainsX * 1000 / elapsed; 5270 float yRate = mTrackballRemainsY * 1000 / elapsed; 5271 int viewWidth = getViewWidth(); 5272 int viewHeight = getViewHeight(); 5273 if (mShiftIsPressed && !nativeFocusIsPlugin()) { 5274 moveSelection(scaleTrackballX(xRate, viewWidth), 5275 scaleTrackballY(yRate, viewHeight)); 5276 mTrackballRemainsX = mTrackballRemainsY = 0; 5277 return; 5278 } 5279 float ax = Math.abs(xRate); 5280 float ay = Math.abs(yRate); 5281 float maxA = Math.max(ax, ay); 5282 if (DebugFlags.WEB_VIEW) { 5283 Log.v(LOGTAG, "doTrackball elapsed=" + elapsed 5284 + " xRate=" + xRate 5285 + " yRate=" + yRate 5286 + " mTrackballRemainsX=" + mTrackballRemainsX 5287 + " mTrackballRemainsY=" + mTrackballRemainsY); 5288 } 5289 int width = mContentWidth - viewWidth; 5290 int height = mContentHeight - viewHeight; 5291 if (width < 0) width = 0; 5292 if (height < 0) height = 0; 5293 ax = Math.abs(mTrackballRemainsX * TRACKBALL_MULTIPLIER); 5294 ay = Math.abs(mTrackballRemainsY * TRACKBALL_MULTIPLIER); 5295 maxA = Math.max(ax, ay); 5296 int count = Math.max(0, (int) maxA); 5297 int oldScrollX = mScrollX; 5298 int oldScrollY = mScrollY; 5299 if (count > 0) { 5300 int selectKeyCode = ax < ay ? mTrackballRemainsY < 0 ? 5301 KeyEvent.KEYCODE_DPAD_UP : KeyEvent.KEYCODE_DPAD_DOWN : 5302 mTrackballRemainsX < 0 ? KeyEvent.KEYCODE_DPAD_LEFT : 5303 KeyEvent.KEYCODE_DPAD_RIGHT; 5304 count = Math.min(count, TRACKBALL_MOVE_COUNT); 5305 if (DebugFlags.WEB_VIEW) { 5306 Log.v(LOGTAG, "doTrackball keyCode=" + selectKeyCode 5307 + " count=" + count 5308 + " mTrackballRemainsX=" + mTrackballRemainsX 5309 + " mTrackballRemainsY=" + mTrackballRemainsY); 5310 } 5311 if (nativeFocusIsPlugin()) { 5312 for (int i = 0; i < count; i++) { 5313 letPluginHandleNavKey(selectKeyCode, time, true); 5314 } 5315 letPluginHandleNavKey(selectKeyCode, time, false); 5316 } else if (navHandledKey(selectKeyCode, count, false, time)) { 5317 playSoundEffect(keyCodeToSoundsEffect(selectKeyCode)); 5318 } 5319 mTrackballRemainsX = mTrackballRemainsY = 0; 5320 } 5321 if (count >= TRACKBALL_SCROLL_COUNT) { 5322 int xMove = scaleTrackballX(xRate, width); 5323 int yMove = scaleTrackballY(yRate, height); 5324 if (DebugFlags.WEB_VIEW) { 5325 Log.v(LOGTAG, "doTrackball pinScrollBy" 5326 + " count=" + count 5327 + " xMove=" + xMove + " yMove=" + yMove 5328 + " mScrollX-oldScrollX=" + (mScrollX-oldScrollX) 5329 + " mScrollY-oldScrollY=" + (mScrollY-oldScrollY) 5330 ); 5331 } 5332 if (Math.abs(mScrollX - oldScrollX) > Math.abs(xMove)) { 5333 xMove = 0; 5334 } 5335 if (Math.abs(mScrollY - oldScrollY) > Math.abs(yMove)) { 5336 yMove = 0; 5337 } 5338 if (xMove != 0 || yMove != 0) { 5339 pinScrollBy(xMove, yMove, true, 0); 5340 } 5341 mUserScroll = true; 5342 } 5343 } 5344 5345 private int computeMaxScrollX() { 5346 return Math.max(computeHorizontalScrollRange() - getViewWidth(), 0); 5347 } 5348 5349 private int computeMaxScrollY() { 5350 return Math.max(computeVerticalScrollRange() + getTitleHeight() 5351 - getViewHeightWithTitle(), getTitleHeight()); 5352 } 5353 5354 public void flingScroll(int vx, int vy) { 5355 mScroller.fling(mScrollX, mScrollY, vx, vy, 0, computeMaxScrollX(), 0, 5356 computeMaxScrollY(), getViewWidth() / 3, getViewHeight() / 3); 5357 invalidate(); 5358 } 5359 5360 private void doFling() { 5361 if (mVelocityTracker == null) { 5362 return; 5363 } 5364 int maxX = computeMaxScrollX(); 5365 int maxY = computeMaxScrollY(); 5366 5367 mVelocityTracker.computeCurrentVelocity(1000, mMaximumFling); 5368 int vx = (int) mVelocityTracker.getXVelocity(); 5369 int vy = (int) mVelocityTracker.getYVelocity(); 5370 5371 if (mSnapScrollMode != SNAP_NONE) { 5372 if ((mSnapScrollMode & SNAP_X) == SNAP_X) { 5373 vy = 0; 5374 } else { 5375 vx = 0; 5376 } 5377 } 5378 5379 if (true /* EMG release: make our fling more like Maps' */) { 5380 // maps cuts their velocity in half 5381 vx = vx * 3 / 4; 5382 vy = vy * 3 / 4; 5383 } 5384 if ((maxX == 0 && vy == 0) || (maxY == 0 && vx == 0)) { 5385 WebViewCore.resumePriority(); 5386 if (mScroller.springback(mScrollX, mScrollY, 0, computeMaxScrollX(), 5387 0, computeMaxScrollY())) { 5388 invalidate(); 5389 } 5390 return; 5391 } 5392 float currentVelocity = mScroller.getCurrVelocity(); 5393 if (mLastVelocity > 0 && currentVelocity > 0) { 5394 float deltaR = (float) (Math.abs(Math.atan2(mLastVelY, mLastVelX) 5395 - Math.atan2(vy, vx))); 5396 final float circle = (float) (Math.PI) * 2.0f; 5397 if (deltaR > circle * 0.9f || deltaR < circle * 0.1f) { 5398 vx += currentVelocity * mLastVelX / mLastVelocity; 5399 vy += currentVelocity * mLastVelY / mLastVelocity; 5400 if (DebugFlags.WEB_VIEW) { 5401 Log.v(LOGTAG, "doFling vx= " + vx + " vy=" + vy); 5402 } 5403 } else if (DebugFlags.WEB_VIEW) { 5404 Log.v(LOGTAG, "doFling missed " + deltaR / circle); 5405 } 5406 } else if (DebugFlags.WEB_VIEW) { 5407 Log.v(LOGTAG, "doFling start last=" + mLastVelocity 5408 + " current=" + currentVelocity 5409 + " vx=" + vx + " vy=" + vy 5410 + " maxX=" + maxX + " maxY=" + maxY 5411 + " mScrollX=" + mScrollX + " mScrollY=" + mScrollY); 5412 } 5413 mLastVelX = vx; 5414 mLastVelY = vy; 5415 mLastVelocity = (float) Math.hypot(vx, vy); 5416 5417 mScroller.fling(mScrollX, mScrollY, -vx, -vy, 0, maxX, 0, maxY, 5418 getViewWidth() / 3, getViewHeight() / 3); 5419 // TODO: duration is calculated based on velocity, if the range is 5420 // small, the animation will stop before duration is up. We may 5421 // want to calculate how long the animation is going to run to precisely 5422 // resume the webcore update. 5423 final int time = mScroller.getDuration(); 5424 mPrivateHandler.sendEmptyMessageDelayed(RESUME_WEBCORE_PRIORITY, time); 5425 awakenScrollBars(time); 5426 invalidate(); 5427 } 5428 5429 private boolean zoomWithPreview(float scale) { 5430 float oldScale = mActualScale; 5431 mInitialScrollX = mScrollX; 5432 mInitialScrollY = mScrollY; 5433 5434 // snap to DEFAULT_SCALE if it is close 5435 if (scale > (mDefaultScale - 0.05) && scale < (mDefaultScale + 0.05)) { 5436 scale = mDefaultScale; 5437 } 5438 5439 setNewZoomScale(scale, true, false); 5440 5441 if (oldScale != mActualScale) { 5442 // use mZoomPickerScale to see zoom preview first 5443 mZoomStart = SystemClock.uptimeMillis(); 5444 mInvInitialZoomScale = 1.0f / oldScale; 5445 mInvFinalZoomScale = 1.0f / mActualScale; 5446 mZoomScale = mActualScale; 5447 WebViewCore.pauseUpdatePicture(mWebViewCore); 5448 invalidate(); 5449 return true; 5450 } else { 5451 return false; 5452 } 5453 } 5454 5455 /** 5456 * Returns a view containing zoom controls i.e. +/- buttons. The caller is 5457 * in charge of installing this view to the view hierarchy. This view will 5458 * become visible when the user starts scrolling via touch and fade away if 5459 * the user does not interact with it. 5460 * <p/> 5461 * API version 3 introduces a built-in zoom mechanism that is shown 5462 * automatically by the MapView. This is the preferred approach for 5463 * showing the zoom UI. 5464 * 5465 * @deprecated The built-in zoom mechanism is preferred, see 5466 * {@link WebSettings#setBuiltInZoomControls(boolean)}. 5467 */ 5468 @Deprecated 5469 public View getZoomControls() { 5470 if (!getSettings().supportZoom()) { 5471 Log.w(LOGTAG, "This WebView doesn't support zoom."); 5472 return null; 5473 } 5474 if (mZoomControls == null) { 5475 mZoomControls = createZoomControls(); 5476 5477 /* 5478 * need to be set to VISIBLE first so that getMeasuredHeight() in 5479 * {@link #onSizeChanged()} can return the measured value for proper 5480 * layout. 5481 */ 5482 mZoomControls.setVisibility(View.VISIBLE); 5483 mZoomControlRunnable = new Runnable() { 5484 public void run() { 5485 5486 /* Don't dismiss the controls if the user has 5487 * focus on them. Wait and check again later. 5488 */ 5489 if (!mZoomControls.hasFocus()) { 5490 mZoomControls.hide(); 5491 } else { 5492 mPrivateHandler.removeCallbacks(mZoomControlRunnable); 5493 mPrivateHandler.postDelayed(mZoomControlRunnable, 5494 ZOOM_CONTROLS_TIMEOUT); 5495 } 5496 } 5497 }; 5498 } 5499 return mZoomControls; 5500 } 5501 5502 private ExtendedZoomControls createZoomControls() { 5503 ExtendedZoomControls zoomControls = new ExtendedZoomControls(mContext 5504 , null); 5505 zoomControls.setOnZoomInClickListener(new OnClickListener() { 5506 public void onClick(View v) { 5507 // reset time out 5508 mPrivateHandler.removeCallbacks(mZoomControlRunnable); 5509 mPrivateHandler.postDelayed(mZoomControlRunnable, 5510 ZOOM_CONTROLS_TIMEOUT); 5511 zoomIn(); 5512 } 5513 }); 5514 zoomControls.setOnZoomOutClickListener(new OnClickListener() { 5515 public void onClick(View v) { 5516 // reset time out 5517 mPrivateHandler.removeCallbacks(mZoomControlRunnable); 5518 mPrivateHandler.postDelayed(mZoomControlRunnable, 5519 ZOOM_CONTROLS_TIMEOUT); 5520 zoomOut(); 5521 } 5522 }); 5523 return zoomControls; 5524 } 5525 5526 /** 5527 * Gets the {@link ZoomButtonsController} which can be used to add 5528 * additional buttons to the zoom controls window. 5529 * 5530 * @return The instance of {@link ZoomButtonsController} used by this class, 5531 * or null if it is unavailable. 5532 * @hide 5533 */ 5534 public ZoomButtonsController getZoomButtonsController() { 5535 return mZoomButtonsController; 5536 } 5537 5538 /** 5539 * Perform zoom in in the webview 5540 * @return TRUE if zoom in succeeds. FALSE if no zoom changes. 5541 */ 5542 public boolean zoomIn() { 5543 // TODO: alternatively we can disallow this during draw history mode 5544 switchOutDrawHistory(); 5545 mInZoomOverview = false; 5546 // Center zooming to the center of the screen. 5547 mZoomCenterX = getViewWidth() * .5f; 5548 mZoomCenterY = getViewHeight() * .5f; 5549 mAnchorX = viewToContentX((int) mZoomCenterX + mScrollX); 5550 mAnchorY = viewToContentY((int) mZoomCenterY + mScrollY); 5551 return zoomWithPreview(mActualScale * 1.25f); 5552 } 5553 5554 /** 5555 * Perform zoom out in the webview 5556 * @return TRUE if zoom out succeeds. FALSE if no zoom changes. 5557 */ 5558 public boolean zoomOut() { 5559 // TODO: alternatively we can disallow this during draw history mode 5560 switchOutDrawHistory(); 5561 // Center zooming to the center of the screen. 5562 mZoomCenterX = getViewWidth() * .5f; 5563 mZoomCenterY = getViewHeight() * .5f; 5564 mAnchorX = viewToContentX((int) mZoomCenterX + mScrollX); 5565 mAnchorY = viewToContentY((int) mZoomCenterY + mScrollY); 5566 return zoomWithPreview(mActualScale * 0.8f); 5567 } 5568 5569 private void updateSelection() { 5570 if (mNativeClass == 0) { 5571 return; 5572 } 5573 // mLastTouchX and mLastTouchY are the point in the current viewport 5574 int contentX = viewToContentX((int) mLastTouchX + mScrollX); 5575 int contentY = viewToContentY((int) mLastTouchY + mScrollY); 5576 Rect rect = new Rect(contentX - mNavSlop, contentY - mNavSlop, 5577 contentX + mNavSlop, contentY + mNavSlop); 5578 nativeSelectBestAt(rect); 5579 } 5580 5581 /** 5582 * Scroll the focused text field/area to match the WebTextView 5583 * @param xPercent New x position of the WebTextView from 0 to 1. 5584 * @param y New y position of the WebTextView in view coordinates 5585 */ 5586 /*package*/ void scrollFocusedTextInput(float xPercent, int y) { 5587 if (!inEditingMode() || mWebViewCore == null) { 5588 return; 5589 } 5590 mWebViewCore.sendMessage(EventHub.SCROLL_TEXT_INPUT, 5591 // Since this position is relative to the top of the text input 5592 // field, we do not need to take the title bar's height into 5593 // consideration. 5594 viewToContentDimension(y), 5595 new Float(xPercent)); 5596 } 5597 5598 /** 5599 * Set our starting point and time for a drag from the WebTextView. 5600 */ 5601 /*package*/ void initiateTextFieldDrag(float x, float y, long eventTime) { 5602 if (!inEditingMode()) { 5603 return; 5604 } 5605 mLastTouchX = x + (float) (mWebTextView.getLeft() - mScrollX); 5606 mLastTouchY = y + (float) (mWebTextView.getTop() - mScrollY); 5607 mLastTouchTime = eventTime; 5608 if (!mScroller.isFinished()) { 5609 abortAnimation(); 5610 mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY); 5611 } 5612 mSnapScrollMode = SNAP_NONE; 5613 mVelocityTracker = VelocityTracker.obtain(); 5614 mTouchMode = TOUCH_DRAG_START_MODE; 5615 } 5616 5617 /** 5618 * Given a motion event from the WebTextView, set its location to our 5619 * coordinates, and handle the event. 5620 */ 5621 /*package*/ boolean textFieldDrag(MotionEvent event) { 5622 if (!inEditingMode()) { 5623 return false; 5624 } 5625 mDragFromTextInput = true; 5626 event.offsetLocation((float) (mWebTextView.getLeft() - mScrollX), 5627 (float) (mWebTextView.getTop() - mScrollY)); 5628 boolean result = onTouchEvent(event); 5629 mDragFromTextInput = false; 5630 return result; 5631 } 5632 5633 /** 5634 * Due a touch up from a WebTextView. This will be handled by webkit to 5635 * change the selection. 5636 * @param event MotionEvent in the WebTextView's coordinates. 5637 */ 5638 /*package*/ void touchUpOnTextField(MotionEvent event) { 5639 if (!inEditingMode()) { 5640 return; 5641 } 5642 int x = viewToContentX((int) event.getX() + mWebTextView.getLeft()); 5643 int y = viewToContentY((int) event.getY() + mWebTextView.getTop()); 5644 nativeMotionUp(x, y, mNavSlop); 5645 } 5646 5647 /** 5648 * Called when pressing the center key or trackball on a textfield. 5649 */ 5650 /*package*/ void centerKeyPressOnTextField() { 5651 mWebViewCore.sendMessage(EventHub.CLICK, nativeCursorFramePointer(), 5652 nativeCursorNodePointer()); 5653 } 5654 5655 private void doShortPress() { 5656 if (mNativeClass == 0) { 5657 return; 5658 } 5659 if (mPreventDefault == PREVENT_DEFAULT_YES) { 5660 return; 5661 } 5662 mTouchMode = TOUCH_DONE_MODE; 5663 switchOutDrawHistory(); 5664 // mLastTouchX and mLastTouchY are the point in the current viewport 5665 int contentX = viewToContentX((int) mLastTouchX + mScrollX); 5666 int contentY = viewToContentY((int) mLastTouchY + mScrollY); 5667 if (nativePointInNavCache(contentX, contentY, mNavSlop)) { 5668 WebViewCore.MotionUpData motionUpData = new WebViewCore 5669 .MotionUpData(); 5670 motionUpData.mFrame = nativeCacheHitFramePointer(); 5671 motionUpData.mNode = nativeCacheHitNodePointer(); 5672 motionUpData.mBounds = nativeCacheHitNodeBounds(); 5673 motionUpData.mX = contentX; 5674 motionUpData.mY = contentY; 5675 mWebViewCore.sendMessageAtFrontOfQueue(EventHub.VALID_NODE_BOUNDS, 5676 motionUpData); 5677 } else { 5678 doMotionUp(contentX, contentY); 5679 } 5680 } 5681 5682 private void doMotionUp(int contentX, int contentY) { 5683 if (mLogEvent && nativeMotionUp(contentX, contentY, mNavSlop)) { 5684 EventLog.writeEvent(EventLogTags.BROWSER_SNAP_CENTER); 5685 } 5686 if (nativeHasCursorNode() && !nativeCursorIsTextInput()) { 5687 playSoundEffect(SoundEffectConstants.CLICK); 5688 } 5689 } 5690 5691 // Rule for double tap: 5692 // 1. if the current scale is not same as the text wrap scale and layout 5693 // algorithm is NARROW_COLUMNS, fit to column; 5694 // 2. if the current state is not overview mode, change to overview mode; 5695 // 3. if the current state is overview mode, change to default scale. 5696 private void doDoubleTap() { 5697 if (mWebViewCore.getSettings().getUseWideViewPort() == false) { 5698 return; 5699 } 5700 mZoomCenterX = mLastTouchX; 5701 mZoomCenterY = mLastTouchY; 5702 mAnchorX = viewToContentX((int) mZoomCenterX + mScrollX); 5703 mAnchorY = viewToContentY((int) mZoomCenterY + mScrollY); 5704 WebSettings settings = getSettings(); 5705 // remove the zoom control after double tap 5706 if (settings.getBuiltInZoomControls()) { 5707 if (mZoomButtonsController.isVisible()) { 5708 mZoomButtonsController.setVisible(false); 5709 } 5710 } else { 5711 if (mZoomControlRunnable != null) { 5712 mPrivateHandler.removeCallbacks(mZoomControlRunnable); 5713 } 5714 if (mZoomControls != null) { 5715 mZoomControls.hide(); 5716 } 5717 } 5718 settings.setDoubleTapToastCount(0); 5719 boolean zoomToDefault = false; 5720 if ((settings.getLayoutAlgorithm() == WebSettings.LayoutAlgorithm.NARROW_COLUMNS) 5721 && (Math.abs(mActualScale - mTextWrapScale) >= 0.01f)) { 5722 setNewZoomScale(mActualScale, true, true); 5723 float overviewScale = (float) getViewWidth() / mZoomOverviewWidth; 5724 if (Math.abs(mActualScale - overviewScale) < 0.01f) { 5725 mInZoomOverview = true; 5726 } 5727 } else if (!mInZoomOverview) { 5728 float newScale = (float) getViewWidth() / mZoomOverviewWidth; 5729 if (Math.abs(mActualScale - newScale) >= 0.01f) { 5730 mInZoomOverview = true; 5731 // Force the titlebar fully reveal in overview mode 5732 if (mScrollY < getTitleHeight()) mScrollY = 0; 5733 zoomWithPreview(newScale); 5734 } else if (Math.abs(mActualScale - mDefaultScale) >= 0.01f) { 5735 zoomToDefault = true; 5736 } 5737 } else { 5738 zoomToDefault = true; 5739 } 5740 if (zoomToDefault) { 5741 mInZoomOverview = false; 5742 int left = nativeGetBlockLeftEdge(mAnchorX, mAnchorY, mActualScale); 5743 if (left != NO_LEFTEDGE) { 5744 // add a 5pt padding to the left edge. 5745 int viewLeft = contentToViewX(left < 5 ? 0 : (left - 5)) 5746 - mScrollX; 5747 // Re-calculate the zoom center so that the new scroll x will be 5748 // on the left edge. 5749 if (viewLeft > 0) { 5750 mZoomCenterX = viewLeft * mDefaultScale 5751 / (mDefaultScale - mActualScale); 5752 } else { 5753 scrollBy(viewLeft, 0); 5754 mZoomCenterX = 0; 5755 } 5756 } 5757 zoomWithPreview(mDefaultScale); 5758 } 5759 } 5760 5761 // Called by JNI to handle a touch on a node representing an email address, 5762 // address, or phone number 5763 private void overrideLoading(String url) { 5764 mCallbackProxy.uiOverrideUrlLoading(url); 5765 } 5766 5767 @Override 5768 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 5769 boolean result = false; 5770 if (inEditingMode()) { 5771 result = mWebTextView.requestFocus(direction, 5772 previouslyFocusedRect); 5773 } else { 5774 result = super.requestFocus(direction, previouslyFocusedRect); 5775 if (mWebViewCore.getSettings().getNeedInitialFocus()) { 5776 // For cases such as GMail, where we gain focus from a direction, 5777 // we want to move to the first available link. 5778 // FIXME: If there are no visible links, we may not want to 5779 int fakeKeyDirection = 0; 5780 switch(direction) { 5781 case View.FOCUS_UP: 5782 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_UP; 5783 break; 5784 case View.FOCUS_DOWN: 5785 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_DOWN; 5786 break; 5787 case View.FOCUS_LEFT: 5788 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_LEFT; 5789 break; 5790 case View.FOCUS_RIGHT: 5791 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_RIGHT; 5792 break; 5793 default: 5794 return result; 5795 } 5796 if (mNativeClass != 0 && !nativeHasCursorNode()) { 5797 navHandledKey(fakeKeyDirection, 1, true, 0); 5798 } 5799 } 5800 } 5801 return result; 5802 } 5803 5804 @Override 5805 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 5806 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 5807 5808 int heightMode = MeasureSpec.getMode(heightMeasureSpec); 5809 int heightSize = MeasureSpec.getSize(heightMeasureSpec); 5810 int widthMode = MeasureSpec.getMode(widthMeasureSpec); 5811 int widthSize = MeasureSpec.getSize(widthMeasureSpec); 5812 5813 int measuredHeight = heightSize; 5814 int measuredWidth = widthSize; 5815 5816 // Grab the content size from WebViewCore. 5817 int contentHeight = contentToViewDimension(mContentHeight); 5818 int contentWidth = contentToViewDimension(mContentWidth); 5819 5820// Log.d(LOGTAG, "------- measure " + heightMode); 5821 5822 if (heightMode != MeasureSpec.EXACTLY) { 5823 mHeightCanMeasure = true; 5824 measuredHeight = contentHeight; 5825 if (heightMode == MeasureSpec.AT_MOST) { 5826 // If we are larger than the AT_MOST height, then our height can 5827 // no longer be measured and we should scroll internally. 5828 if (measuredHeight > heightSize) { 5829 measuredHeight = heightSize; 5830 mHeightCanMeasure = false; 5831 } 5832 } 5833 } else { 5834 mHeightCanMeasure = false; 5835 } 5836 if (mNativeClass != 0) { 5837 nativeSetHeightCanMeasure(mHeightCanMeasure); 5838 } 5839 // For the width, always use the given size unless unspecified. 5840 if (widthMode == MeasureSpec.UNSPECIFIED) { 5841 mWidthCanMeasure = true; 5842 measuredWidth = contentWidth; 5843 } else { 5844 mWidthCanMeasure = false; 5845 } 5846 5847 synchronized (this) { 5848 setMeasuredDimension(measuredWidth, measuredHeight); 5849 } 5850 } 5851 5852 @Override 5853 public boolean requestChildRectangleOnScreen(View child, 5854 Rect rect, 5855 boolean immediate) { 5856 rect.offset(child.getLeft() - child.getScrollX(), 5857 child.getTop() - child.getScrollY()); 5858 5859 Rect content = new Rect(viewToContentX(mScrollX), 5860 viewToContentY(mScrollY), 5861 viewToContentX(mScrollX + getWidth() 5862 - getVerticalScrollbarWidth()), 5863 viewToContentY(mScrollY + getViewHeightWithTitle())); 5864 content = nativeSubtractLayers(content); 5865 int screenTop = contentToViewY(content.top); 5866 int screenBottom = contentToViewY(content.bottom); 5867 int height = screenBottom - screenTop; 5868 int scrollYDelta = 0; 5869 5870 if (rect.bottom > screenBottom) { 5871 int oneThirdOfScreenHeight = height / 3; 5872 if (rect.height() > 2 * oneThirdOfScreenHeight) { 5873 // If the rectangle is too tall to fit in the bottom two thirds 5874 // of the screen, place it at the top. 5875 scrollYDelta = rect.top - screenTop; 5876 } else { 5877 // If the rectangle will still fit on screen, we want its 5878 // top to be in the top third of the screen. 5879 scrollYDelta = rect.top - (screenTop + oneThirdOfScreenHeight); 5880 } 5881 } else if (rect.top < screenTop) { 5882 scrollYDelta = rect.top - screenTop; 5883 } 5884 5885 int screenLeft = contentToViewX(content.left); 5886 int screenRight = contentToViewX(content.right); 5887 int width = screenRight - screenLeft; 5888 int scrollXDelta = 0; 5889 5890 if (rect.right > screenRight && rect.left > screenLeft) { 5891 if (rect.width() > width) { 5892 scrollXDelta += (rect.left - screenLeft); 5893 } else { 5894 scrollXDelta += (rect.right - screenRight); 5895 } 5896 } else if (rect.left < screenLeft) { 5897 scrollXDelta -= (screenLeft - rect.left); 5898 } 5899 5900 if ((scrollYDelta | scrollXDelta) != 0) { 5901 return pinScrollBy(scrollXDelta, scrollYDelta, !immediate, 0); 5902 } 5903 5904 return false; 5905 } 5906 5907 /* package */ void replaceTextfieldText(int oldStart, int oldEnd, 5908 String replace, int newStart, int newEnd) { 5909 WebViewCore.ReplaceTextData arg = new WebViewCore.ReplaceTextData(); 5910 arg.mReplace = replace; 5911 arg.mNewStart = newStart; 5912 arg.mNewEnd = newEnd; 5913 mTextGeneration++; 5914 arg.mTextGeneration = mTextGeneration; 5915 mWebViewCore.sendMessage(EventHub.REPLACE_TEXT, oldStart, oldEnd, arg); 5916 } 5917 5918 /* package */ void passToJavaScript(String currentText, KeyEvent event) { 5919 WebViewCore.JSKeyData arg = new WebViewCore.JSKeyData(); 5920 arg.mEvent = event; 5921 arg.mCurrentText = currentText; 5922 // Increase our text generation number, and pass it to webcore thread 5923 mTextGeneration++; 5924 mWebViewCore.sendMessage(EventHub.PASS_TO_JS, mTextGeneration, 0, arg); 5925 // WebKit's document state is not saved until about to leave the page. 5926 // To make sure the host application, like Browser, has the up to date 5927 // document state when it goes to background, we force to save the 5928 // document state. 5929 mWebViewCore.removeMessages(EventHub.SAVE_DOCUMENT_STATE); 5930 mWebViewCore.sendMessageDelayed(EventHub.SAVE_DOCUMENT_STATE, 5931 cursorData(), 1000); 5932 } 5933 5934 /* package */ synchronized WebViewCore getWebViewCore() { 5935 return mWebViewCore; 5936 } 5937 5938 //------------------------------------------------------------------------- 5939 // Methods can be called from a separate thread, like WebViewCore 5940 // If it needs to call the View system, it has to send message. 5941 //------------------------------------------------------------------------- 5942 5943 /** 5944 * General handler to receive message coming from webkit thread 5945 */ 5946 class PrivateHandler extends Handler { 5947 @Override 5948 public void handleMessage(Message msg) { 5949 // exclude INVAL_RECT_MSG_ID since it is frequently output 5950 if (DebugFlags.WEB_VIEW && msg.what != INVAL_RECT_MSG_ID) { 5951 if (msg.what >= FIRST_PRIVATE_MSG_ID 5952 && msg.what <= LAST_PRIVATE_MSG_ID) { 5953 Log.v(LOGTAG, HandlerPrivateDebugString[msg.what 5954 - FIRST_PRIVATE_MSG_ID]); 5955 } else if (msg.what >= FIRST_PACKAGE_MSG_ID 5956 && msg.what <= LAST_PACKAGE_MSG_ID) { 5957 Log.v(LOGTAG, HandlerPackageDebugString[msg.what 5958 - FIRST_PACKAGE_MSG_ID]); 5959 } else { 5960 Log.v(LOGTAG, Integer.toString(msg.what)); 5961 } 5962 } 5963 if (mWebViewCore == null) { 5964 // after WebView's destroy() is called, skip handling messages. 5965 return; 5966 } 5967 switch (msg.what) { 5968 case REMEMBER_PASSWORD: { 5969 mDatabase.setUsernamePassword( 5970 msg.getData().getString("host"), 5971 msg.getData().getString("username"), 5972 msg.getData().getString("password")); 5973 ((Message) msg.obj).sendToTarget(); 5974 break; 5975 } 5976 case NEVER_REMEMBER_PASSWORD: { 5977 mDatabase.setUsernamePassword( 5978 msg.getData().getString("host"), null, null); 5979 ((Message) msg.obj).sendToTarget(); 5980 break; 5981 } 5982 case PREVENT_DEFAULT_TIMEOUT: { 5983 // if timeout happens, cancel it so that it won't block UI 5984 // to continue handling touch events 5985 if ((msg.arg1 == MotionEvent.ACTION_DOWN 5986 && mPreventDefault == PREVENT_DEFAULT_MAYBE_YES) 5987 || (msg.arg1 == MotionEvent.ACTION_MOVE 5988 && mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN)) { 5989 cancelWebCoreTouchEvent( 5990 viewToContentX((int) mLastTouchX + mScrollX), 5991 viewToContentY((int) mLastTouchY + mScrollY), 5992 true); 5993 } 5994 break; 5995 } 5996 case SWITCH_TO_SHORTPRESS: { 5997 if (mTouchMode == TOUCH_INIT_MODE) { 5998 if (mPreventDefault != PREVENT_DEFAULT_YES) { 5999 mTouchMode = TOUCH_SHORTPRESS_START_MODE; 6000 updateSelection(); 6001 } else { 6002 // set to TOUCH_SHORTPRESS_MODE so that it won't 6003 // trigger double tap any more 6004 mTouchMode = TOUCH_SHORTPRESS_MODE; 6005 } 6006 } else if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) { 6007 mTouchMode = TOUCH_DONE_MODE; 6008 } 6009 break; 6010 } 6011 case SWITCH_TO_LONGPRESS: { 6012 if (inFullScreenMode() || mDeferTouchProcess) { 6013 TouchEventData ted = new TouchEventData(); 6014 ted.mAction = WebViewCore.ACTION_LONGPRESS; 6015 ted.mX = viewToContentX((int) mLastTouchX + mScrollX); 6016 ted.mY = viewToContentY((int) mLastTouchY + mScrollY); 6017 // metaState for long press is tricky. Should it be the 6018 // state when the press started or when the press was 6019 // released? Or some intermediary key state? For 6020 // simplicity for now, we don't set it. 6021 ted.mMetaState = 0; 6022 ted.mReprocess = mDeferTouchProcess; 6023 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 6024 } else if (mPreventDefault != PREVENT_DEFAULT_YES) { 6025 mTouchMode = TOUCH_DONE_MODE; 6026 performLongClick(); 6027 rebuildWebTextView(); 6028 } 6029 break; 6030 } 6031 case RELEASE_SINGLE_TAP: { 6032 doShortPress(); 6033 break; 6034 } 6035 case SCROLL_BY_MSG_ID: 6036 setContentScrollBy(msg.arg1, msg.arg2, (Boolean) msg.obj); 6037 break; 6038 case SYNC_SCROLL_TO_MSG_ID: 6039 if (mUserScroll) { 6040 // if user has scrolled explicitly, don't sync the 6041 // scroll position any more 6042 mUserScroll = false; 6043 break; 6044 } 6045 // fall through 6046 case SCROLL_TO_MSG_ID: 6047 if (setContentScrollTo(msg.arg1, msg.arg2)) { 6048 // if we can't scroll to the exact position due to pin, 6049 // send a message to WebCore to re-scroll when we get a 6050 // new picture 6051 mUserScroll = false; 6052 mWebViewCore.sendMessage(EventHub.SYNC_SCROLL, 6053 msg.arg1, msg.arg2); 6054 } 6055 break; 6056 case SPAWN_SCROLL_TO_MSG_ID: 6057 spawnContentScrollTo(msg.arg1, msg.arg2); 6058 break; 6059 case UPDATE_ZOOM_RANGE: { 6060 WebViewCore.RestoreState restoreState 6061 = (WebViewCore.RestoreState) msg.obj; 6062 // mScrollX contains the new minPrefWidth 6063 updateZoomRange(restoreState, getViewWidth(), 6064 restoreState.mScrollX, false); 6065 break; 6066 } 6067 case NEW_PICTURE_MSG_ID: { 6068 WebSettings settings = mWebViewCore.getSettings(); 6069 // called for new content 6070 final int viewWidth = getViewWidth(); 6071 final WebViewCore.DrawData draw = 6072 (WebViewCore.DrawData) msg.obj; 6073 final Point viewSize = draw.mViewPoint; 6074 boolean useWideViewport = settings.getUseWideViewPort(); 6075 WebViewCore.RestoreState restoreState = draw.mRestoreState; 6076 boolean hasRestoreState = restoreState != null; 6077 if (hasRestoreState) { 6078 updateZoomRange(restoreState, viewSize.x, 6079 draw.mMinPrefWidth, true); 6080 if (!mDrawHistory) { 6081 mInZoomOverview = false; 6082 6083 if (mInitialScaleInPercent > 0) { 6084 setNewZoomScale(mInitialScaleInPercent / 100.0f, 6085 mInitialScaleInPercent != mTextWrapScale * 100, 6086 false); 6087 } else if (restoreState.mViewScale > 0) { 6088 mTextWrapScale = restoreState.mTextWrapScale; 6089 setNewZoomScale(restoreState.mViewScale, false, 6090 false); 6091 } else { 6092 mInZoomOverview = useWideViewport 6093 && settings.getLoadWithOverviewMode(); 6094 float scale; 6095 if (mInZoomOverview) { 6096 scale = (float) viewWidth 6097 / DEFAULT_VIEWPORT_WIDTH; 6098 } else { 6099 scale = restoreState.mTextWrapScale; 6100 } 6101 setNewZoomScale(scale, Math.abs(scale 6102 - mTextWrapScale) >= 0.01f, false); 6103 } 6104 setContentScrollTo(restoreState.mScrollX, 6105 restoreState.mScrollY); 6106 // As we are on a new page, remove the WebTextView. This 6107 // is necessary for page loads driven by webkit, and in 6108 // particular when the user was on a password field, so 6109 // the WebTextView was visible. 6110 clearTextEntry(false); 6111 // update the zoom buttons as the scale can be changed 6112 if (getSettings().getBuiltInZoomControls()) { 6113 updateZoomButtonsEnabled(); 6114 } 6115 } 6116 } 6117 // We update the layout (i.e. request a layout from the 6118 // view system) if the last view size that we sent to 6119 // WebCore matches the view size of the picture we just 6120 // received in the fixed dimension. 6121 final boolean updateLayout = viewSize.x == mLastWidthSent 6122 && viewSize.y == mLastHeightSent; 6123 recordNewContentSize(draw.mWidthHeight.x, 6124 draw.mWidthHeight.y 6125 + (mFindIsUp ? mFindHeight : 0), updateLayout); 6126 if (DebugFlags.WEB_VIEW) { 6127 Rect b = draw.mInvalRegion.getBounds(); 6128 Log.v(LOGTAG, "NEW_PICTURE_MSG_ID {" + 6129 b.left+","+b.top+","+b.right+","+b.bottom+"}"); 6130 } 6131 invalidateContentRect(draw.mInvalRegion.getBounds()); 6132 if (mPictureListener != null) { 6133 mPictureListener.onNewPicture(WebView.this, capturePicture()); 6134 } 6135 if (useWideViewport) { 6136 // limit mZoomOverviewWidth upper bound to 6137 // sMaxViewportWidth so that if the page doesn't behave 6138 // well, the WebView won't go insane. limit the lower 6139 // bound to match the default scale for mobile sites. 6140 mZoomOverviewWidth = Math.min(sMaxViewportWidth, Math 6141 .max((int) (viewWidth / mDefaultScale), Math 6142 .max(draw.mMinPrefWidth, 6143 draw.mViewPoint.x))); 6144 } 6145 if (!mMinZoomScaleFixed) { 6146 mMinZoomScale = (float) viewWidth / mZoomOverviewWidth; 6147 } 6148 if (!mDrawHistory && mInZoomOverview) { 6149 // fit the content width to the current view. Ignore 6150 // the rounding error case. 6151 if (Math.abs((viewWidth * mInvActualScale) 6152 - mZoomOverviewWidth) > 1) { 6153 setNewZoomScale((float) viewWidth 6154 / mZoomOverviewWidth, Math.abs(mActualScale 6155 - mTextWrapScale) < 0.01f, false); 6156 } 6157 } 6158 if (draw.mFocusSizeChanged && inEditingMode()) { 6159 mFocusSizeChanged = true; 6160 } 6161 if (hasRestoreState) { 6162 mViewManager.postReadyToDrawAll(); 6163 } 6164 break; 6165 } 6166 case WEBCORE_INITIALIZED_MSG_ID: 6167 // nativeCreate sets mNativeClass to a non-zero value 6168 nativeCreate(msg.arg1); 6169 break; 6170 case UPDATE_TEXTFIELD_TEXT_MSG_ID: 6171 // Make sure that the textfield is currently focused 6172 // and representing the same node as the pointer. 6173 if (inEditingMode() && 6174 mWebTextView.isSameTextField(msg.arg1)) { 6175 if (msg.getData().getBoolean("password")) { 6176 Spannable text = (Spannable) mWebTextView.getText(); 6177 int start = Selection.getSelectionStart(text); 6178 int end = Selection.getSelectionEnd(text); 6179 mWebTextView.setInPassword(true); 6180 // Restore the selection, which may have been 6181 // ruined by setInPassword. 6182 Spannable pword = 6183 (Spannable) mWebTextView.getText(); 6184 Selection.setSelection(pword, start, end); 6185 // If the text entry has created more events, ignore 6186 // this one. 6187 } else if (msg.arg2 == mTextGeneration) { 6188 mWebTextView.setTextAndKeepSelection( 6189 (String) msg.obj); 6190 } 6191 } 6192 break; 6193 case UPDATE_TEXT_SELECTION_MSG_ID: 6194 // If no textfield was in focus, and the user touched one, 6195 // causing it to send this message, then WebTextView has not 6196 // been set up yet. Rebuild it so it can set its selection. 6197 rebuildWebTextView(); 6198 if (inEditingMode() 6199 && mWebTextView.isSameTextField(msg.arg1) 6200 && msg.arg2 == mTextGeneration) { 6201 WebViewCore.TextSelectionData tData 6202 = (WebViewCore.TextSelectionData) msg.obj; 6203 mWebTextView.setSelectionFromWebKit(tData.mStart, 6204 tData.mEnd); 6205 } 6206 break; 6207 case RETURN_LABEL: 6208 if (inEditingMode() 6209 && mWebTextView.isSameTextField(msg.arg1)) { 6210 mWebTextView.setHint((String) msg.obj); 6211 InputMethodManager imm 6212 = InputMethodManager.peekInstance(); 6213 // The hint is propagated to the IME in 6214 // onCreateInputConnection. If the IME is already 6215 // active, restart it so that its hint text is updated. 6216 if (imm != null && imm.isActive(mWebTextView)) { 6217 imm.restartInput(mWebTextView); 6218 } 6219 } 6220 break; 6221 case MOVE_OUT_OF_PLUGIN: 6222 navHandledKey(msg.arg1, 1, false, 0); 6223 break; 6224 case UPDATE_TEXT_ENTRY_MSG_ID: 6225 // this is sent after finishing resize in WebViewCore. Make 6226 // sure the text edit box is still on the screen. 6227 if (inEditingMode() && nativeCursorIsTextInput()) { 6228 mWebTextView.bringIntoView(); 6229 rebuildWebTextView(); 6230 } 6231 break; 6232 case CLEAR_TEXT_ENTRY: 6233 clearTextEntry(false); 6234 break; 6235 case INVAL_RECT_MSG_ID: { 6236 Rect r = (Rect)msg.obj; 6237 if (r == null) { 6238 invalidate(); 6239 } else { 6240 // we need to scale r from content into view coords, 6241 // which viewInvalidate() does for us 6242 viewInvalidate(r.left, r.top, r.right, r.bottom); 6243 } 6244 break; 6245 } 6246 case IMMEDIATE_REPAINT_MSG_ID: { 6247 invalidate(); 6248 break; 6249 } 6250 case SET_ROOT_LAYER_MSG_ID: { 6251 nativeSetRootLayer(msg.arg1); 6252 invalidate(); 6253 break; 6254 } 6255 case REQUEST_FORM_DATA: 6256 AutoCompleteAdapter adapter = (AutoCompleteAdapter) msg.obj; 6257 if (mWebTextView.isSameTextField(msg.arg1)) { 6258 mWebTextView.setAdapterCustom(adapter); 6259 } 6260 break; 6261 case RESUME_WEBCORE_PRIORITY: 6262 WebViewCore.resumePriority(); 6263 break; 6264 6265 case LONG_PRESS_CENTER: 6266 // as this is shared by keydown and trackballdown, reset all 6267 // the states 6268 mGotCenterDown = false; 6269 mTrackballDown = false; 6270 performLongClick(); 6271 break; 6272 6273 case WEBCORE_NEED_TOUCH_EVENTS: 6274 mForwardTouchEvents = (msg.arg1 != 0); 6275 break; 6276 6277 case PREVENT_TOUCH_ID: 6278 if (inFullScreenMode()) { 6279 break; 6280 } 6281 if (msg.obj == null) { 6282 if (msg.arg1 == MotionEvent.ACTION_DOWN 6283 && mPreventDefault == PREVENT_DEFAULT_MAYBE_YES) { 6284 // if prevent default is called from WebCore, UI 6285 // will not handle the rest of the touch events any 6286 // more. 6287 mPreventDefault = msg.arg2 == 1 ? PREVENT_DEFAULT_YES 6288 : PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN; 6289 } else if (msg.arg1 == MotionEvent.ACTION_MOVE 6290 && mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN) { 6291 // the return for the first ACTION_MOVE will decide 6292 // whether UI will handle touch or not. Currently no 6293 // support for alternating prevent default 6294 mPreventDefault = msg.arg2 == 1 ? PREVENT_DEFAULT_YES 6295 : PREVENT_DEFAULT_NO; 6296 } 6297 } else if (msg.arg2 == 0) { 6298 // prevent default is not called in WebCore, so the 6299 // message needs to be reprocessed in UI 6300 TouchEventData ted = (TouchEventData) msg.obj; 6301 switch (ted.mAction) { 6302 case MotionEvent.ACTION_DOWN: 6303 mLastDeferTouchX = contentToViewX(ted.mX) 6304 - mScrollX; 6305 mLastDeferTouchY = contentToViewY(ted.mY) 6306 - mScrollY; 6307 mDeferTouchMode = TOUCH_INIT_MODE; 6308 break; 6309 case MotionEvent.ACTION_MOVE: { 6310 // no snapping in defer process 6311 int x = contentToViewX(ted.mX) - mScrollX; 6312 int y = contentToViewY(ted.mY) - mScrollY; 6313 if (mDeferTouchMode != TOUCH_DRAG_MODE) { 6314 mDeferTouchMode = TOUCH_DRAG_MODE; 6315 mLastDeferTouchX = x; 6316 mLastDeferTouchY = y; 6317 startDrag(); 6318 } 6319 doDrag((int) (mLastDeferTouchX - x), 6320 (int) (mLastDeferTouchY - y)); 6321 mLastDeferTouchX = x; 6322 mLastDeferTouchY = y; 6323 break; 6324 } 6325 case MotionEvent.ACTION_UP: 6326 case MotionEvent.ACTION_CANCEL: 6327 if (mDeferTouchMode == TOUCH_DRAG_MODE) { 6328 // no fling in defer process 6329 mScroller.springback(mScrollX, mScrollY, 0, 6330 computeMaxScrollX(), 0, 6331 computeMaxScrollY()); 6332 invalidate(); 6333 WebViewCore.resumePriority(); 6334 } 6335 mDeferTouchMode = TOUCH_DONE_MODE; 6336 break; 6337 case WebViewCore.ACTION_DOUBLETAP: 6338 // doDoubleTap() needs mLastTouchX/Y as anchor 6339 mLastTouchX = contentToViewX(ted.mX) - mScrollX; 6340 mLastTouchY = contentToViewY(ted.mY) - mScrollY; 6341 doDoubleTap(); 6342 mDeferTouchMode = TOUCH_DONE_MODE; 6343 break; 6344 case WebViewCore.ACTION_LONGPRESS: 6345 HitTestResult hitTest = getHitTestResult(); 6346 if (hitTest != null && hitTest.mType 6347 != HitTestResult.UNKNOWN_TYPE) { 6348 performLongClick(); 6349 rebuildWebTextView(); 6350 } 6351 mDeferTouchMode = TOUCH_DONE_MODE; 6352 break; 6353 } 6354 } 6355 break; 6356 6357 case REQUEST_KEYBOARD: 6358 if (msg.arg1 == 0) { 6359 hideSoftKeyboard(); 6360 } else { 6361 displaySoftKeyboard(1 == msg.arg2); 6362 } 6363 break; 6364 6365 case FIND_AGAIN: 6366 // Ignore if find has been dismissed. 6367 if (mFindIsUp) { 6368 findAll(mLastFind); 6369 } 6370 break; 6371 6372 case DRAG_HELD_MOTIONLESS: 6373 mHeldMotionless = MOTIONLESS_TRUE; 6374 invalidate(); 6375 // fall through to keep scrollbars awake 6376 6377 case AWAKEN_SCROLL_BARS: 6378 if (mTouchMode == TOUCH_DRAG_MODE 6379 && mHeldMotionless == MOTIONLESS_TRUE) { 6380 awakenScrollBars(ViewConfiguration 6381 .getScrollDefaultDelay(), false); 6382 mPrivateHandler.sendMessageDelayed(mPrivateHandler 6383 .obtainMessage(AWAKEN_SCROLL_BARS), 6384 ViewConfiguration.getScrollDefaultDelay()); 6385 } 6386 break; 6387 6388 case DO_MOTION_UP: 6389 doMotionUp(msg.arg1, msg.arg2); 6390 break; 6391 6392 case SHOW_FULLSCREEN: { 6393 WebViewCore.PluginFullScreenData data 6394 = (WebViewCore.PluginFullScreenData) msg.obj; 6395 if (data.mNpp != 0 && data.mView != null) { 6396 if (inFullScreenMode()) { 6397 Log.w(LOGTAG, 6398 "Should not have another full screen."); 6399 mFullScreenHolder.dismiss(); 6400 } 6401 mFullScreenHolder = new PluginFullScreenHolder( 6402 WebView.this, data.mNpp); 6403 // as we are sharing the View between full screen and 6404 // embedded mode, we have to remove the 6405 // AbsoluteLayout.LayoutParams set by embedded mode to 6406 // ViewGroup.LayoutParams before adding it to the dialog 6407 data.mView.setLayoutParams(new ViewGroup.LayoutParams( 6408 ViewGroup.LayoutParams.FILL_PARENT, 6409 ViewGroup.LayoutParams.FILL_PARENT)); 6410 mFullScreenHolder.setContentView(data.mView); 6411 mFullScreenHolder.setCancelable(false); 6412 mFullScreenHolder.setCanceledOnTouchOutside(false); 6413 mFullScreenHolder.show(); 6414 } else if (!inFullScreenMode()) { 6415 // this may happen if user dismisses the fullscreen and 6416 // then the WebCore re-position message finally reached 6417 // the UI thread. 6418 break; 6419 } 6420 // move the matching embedded view fully into the view so 6421 // that touch will be valid instead of rejected due to out 6422 // of the visible bounds 6423 // TODO: do we need to preserve the original position and 6424 // scale so that we can revert it when leaving the full 6425 // screen mode? 6426 int x = contentToViewX(data.mDocX); 6427 int y = contentToViewY(data.mDocY); 6428 int width = contentToViewDimension(data.mDocWidth); 6429 int height = contentToViewDimension(data.mDocHeight); 6430 int viewWidth = getViewWidth(); 6431 int viewHeight = getViewHeight(); 6432 int newX = mScrollX; 6433 int newY = mScrollY; 6434 if (x < mScrollX) { 6435 newX = x + (width > viewWidth 6436 ? (width - viewWidth) / 2 : 0); 6437 } else if (x + width > mScrollX + viewWidth) { 6438 newX = x + width - viewWidth - (width > viewWidth 6439 ? (width - viewWidth) / 2 : 0); 6440 } 6441 if (y < mScrollY) { 6442 newY = y + (height > viewHeight 6443 ? (height - viewHeight) / 2 : 0); 6444 } else if (y + height > mScrollY + viewHeight) { 6445 newY = y + height - viewHeight - (height > viewHeight 6446 ? (height - viewHeight) / 2 : 0); 6447 } 6448 scrollTo(newX, newY); 6449 if (width > viewWidth || height > viewHeight) { 6450 mZoomCenterX = viewWidth * .5f; 6451 mZoomCenterY = viewHeight * .5f; 6452 // do not change text wrap scale so that there is no 6453 // reflow 6454 setNewZoomScale(mActualScale 6455 / Math.max((float) width / viewWidth, 6456 (float) height / viewHeight), false, 6457 false); 6458 } 6459 // Now update the bound 6460 mFullScreenHolder.updateBound(contentToViewX(data.mDocX) 6461 - mScrollX, contentToViewY(data.mDocY) - mScrollY, 6462 contentToViewDimension(data.mDocWidth), 6463 contentToViewDimension(data.mDocHeight)); 6464 } 6465 break; 6466 6467 case HIDE_FULLSCREEN: 6468 if (inFullScreenMode()) { 6469 mFullScreenHolder.dismiss(); 6470 mFullScreenHolder = null; 6471 } 6472 break; 6473 6474 case DOM_FOCUS_CHANGED: 6475 if (inEditingMode()) { 6476 nativeClearCursor(); 6477 rebuildWebTextView(); 6478 } 6479 break; 6480 6481 case SHOW_RECT_MSG_ID: { 6482 WebViewCore.ShowRectData data = (WebViewCore.ShowRectData) msg.obj; 6483 int x = mScrollX; 6484 int left = contentToViewX(data.mLeft); 6485 int width = contentToViewDimension(data.mWidth); 6486 int maxWidth = contentToViewDimension(data.mContentWidth); 6487 int viewWidth = getViewWidth(); 6488 if (width < viewWidth) { 6489 // center align 6490 x += left + width / 2 - mScrollX - viewWidth / 2; 6491 } else { 6492 x += (int) (left + data.mXPercentInDoc * width 6493 - mScrollX - data.mXPercentInView * viewWidth); 6494 } 6495 if (DebugFlags.WEB_VIEW) { 6496 Log.v(LOGTAG, "showRectMsg=(left=" + left + ",width=" + 6497 width + ",maxWidth=" + maxWidth + 6498 ",viewWidth=" + viewWidth + ",x=" 6499 + x + ",xPercentInDoc=" + data.mXPercentInDoc + 6500 ",xPercentInView=" + data.mXPercentInView+ ")"); 6501 } 6502 // use the passing content width to cap x as the current 6503 // mContentWidth may not be updated yet 6504 x = Math.max(0, 6505 (Math.min(maxWidth, x + viewWidth)) - viewWidth); 6506 int top = contentToViewY(data.mTop); 6507 int height = contentToViewDimension(data.mHeight); 6508 int maxHeight = contentToViewDimension(data.mContentHeight); 6509 int viewHeight = getViewHeight(); 6510 int y = (int) (top + data.mYPercentInDoc * height - 6511 data.mYPercentInView * viewHeight); 6512 if (DebugFlags.WEB_VIEW) { 6513 Log.v(LOGTAG, "showRectMsg=(top=" + top + ",height=" + 6514 height + ",maxHeight=" + maxHeight + 6515 ",viewHeight=" + viewHeight + ",y=" 6516 + y + ",yPercentInDoc=" + data.mYPercentInDoc + 6517 ",yPercentInView=" + data.mYPercentInView+ ")"); 6518 } 6519 // use the passing content height to cap y as the current 6520 // mContentHeight may not be updated yet 6521 y = Math.max(0, 6522 (Math.min(maxHeight, y + viewHeight) - viewHeight)); 6523 // We need to take into account the visible title height 6524 // when scrolling since y is an absolute view position. 6525 y = Math.max(0, y - getVisibleTitleHeight()); 6526 scrollTo(x, y); 6527 } 6528 break; 6529 6530 default: 6531 super.handleMessage(msg); 6532 break; 6533 } 6534 } 6535 } 6536 6537 // Class used to use a dropdown for a <select> element 6538 private class InvokeListBox implements Runnable { 6539 // Whether the listbox allows multiple selection. 6540 private boolean mMultiple; 6541 // Passed in to a list with multiple selection to tell 6542 // which items are selected. 6543 private int[] mSelectedArray; 6544 // Passed in to a list with single selection to tell 6545 // where the initial selection is. 6546 private int mSelection; 6547 6548 private Container[] mContainers; 6549 6550 // Need these to provide stable ids to my ArrayAdapter, 6551 // which normally does not have stable ids. (Bug 1250098) 6552 private class Container extends Object { 6553 /** 6554 * Possible values for mEnabled. Keep in sync with OptionStatus in 6555 * WebViewCore.cpp 6556 */ 6557 final static int OPTGROUP = -1; 6558 final static int OPTION_DISABLED = 0; 6559 final static int OPTION_ENABLED = 1; 6560 6561 String mString; 6562 int mEnabled; 6563 int mId; 6564 6565 public String toString() { 6566 return mString; 6567 } 6568 } 6569 6570 /** 6571 * Subclass ArrayAdapter so we can disable OptionGroupLabels, 6572 * and allow filtering. 6573 */ 6574 private class MyArrayListAdapter extends ArrayAdapter<Container> { 6575 public MyArrayListAdapter(Context context, Container[] objects, boolean multiple) { 6576 super(context, 6577 multiple ? com.android.internal.R.layout.select_dialog_multichoice : 6578 com.android.internal.R.layout.select_dialog_singlechoice, 6579 objects); 6580 } 6581 6582 @Override 6583 public View getView(int position, View convertView, 6584 ViewGroup parent) { 6585 // Always pass in null so that we will get a new CheckedTextView 6586 // Otherwise, an item which was previously used as an <optgroup> 6587 // element (i.e. has no check), could get used as an <option> 6588 // element, which needs a checkbox/radio, but it would not have 6589 // one. 6590 convertView = super.getView(position, null, parent); 6591 Container c = item(position); 6592 if (c != null && Container.OPTION_ENABLED != c.mEnabled) { 6593 // ListView does not draw dividers between disabled and 6594 // enabled elements. Use a LinearLayout to provide dividers 6595 LinearLayout layout = new LinearLayout(mContext); 6596 layout.setOrientation(LinearLayout.VERTICAL); 6597 if (position > 0) { 6598 View dividerTop = new View(mContext); 6599 dividerTop.setBackgroundResource( 6600 android.R.drawable.divider_horizontal_bright); 6601 layout.addView(dividerTop); 6602 } 6603 6604 if (Container.OPTGROUP == c.mEnabled) { 6605 // Currently select_dialog_multichoice and 6606 // select_dialog_singlechoice are CheckedTextViews. If 6607 // that changes, the class cast will no longer be valid. 6608 Assert.assertTrue( 6609 convertView instanceof CheckedTextView); 6610 ((CheckedTextView) convertView).setCheckMarkDrawable( 6611 null); 6612 } else { 6613 // c.mEnabled == Container.OPTION_DISABLED 6614 // Draw the disabled element in a disabled state. 6615 convertView.setEnabled(false); 6616 } 6617 6618 layout.addView(convertView); 6619 if (position < getCount() - 1) { 6620 View dividerBottom = new View(mContext); 6621 dividerBottom.setBackgroundResource( 6622 android.R.drawable.divider_horizontal_bright); 6623 layout.addView(dividerBottom); 6624 } 6625 return layout; 6626 } 6627 return convertView; 6628 } 6629 6630 @Override 6631 public boolean hasStableIds() { 6632 // AdapterView's onChanged method uses this to determine whether 6633 // to restore the old state. Return false so that the old (out 6634 // of date) state does not replace the new, valid state. 6635 return false; 6636 } 6637 6638 private Container item(int position) { 6639 if (position < 0 || position >= getCount()) { 6640 return null; 6641 } 6642 return (Container) getItem(position); 6643 } 6644 6645 @Override 6646 public long getItemId(int position) { 6647 Container item = item(position); 6648 if (item == null) { 6649 return -1; 6650 } 6651 return item.mId; 6652 } 6653 6654 @Override 6655 public boolean areAllItemsEnabled() { 6656 return false; 6657 } 6658 6659 @Override 6660 public boolean isEnabled(int position) { 6661 Container item = item(position); 6662 if (item == null) { 6663 return false; 6664 } 6665 return Container.OPTION_ENABLED == item.mEnabled; 6666 } 6667 } 6668 6669 private InvokeListBox(String[] array, int[] enabled, int[] selected) { 6670 mMultiple = true; 6671 mSelectedArray = selected; 6672 6673 int length = array.length; 6674 mContainers = new Container[length]; 6675 for (int i = 0; i < length; i++) { 6676 mContainers[i] = new Container(); 6677 mContainers[i].mString = array[i]; 6678 mContainers[i].mEnabled = enabled[i]; 6679 mContainers[i].mId = i; 6680 } 6681 } 6682 6683 private InvokeListBox(String[] array, int[] enabled, int selection) { 6684 mSelection = selection; 6685 mMultiple = false; 6686 6687 int length = array.length; 6688 mContainers = new Container[length]; 6689 for (int i = 0; i < length; i++) { 6690 mContainers[i] = new Container(); 6691 mContainers[i].mString = array[i]; 6692 mContainers[i].mEnabled = enabled[i]; 6693 mContainers[i].mId = i; 6694 } 6695 } 6696 6697 /* 6698 * Whenever the data set changes due to filtering, this class ensures 6699 * that the checked item remains checked. 6700 */ 6701 private class SingleDataSetObserver extends DataSetObserver { 6702 private long mCheckedId; 6703 private ListView mListView; 6704 private Adapter mAdapter; 6705 6706 /* 6707 * Create a new observer. 6708 * @param id The ID of the item to keep checked. 6709 * @param l ListView for getting and clearing the checked states 6710 * @param a Adapter for getting the IDs 6711 */ 6712 public SingleDataSetObserver(long id, ListView l, Adapter a) { 6713 mCheckedId = id; 6714 mListView = l; 6715 mAdapter = a; 6716 } 6717 6718 public void onChanged() { 6719 // The filter may have changed which item is checked. Find the 6720 // item that the ListView thinks is checked. 6721 int position = mListView.getCheckedItemPosition(); 6722 long id = mAdapter.getItemId(position); 6723 if (mCheckedId != id) { 6724 // Clear the ListView's idea of the checked item, since 6725 // it is incorrect 6726 mListView.clearChoices(); 6727 // Search for mCheckedId. If it is in the filtered list, 6728 // mark it as checked 6729 int count = mAdapter.getCount(); 6730 for (int i = 0; i < count; i++) { 6731 if (mAdapter.getItemId(i) == mCheckedId) { 6732 mListView.setItemChecked(i, true); 6733 break; 6734 } 6735 } 6736 } 6737 } 6738 6739 public void onInvalidate() {} 6740 } 6741 6742 public void run() { 6743 final ListView listView = (ListView) LayoutInflater.from(mContext) 6744 .inflate(com.android.internal.R.layout.select_dialog, null); 6745 final MyArrayListAdapter adapter = new 6746 MyArrayListAdapter(mContext, mContainers, mMultiple); 6747 AlertDialog.Builder b = new AlertDialog.Builder(mContext) 6748 .setView(listView).setCancelable(true) 6749 .setInverseBackgroundForced(true); 6750 6751 if (mMultiple) { 6752 b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { 6753 public void onClick(DialogInterface dialog, int which) { 6754 mWebViewCore.sendMessage( 6755 EventHub.LISTBOX_CHOICES, 6756 adapter.getCount(), 0, 6757 listView.getCheckedItemPositions()); 6758 }}); 6759 b.setNegativeButton(android.R.string.cancel, 6760 new DialogInterface.OnClickListener() { 6761 public void onClick(DialogInterface dialog, int which) { 6762 mWebViewCore.sendMessage( 6763 EventHub.SINGLE_LISTBOX_CHOICE, -2, 0); 6764 }}); 6765 } 6766 final AlertDialog dialog = b.create(); 6767 listView.setAdapter(adapter); 6768 listView.setFocusableInTouchMode(true); 6769 // There is a bug (1250103) where the checks in a ListView with 6770 // multiple items selected are associated with the positions, not 6771 // the ids, so the items do not properly retain their checks when 6772 // filtered. Do not allow filtering on multiple lists until 6773 // that bug is fixed. 6774 6775 listView.setTextFilterEnabled(!mMultiple); 6776 if (mMultiple) { 6777 listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); 6778 int length = mSelectedArray.length; 6779 for (int i = 0; i < length; i++) { 6780 listView.setItemChecked(mSelectedArray[i], true); 6781 } 6782 } else { 6783 listView.setOnItemClickListener(new OnItemClickListener() { 6784 public void onItemClick(AdapterView parent, View v, 6785 int position, long id) { 6786 mWebViewCore.sendMessage( 6787 EventHub.SINGLE_LISTBOX_CHOICE, (int)id, 0); 6788 dialog.dismiss(); 6789 } 6790 }); 6791 if (mSelection != -1) { 6792 listView.setSelection(mSelection); 6793 listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 6794 listView.setItemChecked(mSelection, true); 6795 DataSetObserver observer = new SingleDataSetObserver( 6796 adapter.getItemId(mSelection), listView, adapter); 6797 adapter.registerDataSetObserver(observer); 6798 } 6799 } 6800 dialog.setOnCancelListener(new DialogInterface.OnCancelListener() { 6801 public void onCancel(DialogInterface dialog) { 6802 mWebViewCore.sendMessage( 6803 EventHub.SINGLE_LISTBOX_CHOICE, -2, 0); 6804 } 6805 }); 6806 dialog.show(); 6807 } 6808 } 6809 6810 /* 6811 * Request a dropdown menu for a listbox with multiple selection. 6812 * 6813 * @param array Labels for the listbox. 6814 * @param enabledArray State for each element in the list. See static 6815 * integers in Container class. 6816 * @param selectedArray Which positions are initally selected. 6817 */ 6818 void requestListBox(String[] array, int[] enabledArray, int[] 6819 selectedArray) { 6820 mPrivateHandler.post( 6821 new InvokeListBox(array, enabledArray, selectedArray)); 6822 } 6823 6824 private void updateZoomRange(WebViewCore.RestoreState restoreState, 6825 int viewWidth, int minPrefWidth, boolean updateZoomOverview) { 6826 if (restoreState.mMinScale == 0) { 6827 if (restoreState.mMobileSite) { 6828 if (minPrefWidth > Math.max(0, viewWidth)) { 6829 mMinZoomScale = (float) viewWidth / minPrefWidth; 6830 mMinZoomScaleFixed = false; 6831 if (updateZoomOverview) { 6832 WebSettings settings = getSettings(); 6833 mInZoomOverview = settings.getUseWideViewPort() && 6834 settings.getLoadWithOverviewMode(); 6835 } 6836 } else { 6837 mMinZoomScale = restoreState.mDefaultScale; 6838 mMinZoomScaleFixed = true; 6839 } 6840 } else { 6841 mMinZoomScale = DEFAULT_MIN_ZOOM_SCALE; 6842 mMinZoomScaleFixed = false; 6843 } 6844 } else { 6845 mMinZoomScale = restoreState.mMinScale; 6846 mMinZoomScaleFixed = true; 6847 } 6848 if (restoreState.mMaxScale == 0) { 6849 mMaxZoomScale = DEFAULT_MAX_ZOOM_SCALE; 6850 } else { 6851 mMaxZoomScale = restoreState.mMaxScale; 6852 } 6853 } 6854 6855 /* 6856 * Request a dropdown menu for a listbox with single selection or a single 6857 * <select> element. 6858 * 6859 * @param array Labels for the listbox. 6860 * @param enabledArray State for each element in the list. See static 6861 * integers in Container class. 6862 * @param selection Which position is initally selected. 6863 */ 6864 void requestListBox(String[] array, int[] enabledArray, int selection) { 6865 mPrivateHandler.post( 6866 new InvokeListBox(array, enabledArray, selection)); 6867 } 6868 6869 // called by JNI 6870 private void sendMoveFocus(int frame, int node) { 6871 mWebViewCore.sendMessage(EventHub.SET_MOVE_FOCUS, 6872 new WebViewCore.CursorData(frame, node, 0, 0)); 6873 } 6874 6875 // called by JNI 6876 private void sendMoveMouse(int frame, int node, int x, int y) { 6877 mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE, 6878 new WebViewCore.CursorData(frame, node, x, y)); 6879 } 6880 6881 /* 6882 * Send a mouse move event to the webcore thread. 6883 * 6884 * @param removeFocus Pass true if the "mouse" cursor is now over a node 6885 * which wants key events, but it is not the focus. This 6886 * will make the visual appear as though nothing is in 6887 * focus. Remove the WebTextView, if present, and stop 6888 * drawing the blinking caret. 6889 * called by JNI 6890 */ 6891 private void sendMoveMouseIfLatest(boolean removeFocus) { 6892 if (removeFocus) { 6893 clearTextEntry(true); 6894 } 6895 mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE_IF_LATEST, 6896 cursorData()); 6897 } 6898 6899 // called by JNI 6900 private void sendMotionUp(int touchGeneration, 6901 int frame, int node, int x, int y) { 6902 WebViewCore.TouchUpData touchUpData = new WebViewCore.TouchUpData(); 6903 touchUpData.mMoveGeneration = touchGeneration; 6904 touchUpData.mFrame = frame; 6905 touchUpData.mNode = node; 6906 touchUpData.mX = x; 6907 touchUpData.mY = y; 6908 mWebViewCore.sendMessage(EventHub.TOUCH_UP, touchUpData); 6909 } 6910 6911 6912 private int getScaledMaxXScroll() { 6913 int width; 6914 if (mHeightCanMeasure == false) { 6915 width = getViewWidth() / 4; 6916 } else { 6917 Rect visRect = new Rect(); 6918 calcOurVisibleRect(visRect); 6919 width = visRect.width() / 2; 6920 } 6921 // FIXME the divisor should be retrieved from somewhere 6922 return viewToContentX(width); 6923 } 6924 6925 private int getScaledMaxYScroll() { 6926 int height; 6927 if (mHeightCanMeasure == false) { 6928 height = getViewHeight() / 4; 6929 } else { 6930 Rect visRect = new Rect(); 6931 calcOurVisibleRect(visRect); 6932 height = visRect.height() / 2; 6933 } 6934 // FIXME the divisor should be retrieved from somewhere 6935 // the closest thing today is hard-coded into ScrollView.java 6936 // (from ScrollView.java, line 363) int maxJump = height/2; 6937 return Math.round(height * mInvActualScale); 6938 } 6939 6940 /** 6941 * Called by JNI to invalidate view 6942 */ 6943 private void viewInvalidate() { 6944 invalidate(); 6945 } 6946 6947 /** 6948 * Pass the key to the plugin. This assumes that nativeFocusIsPlugin() 6949 * returned true. 6950 */ 6951 private void letPluginHandleNavKey(int keyCode, long time, boolean down) { 6952 int keyEventAction; 6953 int eventHubAction; 6954 if (down) { 6955 keyEventAction = KeyEvent.ACTION_DOWN; 6956 eventHubAction = EventHub.KEY_DOWN; 6957 playSoundEffect(keyCodeToSoundsEffect(keyCode)); 6958 } else { 6959 keyEventAction = KeyEvent.ACTION_UP; 6960 eventHubAction = EventHub.KEY_UP; 6961 } 6962 KeyEvent event = new KeyEvent(time, time, keyEventAction, keyCode, 6963 1, (mShiftIsPressed ? KeyEvent.META_SHIFT_ON : 0) 6964 | (false ? KeyEvent.META_ALT_ON : 0) // FIXME 6965 | (false ? KeyEvent.META_SYM_ON : 0) // FIXME 6966 , 0, 0, 0); 6967 mWebViewCore.sendMessage(eventHubAction, event); 6968 } 6969 6970 // return true if the key was handled 6971 private boolean navHandledKey(int keyCode, int count, boolean noScroll, 6972 long time) { 6973 if (mNativeClass == 0) { 6974 return false; 6975 } 6976 mLastCursorTime = time; 6977 mLastCursorBounds = nativeGetCursorRingBounds(); 6978 boolean keyHandled 6979 = nativeMoveCursor(keyCode, count, noScroll) == false; 6980 if (DebugFlags.WEB_VIEW) { 6981 Log.v(LOGTAG, "navHandledKey mLastCursorBounds=" + mLastCursorBounds 6982 + " mLastCursorTime=" + mLastCursorTime 6983 + " handled=" + keyHandled); 6984 } 6985 if (keyHandled == false || mHeightCanMeasure == false) { 6986 return keyHandled; 6987 } 6988 Rect contentCursorRingBounds = nativeGetCursorRingBounds(); 6989 if (contentCursorRingBounds.isEmpty()) return keyHandled; 6990 Rect viewCursorRingBounds = contentToViewRect(contentCursorRingBounds); 6991 Rect visRect = new Rect(); 6992 calcOurVisibleRect(visRect); 6993 Rect outset = new Rect(visRect); 6994 int maxXScroll = visRect.width() / 2; 6995 int maxYScroll = visRect.height() / 2; 6996 outset.inset(-maxXScroll, -maxYScroll); 6997 if (Rect.intersects(outset, viewCursorRingBounds) == false) { 6998 return keyHandled; 6999 } 7000 // FIXME: Necessary because ScrollView/ListView do not scroll left/right 7001 int maxH = Math.min(viewCursorRingBounds.right - visRect.right, 7002 maxXScroll); 7003 if (maxH > 0) { 7004 pinScrollBy(maxH, 0, true, 0); 7005 } else { 7006 maxH = Math.max(viewCursorRingBounds.left - visRect.left, 7007 -maxXScroll); 7008 if (maxH < 0) { 7009 pinScrollBy(maxH, 0, true, 0); 7010 } 7011 } 7012 if (mLastCursorBounds.isEmpty()) return keyHandled; 7013 if (mLastCursorBounds.equals(contentCursorRingBounds)) { 7014 return keyHandled; 7015 } 7016 if (DebugFlags.WEB_VIEW) { 7017 Log.v(LOGTAG, "navHandledKey contentCursorRingBounds=" 7018 + contentCursorRingBounds); 7019 } 7020 requestRectangleOnScreen(viewCursorRingBounds); 7021 mUserScroll = true; 7022 return keyHandled; 7023 } 7024 7025 /** 7026 * Set the background color. It's white by default. Pass 7027 * zero to make the view transparent. 7028 * @param color the ARGB color described by Color.java 7029 */ 7030 public void setBackgroundColor(int color) { 7031 mBackgroundColor = color; 7032 mWebViewCore.sendMessage(EventHub.SET_BACKGROUND_COLOR, color); 7033 } 7034 7035 public void debugDump() { 7036 nativeDebugDump(); 7037 mWebViewCore.sendMessage(EventHub.DUMP_NAVTREE); 7038 } 7039 7040 /** 7041 * Draw the HTML page into the specified canvas. This call ignores any 7042 * view-specific zoom, scroll offset, or other changes. It does not draw 7043 * any view-specific chrome, such as progress or URL bars. 7044 * 7045 * @hide only needs to be accessible to Browser and testing 7046 */ 7047 public void drawPage(Canvas canvas) { 7048 mWebViewCore.drawContentPicture(canvas, 0, false, false); 7049 } 7050 7051 /** 7052 * Set the time to wait between passing touches to WebCore. See also the 7053 * TOUCH_SENT_INTERVAL member for further discussion. 7054 * 7055 * @hide This is only used by the DRT test application. 7056 */ 7057 public void setTouchInterval(int interval) { 7058 mCurrentTouchInterval = interval; 7059 } 7060 7061 /** 7062 * Update our cache with updatedText. 7063 * @param updatedText The new text to put in our cache. 7064 */ 7065 /* package */ void updateCachedTextfield(String updatedText) { 7066 // Also place our generation number so that when we look at the cache 7067 // we recognize that it is up to date. 7068 nativeUpdateCachedTextfield(updatedText, mTextGeneration); 7069 } 7070 7071 private native int nativeCacheHitFramePointer(); 7072 private native Rect nativeCacheHitNodeBounds(); 7073 private native int nativeCacheHitNodePointer(); 7074 /* package */ native void nativeClearCursor(); 7075 private native void nativeCreate(int ptr); 7076 private native int nativeCursorFramePointer(); 7077 private native Rect nativeCursorNodeBounds(); 7078 private native int nativeCursorNodePointer(); 7079 /* package */ native boolean nativeCursorMatchesFocus(); 7080 private native boolean nativeCursorIntersects(Rect visibleRect); 7081 private native boolean nativeCursorIsAnchor(); 7082 private native boolean nativeCursorIsTextInput(); 7083 private native Point nativeCursorPosition(); 7084 private native String nativeCursorText(); 7085 /** 7086 * Returns true if the native cursor node says it wants to handle key events 7087 * (ala plugins). This can only be called if mNativeClass is non-zero! 7088 */ 7089 private native boolean nativeCursorWantsKeyEvents(); 7090 private native void nativeDebugDump(); 7091 private native void nativeDestroy(); 7092 private native boolean nativeEvaluateLayersAnimations(); 7093 private native void nativeDrawExtras(Canvas canvas, int extra); 7094 private native void nativeDumpDisplayTree(String urlOrNull); 7095 private native int nativeFindAll(String findLower, String findUpper); 7096 private native void nativeFindNext(boolean forward); 7097 /* package */ native int nativeFocusCandidateFramePointer(); 7098 private native boolean nativeFocusCandidateIsPassword(); 7099 private native boolean nativeFocusCandidateIsRtlText(); 7100 private native boolean nativeFocusCandidateIsTextInput(); 7101 /* package */ native int nativeFocusCandidateMaxLength(); 7102 /* package */ native String nativeFocusCandidateName(); 7103 private native Rect nativeFocusCandidateNodeBounds(); 7104 private native int nativeFocusCandidatePointer(); 7105 private native String nativeFocusCandidateText(); 7106 private native int nativeFocusCandidateTextSize(); 7107 /** 7108 * Returns an integer corresponding to WebView.cpp::type. 7109 * See WebTextView.setType() 7110 */ 7111 private native int nativeFocusCandidateType(); 7112 private native boolean nativeFocusIsPlugin(); 7113 /* package */ native int nativeFocusNodePointer(); 7114 private native Rect nativeGetCursorRingBounds(); 7115 private native String nativeGetSelection(); 7116 private native boolean nativeHasCursorNode(); 7117 private native boolean nativeHasFocusNode(); 7118 private native void nativeHideCursor(); 7119 private native String nativeImageURI(int x, int y); 7120 private native void nativeInstrumentReport(); 7121 /* package */ native boolean nativeMoveCursorToNextTextInput(); 7122 // return true if the page has been scrolled 7123 private native boolean nativeMotionUp(int x, int y, int slop); 7124 // returns false if it handled the key 7125 private native boolean nativeMoveCursor(int keyCode, int count, 7126 boolean noScroll); 7127 private native int nativeMoveGeneration(); 7128 private native void nativeMoveSelection(int x, int y, 7129 boolean extendSelection); 7130 private native boolean nativePointInNavCache(int x, int y, int slop); 7131 // Like many other of our native methods, you must make sure that 7132 // mNativeClass is not null before calling this method. 7133 private native void nativeRecordButtons(boolean focused, 7134 boolean pressed, boolean invalidate); 7135 private native void nativeSelectBestAt(Rect rect); 7136 private native void nativeSetFindIsEmpty(); 7137 private native void nativeSetFindIsUp(boolean isUp); 7138 private native void nativeSetFollowedLink(boolean followed); 7139 private native void nativeSetHeightCanMeasure(boolean measure); 7140 private native void nativeSetRootLayer(int layer); 7141 private native void nativeSetSelectionPointer(boolean set, 7142 float scale, int x, int y, boolean extendSelection); 7143 private native void nativeSetSelectionRegion(boolean set); 7144 private native Rect nativeSubtractLayers(Rect content); 7145 private native int nativeTextGeneration(); 7146 // Never call this version except by updateCachedTextfield(String) - 7147 // we always want to pass in our generation number. 7148 private native void nativeUpdateCachedTextfield(String updatedText, 7149 int generation); 7150 // return NO_LEFTEDGE means failure. 7151 private static final int NO_LEFTEDGE = -1; 7152 private native int nativeGetBlockLeftEdge(int x, int y, float scale); 7153} 7154