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