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