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