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