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