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