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