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