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