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