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