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