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