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