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