WebView.java revision 6b53e8daa69cba1a2a5a7c95a01e37ce9c53226c
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 mWebViewCore = new WebViewCore(context, this, mCallbackProxy, javascriptInterfaces); 910 mDatabase = WebViewDatabase.getInstance(context); 911 mScroller = new Scroller(context); 912 mZoomManager = new ZoomManager(this, mCallbackProxy); 913 914 /* The init method must follow the creation of certain member variables, 915 * such as the mZoomManager. 916 */ 917 init(); 918 setupPackageListener(context); 919 updateMultiTouchSupport(context); 920 921 if (privateBrowsing) { 922 startPrivateBrowsing(); 923 } 924 925 L10nUtils.loadStrings(context); 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 * Since we draw the title bar ourselves, we removed the shadow from the 2191 * browser's activity. We do want a shadow at the bottom of the title bar, 2192 * or at the top of the screen if the title bar is not visible. This 2193 * drawable serves that purpose. 2194 */ 2195 private Drawable mTitleShadow; 2196 2197 /** 2198 * Add or remove a title bar to be embedded into the WebView, and scroll 2199 * along with it vertically, while remaining in view horizontally. Pass 2200 * null to remove the title bar from the WebView, and return to drawing 2201 * the WebView normally without translating to account for the title bar. 2202 * @hide 2203 */ 2204 public void setEmbeddedTitleBar(View v) { 2205 if (null == v) { 2206 // If one of our callbacks is holding onto the titlebar to replace 2207 // it when its ActionMode ends, remove it. 2208 if (mSelectCallback != null) { 2209 mSelectCallback.setTitleBar(null); 2210 } 2211 if (mFindCallback != null) { 2212 mFindCallback.setTitleBar(null); 2213 } 2214 } 2215 if (mTitleBar == v) return; 2216 if (mTitleBar != null) { 2217 removeView(mTitleBar); 2218 } 2219 if (null != v) { 2220 addView(v, new AbsoluteLayout.LayoutParams( 2221 ViewGroup.LayoutParams.MATCH_PARENT, 2222 ViewGroup.LayoutParams.WRAP_CONTENT, 0, 0)); 2223 if (mTitleShadow == null) { 2224 mTitleShadow = (Drawable) mContext.getResources().getDrawable( 2225 com.android.internal.R.drawable.title_bar_shadow); 2226 } 2227 } 2228 mTitleBar = v; 2229 } 2230 2231 /** 2232 * Given a distance in view space, convert it to content space. Note: this 2233 * does not reflect translation, just scaling, so this should not be called 2234 * with coordinates, but should be called for dimensions like width or 2235 * height. 2236 */ 2237 private int viewToContentDimension(int d) { 2238 return Math.round(d * mZoomManager.getInvScale()); 2239 } 2240 2241 /** 2242 * Given an x coordinate in view space, convert it to content space. Also 2243 * may be used for absolute heights (such as for the WebTextView's 2244 * textSize, which is unaffected by the height of the title bar). 2245 */ 2246 /*package*/ int viewToContentX(int x) { 2247 return viewToContentDimension(x); 2248 } 2249 2250 /** 2251 * Given a y coordinate in view space, convert it to content space. 2252 * Takes into account the height of the title bar if there is one 2253 * embedded into the WebView. 2254 */ 2255 /*package*/ int viewToContentY(int y) { 2256 return viewToContentDimension(y - getTitleHeight()); 2257 } 2258 2259 /** 2260 * Given a x coordinate in view space, convert it to content space. 2261 * Returns the result as a float. 2262 */ 2263 private float viewToContentXf(int x) { 2264 return x * mZoomManager.getInvScale(); 2265 } 2266 2267 /** 2268 * Given a y coordinate in view space, convert it to content space. 2269 * Takes into account the height of the title bar if there is one 2270 * embedded into the WebView. Returns the result as a float. 2271 */ 2272 private float viewToContentYf(int y) { 2273 return (y - getTitleHeight()) * mZoomManager.getInvScale(); 2274 } 2275 2276 /** 2277 * Given a distance in content space, convert it to view space. Note: this 2278 * does not reflect translation, just scaling, so this should not be called 2279 * with coordinates, but should be called for dimensions like width or 2280 * height. 2281 */ 2282 /*package*/ int contentToViewDimension(int d) { 2283 return Math.round(d * mZoomManager.getScale()); 2284 } 2285 2286 /** 2287 * Given an x coordinate in content space, convert it to view 2288 * space. 2289 */ 2290 /*package*/ int contentToViewX(int x) { 2291 return contentToViewDimension(x); 2292 } 2293 2294 /** 2295 * Given a y coordinate in content space, convert it to view 2296 * space. Takes into account the height of the title bar. 2297 */ 2298 /*package*/ int contentToViewY(int y) { 2299 return contentToViewDimension(y) + getTitleHeight(); 2300 } 2301 2302 private Rect contentToViewRect(Rect x) { 2303 return new Rect(contentToViewX(x.left), contentToViewY(x.top), 2304 contentToViewX(x.right), contentToViewY(x.bottom)); 2305 } 2306 2307 /* To invalidate a rectangle in content coordinates, we need to transform 2308 the rect into view coordinates, so we can then call invalidate(...). 2309 2310 Normally, we would just call contentToView[XY](...), which eventually 2311 calls Math.round(coordinate * mActualScale). However, for invalidates, 2312 we need to account for the slop that occurs with antialiasing. To 2313 address that, we are a little more liberal in the size of the rect that 2314 we invalidate. 2315 2316 This liberal calculation calls floor() for the top/left, and ceil() for 2317 the bottom/right coordinates. This catches the possible extra pixels of 2318 antialiasing that we might have missed with just round(). 2319 */ 2320 2321 // Called by JNI to invalidate the View, given rectangle coordinates in 2322 // content space 2323 private void viewInvalidate(int l, int t, int r, int b) { 2324 final float scale = mZoomManager.getScale(); 2325 final int dy = getTitleHeight(); 2326 invalidate((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 // Called by JNI to invalidate the View after a delay, given rectangle 2333 // coordinates in content space 2334 private void viewInvalidateDelayed(long delay, int l, int t, int r, int b) { 2335 final float scale = mZoomManager.getScale(); 2336 final int dy = getTitleHeight(); 2337 postInvalidateDelayed(delay, 2338 (int)Math.floor(l * scale), 2339 (int)Math.floor(t * scale) + dy, 2340 (int)Math.ceil(r * scale), 2341 (int)Math.ceil(b * scale) + dy); 2342 } 2343 2344 private void invalidateContentRect(Rect r) { 2345 viewInvalidate(r.left, r.top, r.right, r.bottom); 2346 } 2347 2348 // stop the scroll animation, and don't let a subsequent fling add 2349 // to the existing velocity 2350 private void abortAnimation() { 2351 mScroller.abortAnimation(); 2352 mLastVelocity = 0; 2353 } 2354 2355 /* call from webcoreview.draw(), so we're still executing in the UI thread 2356 */ 2357 private void recordNewContentSize(int w, int h, boolean updateLayout) { 2358 2359 // premature data from webkit, ignore 2360 if ((w | h) == 0) { 2361 return; 2362 } 2363 2364 // don't abort a scroll animation if we didn't change anything 2365 if (mContentWidth != w || mContentHeight != h) { 2366 // record new dimensions 2367 mContentWidth = w; 2368 mContentHeight = h; 2369 // If history Picture is drawn, don't update scroll. They will be 2370 // updated when we get out of that mode. 2371 if (!mDrawHistory) { 2372 // repin our scroll, taking into account the new content size 2373 updateScrollCoordinates(pinLocX(mScrollX), pinLocY(mScrollY)); 2374 if (!mScroller.isFinished()) { 2375 // We are in the middle of a scroll. Repin the final scroll 2376 // position. 2377 mScroller.setFinalX(pinLocX(mScroller.getFinalX())); 2378 mScroller.setFinalY(pinLocY(mScroller.getFinalY())); 2379 } 2380 } 2381 } 2382 contentSizeChanged(updateLayout); 2383 } 2384 2385 // Used to avoid sending many visible rect messages. 2386 private Rect mLastVisibleRectSent; 2387 private Rect mLastGlobalRect; 2388 2389 Rect sendOurVisibleRect() { 2390 if (mZoomManager.isPreventingWebkitUpdates()) return mLastVisibleRectSent; 2391 Rect rect = new Rect(); 2392 calcOurContentVisibleRect(rect); 2393 // Rect.equals() checks for null input. 2394 if (!rect.equals(mLastVisibleRectSent)) { 2395 Point pos = new Point(rect.left, rect.top); 2396 mWebViewCore.sendMessage(EventHub.SET_SCROLL_OFFSET, 2397 nativeMoveGeneration(), mUserScroll ? 1 : 0, pos); 2398 mLastVisibleRectSent = rect; 2399 } 2400 Rect globalRect = new Rect(); 2401 if (getGlobalVisibleRect(globalRect) 2402 && !globalRect.equals(mLastGlobalRect)) { 2403 if (DebugFlags.WEB_VIEW) { 2404 Log.v(LOGTAG, "sendOurVisibleRect=(" + globalRect.left + "," 2405 + globalRect.top + ",r=" + globalRect.right + ",b=" 2406 + globalRect.bottom); 2407 } 2408 // TODO: the global offset is only used by windowRect() 2409 // in ChromeClientAndroid ; other clients such as touch 2410 // and mouse events could return view + screen relative points. 2411 mWebViewCore.sendMessage(EventHub.SET_GLOBAL_BOUNDS, globalRect); 2412 mLastGlobalRect = globalRect; 2413 } 2414 return rect; 2415 } 2416 2417 // Sets r to be the visible rectangle of our webview in view coordinates 2418 private void calcOurVisibleRect(Rect r) { 2419 Point p = new Point(); 2420 getGlobalVisibleRect(r, p); 2421 r.offset(-p.x, -p.y); 2422 } 2423 2424 // Sets r to be our visible rectangle in content coordinates 2425 private void calcOurContentVisibleRect(Rect r) { 2426 calcOurVisibleRect(r); 2427 // pin the rect to the bounds of the content 2428 r.left = Math.max(viewToContentX(r.left), 0); 2429 // viewToContentY will remove the total height of the title bar. Add 2430 // the visible height back in to account for the fact that if the title 2431 // bar is partially visible, the part of the visible rect which is 2432 // displaying our content is displaced by that amount. 2433 r.top = Math.max(viewToContentY(r.top + getVisibleTitleHeight()), 0); 2434 r.right = Math.min(viewToContentX(r.right), mContentWidth); 2435 r.bottom = Math.min(viewToContentY(r.bottom), mContentHeight); 2436 } 2437 2438 // Sets r to be our visible rectangle in content coordinates. We use this 2439 // method on the native side to compute the position of the fixed layers. 2440 // Uses floating coordinates (necessary to correctly place elements when 2441 // the scale factor is not 1) 2442 private void calcOurContentVisibleRectF(RectF r) { 2443 Rect ri = new Rect(0,0,0,0); 2444 calcOurVisibleRect(ri); 2445 // pin the rect to the bounds of the content 2446 r.left = Math.max(viewToContentXf(ri.left), 0.0f); 2447 // viewToContentY will remove the total height of the title bar. Add 2448 // the visible height back in to account for the fact that if the title 2449 // bar is partially visible, the part of the visible rect which is 2450 // displaying our content is displaced by that amount. 2451 r.top = Math.max(viewToContentYf(ri.top + getVisibleTitleHeight()), 0.0f); 2452 r.right = Math.min(viewToContentXf(ri.right), (float)mContentWidth); 2453 r.bottom = Math.min(viewToContentYf(ri.bottom), (float)mContentHeight); 2454 } 2455 2456 static class ViewSizeData { 2457 int mWidth; 2458 int mHeight; 2459 int mTextWrapWidth; 2460 int mAnchorX; 2461 int mAnchorY; 2462 float mScale; 2463 boolean mIgnoreHeight; 2464 } 2465 2466 /** 2467 * Compute unzoomed width and height, and if they differ from the last 2468 * values we sent, send them to webkit (to be used as new viewport) 2469 * 2470 * @param force ensures that the message is sent to webkit even if the width 2471 * or height has not changed since the last message 2472 * 2473 * @return true if new values were sent 2474 */ 2475 boolean sendViewSizeZoom(boolean force) { 2476 if (mZoomManager.isPreventingWebkitUpdates()) return false; 2477 2478 int viewWidth = getViewWidth(); 2479 int newWidth = Math.round(viewWidth * mZoomManager.getInvScale()); 2480 int newHeight = Math.round((getViewHeightWithTitle() - getTitleHeight()) * mZoomManager.getInvScale()); 2481 /* 2482 * Because the native side may have already done a layout before the 2483 * View system was able to measure us, we have to send a height of 0 to 2484 * remove excess whitespace when we grow our width. This will trigger a 2485 * layout and a change in content size. This content size change will 2486 * mean that contentSizeChanged will either call this method directly or 2487 * indirectly from onSizeChanged. 2488 */ 2489 if (newWidth > mLastWidthSent && mWrapContent) { 2490 newHeight = 0; 2491 } 2492 // Avoid sending another message if the dimensions have not changed. 2493 if (newWidth != mLastWidthSent || newHeight != mLastHeightSent || force) { 2494 ViewSizeData data = new ViewSizeData(); 2495 data.mWidth = newWidth; 2496 data.mHeight = newHeight; 2497 data.mTextWrapWidth = Math.round(viewWidth / mZoomManager.getTextWrapScale()); 2498 data.mScale = mZoomManager.getScale(); 2499 data.mIgnoreHeight = mZoomManager.isFixedLengthAnimationInProgress() 2500 && !mHeightCanMeasure; 2501 data.mAnchorX = mZoomManager.getDocumentAnchorX(); 2502 data.mAnchorY = mZoomManager.getDocumentAnchorY(); 2503 mWebViewCore.sendMessage(EventHub.VIEW_SIZE_CHANGED, data); 2504 mLastWidthSent = newWidth; 2505 mLastHeightSent = newHeight; 2506 mZoomManager.clearDocumentAnchor(); 2507 return true; 2508 } 2509 return false; 2510 } 2511 2512 @Override 2513 protected int computeHorizontalScrollRange() { 2514 if (mDrawHistory) { 2515 return mHistoryWidth; 2516 } else if (mHorizontalScrollBarMode == SCROLLBAR_ALWAYSOFF 2517 && !mZoomManager.canZoomOut()) { 2518 // only honor the scrollbar mode when it is at minimum zoom level 2519 return computeHorizontalScrollExtent(); 2520 } else { 2521 // to avoid rounding error caused unnecessary scrollbar, use floor 2522 return (int) Math.floor(mContentWidth * mZoomManager.getScale()); 2523 } 2524 } 2525 2526 @Override 2527 protected int computeVerticalScrollRange() { 2528 if (mDrawHistory) { 2529 return mHistoryHeight; 2530 } else if (mVerticalScrollBarMode == SCROLLBAR_ALWAYSOFF 2531 && !mZoomManager.canZoomOut()) { 2532 // only honor the scrollbar mode when it is at minimum zoom level 2533 return computeVerticalScrollExtent(); 2534 } else { 2535 // to avoid rounding error caused unnecessary scrollbar, use floor 2536 return (int) Math.floor(mContentHeight * mZoomManager.getScale()); 2537 } 2538 } 2539 2540 @Override 2541 protected int computeVerticalScrollOffset() { 2542 return Math.max(mScrollY - getTitleHeight(), 0); 2543 } 2544 2545 @Override 2546 protected int computeVerticalScrollExtent() { 2547 return getViewHeight(); 2548 } 2549 2550 /** @hide */ 2551 @Override 2552 protected void onDrawVerticalScrollBar(Canvas canvas, 2553 Drawable scrollBar, 2554 int l, int t, int r, int b) { 2555 scrollBar.setBounds(l, t + getVisibleTitleHeight(), r, b); 2556 scrollBar.draw(canvas); 2557 } 2558 2559 /** 2560 * Get the url for the current page. This is not always the same as the url 2561 * passed to WebViewClient.onPageStarted because although the load for 2562 * that url has begun, the current page may not have changed. 2563 * @return The url for the current page. 2564 */ 2565 public String getUrl() { 2566 WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem(); 2567 return h != null ? h.getUrl() : null; 2568 } 2569 2570 /** 2571 * Get the original url for the current page. This is not always the same 2572 * as the url passed to WebViewClient.onPageStarted because although the 2573 * load for that url has begun, the current page may not have changed. 2574 * Also, there may have been redirects resulting in a different url to that 2575 * originally requested. 2576 * @return The url that was originally requested for the current page. 2577 */ 2578 public String getOriginalUrl() { 2579 WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem(); 2580 return h != null ? h.getOriginalUrl() : null; 2581 } 2582 2583 /** 2584 * Get the title for the current page. This is the title of the current page 2585 * until WebViewClient.onReceivedTitle is called. 2586 * @return The title for the current page. 2587 */ 2588 public String getTitle() { 2589 WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem(); 2590 return h != null ? h.getTitle() : null; 2591 } 2592 2593 /** 2594 * Get the favicon for the current page. This is the favicon of the current 2595 * page until WebViewClient.onReceivedIcon is called. 2596 * @return The favicon for the current page. 2597 */ 2598 public Bitmap getFavicon() { 2599 WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem(); 2600 return h != null ? h.getFavicon() : null; 2601 } 2602 2603 /** 2604 * Get the touch icon url for the apple-touch-icon <link> element, or 2605 * a URL on this site's server pointing to the standard location of a 2606 * touch icon. 2607 * @hide 2608 */ 2609 public String getTouchIconUrl() { 2610 WebHistoryItem h = mCallbackProxy.getBackForwardList().getCurrentItem(); 2611 return h != null ? h.getTouchIconUrl() : null; 2612 } 2613 2614 /** 2615 * Get the progress for the current page. 2616 * @return The progress for the current page between 0 and 100. 2617 */ 2618 public int getProgress() { 2619 return mCallbackProxy.getProgress(); 2620 } 2621 2622 /** 2623 * @return the height of the HTML content. 2624 */ 2625 public int getContentHeight() { 2626 return mContentHeight; 2627 } 2628 2629 /** 2630 * @return the width of the HTML content. 2631 * @hide 2632 */ 2633 public int getContentWidth() { 2634 return mContentWidth; 2635 } 2636 2637 /** 2638 * Pause all layout, parsing, and javascript timers for all webviews. This 2639 * is a global requests, not restricted to just this webview. This can be 2640 * useful if the application has been paused. 2641 */ 2642 public void pauseTimers() { 2643 mWebViewCore.sendMessage(EventHub.PAUSE_TIMERS); 2644 } 2645 2646 /** 2647 * Resume all layout, parsing, and javascript timers for all webviews. 2648 * This will resume dispatching all timers. 2649 */ 2650 public void resumeTimers() { 2651 mWebViewCore.sendMessage(EventHub.RESUME_TIMERS); 2652 } 2653 2654 /** 2655 * Call this to pause any extra processing associated with this view and 2656 * its associated DOM/plugins/javascript/etc. For example, if the view is 2657 * taken offscreen, this could be called to reduce unnecessary CPU and/or 2658 * network traffic. When the view is again "active", call onResume(). 2659 * 2660 * Note that this differs from pauseTimers(), which affects all views/DOMs 2661 * @hide 2662 */ 2663 public void onPause() { 2664 if (!mIsPaused) { 2665 mIsPaused = true; 2666 mWebViewCore.sendMessage(EventHub.ON_PAUSE); 2667 } 2668 } 2669 2670 /** 2671 * Call this to balanace a previous call to onPause() 2672 * @hide 2673 */ 2674 public void onResume() { 2675 if (mIsPaused) { 2676 mIsPaused = false; 2677 mWebViewCore.sendMessage(EventHub.ON_RESUME); 2678 } 2679 } 2680 2681 /** 2682 * Returns true if the view is paused, meaning onPause() was called. Calling 2683 * onResume() sets the paused state back to false. 2684 * @hide 2685 */ 2686 public boolean isPaused() { 2687 return mIsPaused; 2688 } 2689 2690 /** 2691 * Call this to inform the view that memory is low so that it can 2692 * free any available memory. 2693 */ 2694 public void freeMemory() { 2695 mWebViewCore.sendMessage(EventHub.FREE_MEMORY); 2696 } 2697 2698 /** 2699 * Clear the resource cache. Note that the cache is per-application, so 2700 * this will clear the cache for all WebViews used. 2701 * 2702 * @param includeDiskFiles If false, only the RAM cache is cleared. 2703 */ 2704 public void clearCache(boolean includeDiskFiles) { 2705 // Note: this really needs to be a static method as it clears cache for all 2706 // WebView. But we need mWebViewCore to send message to WebCore thread, so 2707 // we can't make this static. 2708 mWebViewCore.sendMessage(EventHub.CLEAR_CACHE, 2709 includeDiskFiles ? 1 : 0, 0); 2710 } 2711 2712 /** 2713 * Make sure that clearing the form data removes the adapter from the 2714 * currently focused textfield if there is one. 2715 */ 2716 public void clearFormData() { 2717 if (inEditingMode()) { 2718 AutoCompleteAdapter adapter = null; 2719 mWebTextView.setAdapterCustom(adapter); 2720 } 2721 } 2722 2723 /** 2724 * Tell the WebView to clear its internal back/forward list. 2725 */ 2726 public void clearHistory() { 2727 mCallbackProxy.getBackForwardList().setClearPending(); 2728 mWebViewCore.sendMessage(EventHub.CLEAR_HISTORY); 2729 } 2730 2731 /** 2732 * Clear the SSL preferences table stored in response to proceeding with SSL 2733 * certificate errors. 2734 */ 2735 public void clearSslPreferences() { 2736 mWebViewCore.sendMessage(EventHub.CLEAR_SSL_PREF_TABLE); 2737 } 2738 2739 /** 2740 * Return the WebBackForwardList for this WebView. This contains the 2741 * back/forward list for use in querying each item in the history stack. 2742 * This is a copy of the private WebBackForwardList so it contains only a 2743 * snapshot of the current state. Multiple calls to this method may return 2744 * different objects. The object returned from this method will not be 2745 * updated to reflect any new state. 2746 */ 2747 public WebBackForwardList copyBackForwardList() { 2748 return mCallbackProxy.getBackForwardList().clone(); 2749 } 2750 2751 /* 2752 * Highlight and scroll to the next occurance of String in findAll. 2753 * Wraps the page infinitely, and scrolls. Must be called after 2754 * calling findAll. 2755 * 2756 * @param forward Direction to search. 2757 */ 2758 public void findNext(boolean forward) { 2759 if (0 == mNativeClass) return; // client isn't initialized 2760 nativeFindNext(forward); 2761 } 2762 2763 /* 2764 * Find all instances of find on the page and highlight them. 2765 * @param find String to find. 2766 * @return int The number of occurances of the String "find" 2767 * that were found. 2768 */ 2769 public int findAll(String find) { 2770 if (0 == mNativeClass) return 0; // client isn't initialized 2771 int result = find != null ? nativeFindAll(find.toLowerCase(), 2772 find.toUpperCase(), find.equalsIgnoreCase(mLastFind)) : 0; 2773 invalidate(); 2774 mLastFind = find; 2775 return result; 2776 } 2777 2778 /** 2779 * Start an ActionMode for finding text in this WebView. 2780 * @param text If non-null, will be the initial text to search for. 2781 * Otherwise, the last String searched for in this WebView will 2782 * be used to start. 2783 */ 2784 public void showFindDialog(String text) { 2785 mFindCallback = new FindActionModeCallback(mContext); 2786 setFindIsUp(true); 2787 mFindCallback.setWebView(this); 2788 View titleBar = mTitleBar; 2789 // We do not want to show the embedded title bar during find or 2790 // select, but keep track of it so that it can be replaced when the 2791 // mode is exited. 2792 setEmbeddedTitleBar(null); 2793 mFindCallback.setTitleBar(titleBar); 2794 startActionMode(mFindCallback); 2795 if (text == null) { 2796 text = mLastFind; 2797 } 2798 if (text != null) { 2799 mFindCallback.setText(text); 2800 } 2801 } 2802 2803 /** 2804 * Keep track of the find callback so that we can remove its titlebar if 2805 * necessary. 2806 */ 2807 private FindActionModeCallback mFindCallback; 2808 2809 /** 2810 * Toggle whether the find dialog is showing, for both native and Java. 2811 */ 2812 private void setFindIsUp(boolean isUp) { 2813 mFindIsUp = isUp; 2814 if (0 == mNativeClass) return; // client isn't initialized 2815 nativeSetFindIsUp(isUp); 2816 } 2817 2818 /** 2819 * Return the index of the currently highlighted match. 2820 */ 2821 int findIndex() { 2822 if (0 == mNativeClass) return -1; 2823 return nativeFindIndex(); 2824 } 2825 2826 // Used to know whether the find dialog is open. Affects whether 2827 // or not we draw the highlights for matches. 2828 private boolean mFindIsUp; 2829 2830 // Keep track of the last string sent, so we can search again when find is 2831 // reopened. 2832 private String mLastFind; 2833 2834 /** 2835 * Return the first substring consisting of the address of a physical 2836 * location. Currently, only addresses in the United States are detected, 2837 * and consist of: 2838 * - a house number 2839 * - a street name 2840 * - a street type (Road, Circle, etc), either spelled out or abbreviated 2841 * - a city name 2842 * - a state or territory, either spelled out or two-letter abbr. 2843 * - an optional 5 digit or 9 digit zip code. 2844 * 2845 * All names must be correctly capitalized, and the zip code, if present, 2846 * must be valid for the state. The street type must be a standard USPS 2847 * spelling or abbreviation. The state or territory must also be spelled 2848 * or abbreviated using USPS standards. The house number may not exceed 2849 * five digits. 2850 * @param addr The string to search for addresses. 2851 * 2852 * @return the address, or if no address is found, return null. 2853 */ 2854 public static String findAddress(String addr) { 2855 return findAddress(addr, false); 2856 } 2857 2858 /** 2859 * @hide 2860 * Return the first substring consisting of the address of a physical 2861 * location. Currently, only addresses in the United States are detected, 2862 * and consist of: 2863 * - a house number 2864 * - a street name 2865 * - a street type (Road, Circle, etc), either spelled out or abbreviated 2866 * - a city name 2867 * - a state or territory, either spelled out or two-letter abbr. 2868 * - an optional 5 digit or 9 digit zip code. 2869 * 2870 * Names are optionally capitalized, and the zip code, if present, 2871 * must be valid for the state. The street type must be a standard USPS 2872 * spelling or abbreviation. The state or territory must also be spelled 2873 * or abbreviated using USPS standards. The house number may not exceed 2874 * five digits. 2875 * @param addr The string to search for addresses. 2876 * @param caseInsensitive addr Set to true to make search ignore case. 2877 * 2878 * @return the address, or if no address is found, return null. 2879 */ 2880 public static String findAddress(String addr, boolean caseInsensitive) { 2881 return WebViewCore.nativeFindAddress(addr, caseInsensitive); 2882 } 2883 2884 /* 2885 * Clear the highlighting surrounding text matches created by findAll. 2886 */ 2887 public void clearMatches() { 2888 if (mNativeClass == 0) 2889 return; 2890 nativeSetFindIsEmpty(); 2891 invalidate(); 2892 } 2893 2894 /** 2895 * Called when the find ActionMode ends. 2896 */ 2897 void notifyFindDialogDismissed() { 2898 mFindCallback = null; 2899 if (mWebViewCore == null) { 2900 return; 2901 } 2902 clearMatches(); 2903 setFindIsUp(false); 2904 // Now that the dialog has been removed, ensure that we scroll to a 2905 // location that is not beyond the end of the page. 2906 pinScrollTo(mScrollX, mScrollY, false, 0); 2907 invalidate(); 2908 } 2909 2910 /** 2911 * Query the document to see if it contains any image references. The 2912 * message object will be dispatched with arg1 being set to 1 if images 2913 * were found and 0 if the document does not reference any images. 2914 * @param response The message that will be dispatched with the result. 2915 */ 2916 public void documentHasImages(Message response) { 2917 if (response == null) { 2918 return; 2919 } 2920 mWebViewCore.sendMessage(EventHub.DOC_HAS_IMAGES, response); 2921 } 2922 2923 /** 2924 * Request the scroller to abort any ongoing animation 2925 * 2926 * @hide 2927 */ 2928 public void stopScroll() { 2929 mScroller.forceFinished(true); 2930 mLastVelocity = 0; 2931 } 2932 2933 @Override 2934 public void computeScroll() { 2935 if (mScroller.computeScrollOffset()) { 2936 int oldX = mScrollX; 2937 int oldY = mScrollY; 2938 mScrollX = mScroller.getCurrX(); 2939 mScrollY = mScroller.getCurrY(); 2940 postInvalidate(); // So we draw again 2941 if (oldX != mScrollX || oldY != mScrollY) { 2942 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 2943 } else if (mScroller.getStartX() != mScrollX 2944 || mScroller.getStartY() != mScrollY) { 2945 abortAnimation(); 2946 mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY); 2947 WebViewCore.resumePriority(); 2948 WebViewCore.resumeUpdatePicture(mWebViewCore); 2949 } 2950 } else { 2951 super.computeScroll(); 2952 } 2953 } 2954 2955 private static int computeDuration(int dx, int dy) { 2956 int distance = Math.max(Math.abs(dx), Math.abs(dy)); 2957 int duration = distance * 1000 / STD_SPEED; 2958 return Math.min(duration, MAX_DURATION); 2959 } 2960 2961 // helper to pin the scrollBy parameters (already in view coordinates) 2962 // returns true if the scroll was changed 2963 private boolean pinScrollBy(int dx, int dy, boolean animate, int animationDuration) { 2964 return pinScrollTo(mScrollX + dx, mScrollY + dy, animate, animationDuration); 2965 } 2966 // helper to pin the scrollTo parameters (already in view coordinates) 2967 // returns true if the scroll was changed 2968 private boolean pinScrollTo(int x, int y, boolean animate, int animationDuration) { 2969 x = pinLocX(x); 2970 y = pinLocY(y); 2971 int dx = x - mScrollX; 2972 int dy = y - mScrollY; 2973 2974 if ((dx | dy) == 0) { 2975 return false; 2976 } 2977 abortAnimation(); 2978 if (animate) { 2979 // Log.d(LOGTAG, "startScroll: " + dx + " " + dy); 2980 mScroller.startScroll(mScrollX, mScrollY, dx, dy, 2981 animationDuration > 0 ? animationDuration : computeDuration(dx, dy)); 2982 awakenScrollBars(mScroller.getDuration()); 2983 invalidate(); 2984 } else { 2985 scrollTo(x, y); 2986 } 2987 return true; 2988 } 2989 2990 // Scale from content to view coordinates, and pin. 2991 // Also called by jni webview.cpp 2992 private boolean setContentScrollBy(int cx, int cy, boolean animate) { 2993 if (mDrawHistory) { 2994 // disallow WebView to change the scroll position as History Picture 2995 // is used in the view system. 2996 // TODO: as we switchOutDrawHistory when trackball or navigation 2997 // keys are hit, this should be safe. Right? 2998 return false; 2999 } 3000 cx = contentToViewDimension(cx); 3001 cy = contentToViewDimension(cy); 3002 if (mHeightCanMeasure) { 3003 // move our visible rect according to scroll request 3004 if (cy != 0) { 3005 Rect tempRect = new Rect(); 3006 calcOurVisibleRect(tempRect); 3007 tempRect.offset(cx, cy); 3008 requestRectangleOnScreen(tempRect); 3009 } 3010 // FIXME: We scroll horizontally no matter what because currently 3011 // ScrollView and ListView will not scroll horizontally. 3012 // FIXME: Why do we only scroll horizontally if there is no 3013 // vertical scroll? 3014// Log.d(LOGTAG, "setContentScrollBy cy=" + cy); 3015 return cy == 0 && cx != 0 && pinScrollBy(cx, 0, animate, 0); 3016 } else { 3017 return pinScrollBy(cx, cy, animate, 0); 3018 } 3019 } 3020 3021 /** 3022 * Called by CallbackProxy when the page starts loading. 3023 * @param url The URL of the page which has started loading. 3024 */ 3025 /* package */ void onPageStarted(String url) { 3026 // every time we start a new page, we want to reset the 3027 // WebView certificate: if the new site is secure, we 3028 // will reload it and get a new certificate set; 3029 // if the new site is not secure, the certificate must be 3030 // null, and that will be the case 3031 setCertificate(null); 3032 3033 // reset the flag since we set to true in if need after 3034 // loading is see onPageFinished(Url) 3035 mAccessibilityScriptInjected = false; 3036 } 3037 3038 /** 3039 * Called by CallbackProxy when the page finishes loading. 3040 * @param url The URL of the page which has finished loading. 3041 */ 3042 /* package */ void onPageFinished(String url) { 3043 if (mPageThatNeedsToSlideTitleBarOffScreen != null) { 3044 // If the user is now on a different page, or has scrolled the page 3045 // past the point where the title bar is offscreen, ignore the 3046 // scroll request. 3047 if (mPageThatNeedsToSlideTitleBarOffScreen.equals(url) 3048 && mScrollX == 0 && mScrollY == 0) { 3049 pinScrollTo(0, mYDistanceToSlideTitleOffScreen, true, 3050 SLIDE_TITLE_DURATION); 3051 } 3052 mPageThatNeedsToSlideTitleBarOffScreen = null; 3053 } 3054 3055 injectAccessibilityForUrl(url); 3056 } 3057 3058 /** 3059 * This method injects accessibility in the loaded document if accessibility 3060 * is enabled. If JavaScript is enabled we try to inject a URL specific script. 3061 * If no URL specific script is found or JavaScript is disabled we fallback to 3062 * the default {@link AccessibilityInjector} implementation. 3063 * </p> 3064 * If the URL has the "axs" paramter set to 1 it has already done the 3065 * script injection so we do nothing. If the parameter is set to 0 3066 * the URL opts out accessibility script injection so we fall back to 3067 * the default {@link AccessibilityInjector}. 3068 * </p> 3069 * Note: If the user has not opted-in the accessibility script injection no scripts 3070 * are injected rather the default {@link AccessibilityInjector} implementation 3071 * is used. 3072 * 3073 * @param url The URL loaded by this {@link WebView}. 3074 */ 3075 private void injectAccessibilityForUrl(String url) { 3076 AccessibilityManager accessibilityManager = AccessibilityManager.getInstance(mContext); 3077 3078 if (!accessibilityManager.isEnabled()) { 3079 // it is possible that accessibility was turned off between reloads 3080 ensureAccessibilityScriptInjectorInstance(false); 3081 return; 3082 } 3083 3084 if (!getSettings().getJavaScriptEnabled()) { 3085 // no JS so we fallback to the basic buil-in support 3086 ensureAccessibilityScriptInjectorInstance(true); 3087 return; 3088 } 3089 3090 // check the URL "axs" parameter to choose appropriate action 3091 int axsParameterValue = getAxsUrlParameterValue(url); 3092 if (axsParameterValue == ACCESSIBILITY_SCRIPT_INJECTION_UNDEFINED) { 3093 boolean onDeviceScriptInjectionEnabled = (Settings.Secure.getInt(mContext 3094 .getContentResolver(), Settings.Secure.ACCESSIBILITY_SCRIPT_INJECTION, 0) == 1); 3095 if (onDeviceScriptInjectionEnabled) { 3096 ensureAccessibilityScriptInjectorInstance(false); 3097 // neither script injected nor script injection opted out => we inject 3098 loadUrl(ACCESSIBILITY_SCRIPT_CHOOSER_JAVASCRIPT); 3099 // TODO: Set this flag after successfull script injection. Maybe upon injection 3100 // the chooser should update the meta tag and we check it to declare success 3101 mAccessibilityScriptInjected = true; 3102 } else { 3103 // injection disabled so we fallback to the basic built-in support 3104 ensureAccessibilityScriptInjectorInstance(true); 3105 } 3106 } else if (axsParameterValue == ACCESSIBILITY_SCRIPT_INJECTION_OPTED_OUT) { 3107 // injection opted out so we fallback to the basic buil-in support 3108 ensureAccessibilityScriptInjectorInstance(true); 3109 } else if (axsParameterValue == ACCESSIBILITY_SCRIPT_INJECTION_PROVIDED) { 3110 ensureAccessibilityScriptInjectorInstance(false); 3111 // the URL provides accessibility but we still need to add our generic script 3112 loadUrl(ACCESSIBILITY_SCRIPT_CHOOSER_JAVASCRIPT); 3113 } else { 3114 Log.e(LOGTAG, "Unknown URL value for the \"axs\" URL parameter: " + axsParameterValue); 3115 } 3116 } 3117 3118 /** 3119 * Ensures the instance of the {@link AccessibilityInjector} to be present ot not. 3120 * 3121 * @param present True to ensure an insance, false to ensure no instance. 3122 */ 3123 private void ensureAccessibilityScriptInjectorInstance(boolean present) { 3124 if (present && mAccessibilityInjector == null) { 3125 mAccessibilityInjector = new AccessibilityInjector(this); 3126 } else { 3127 mAccessibilityInjector = null; 3128 } 3129 } 3130 3131 /** 3132 * Gets the "axs" URL parameter value. 3133 * 3134 * @param url A url to fetch the paramter from. 3135 * @return The parameter value if such, -1 otherwise. 3136 */ 3137 private int getAxsUrlParameterValue(String url) { 3138 if (mMatchAxsUrlParameterPattern == null) { 3139 mMatchAxsUrlParameterPattern = Pattern.compile(PATTERN_MATCH_AXS_URL_PARAMETER); 3140 } 3141 Matcher matcher = mMatchAxsUrlParameterPattern.matcher(url); 3142 if (matcher.find()) { 3143 String keyValuePair = url.substring(matcher.start(), matcher.end()); 3144 return Integer.parseInt(keyValuePair.split("=")[1]); 3145 } 3146 return -1; 3147 } 3148 3149 /** 3150 * The URL of a page that sent a message to scroll the title bar off screen. 3151 * 3152 * Many mobile sites tell the page to scroll to (0,1) in order to scroll the 3153 * title bar off the screen. Sometimes, the scroll position is set before 3154 * the page finishes loading. Rather than scrolling while the page is still 3155 * loading, keep track of the URL and new scroll position so we can perform 3156 * the scroll once the page finishes loading. 3157 */ 3158 private String mPageThatNeedsToSlideTitleBarOffScreen; 3159 3160 /** 3161 * The destination Y scroll position to be used when the page finishes 3162 * loading. See mPageThatNeedsToSlideTitleBarOffScreen. 3163 */ 3164 private int mYDistanceToSlideTitleOffScreen; 3165 3166 // scale from content to view coordinates, and pin 3167 // return true if pin caused the final x/y different than the request cx/cy, 3168 // and a future scroll may reach the request cx/cy after our size has 3169 // changed 3170 // return false if the view scroll to the exact position as it is requested, 3171 // where negative numbers are taken to mean 0 3172 private boolean setContentScrollTo(int cx, int cy) { 3173 if (mDrawHistory) { 3174 // disallow WebView to change the scroll position as History Picture 3175 // is used in the view system. 3176 // One known case where this is called is that WebCore tries to 3177 // restore the scroll position. As history Picture already uses the 3178 // saved scroll position, it is ok to skip this. 3179 return false; 3180 } 3181 int vx; 3182 int vy; 3183 if ((cx | cy) == 0) { 3184 // If the page is being scrolled to (0,0), do not add in the title 3185 // bar's height, and simply scroll to (0,0). (The only other work 3186 // in contentToView_ is to multiply, so this would not change 0.) 3187 vx = 0; 3188 vy = 0; 3189 } else { 3190 vx = contentToViewX(cx); 3191 vy = contentToViewY(cy); 3192 } 3193// Log.d(LOGTAG, "content scrollTo [" + cx + " " + cy + "] view=[" + 3194// vx + " " + vy + "]"); 3195 // Some mobile sites attempt to scroll the title bar off the page by 3196 // scrolling to (0,1). If we are at the top left corner of the 3197 // page, assume this is an attempt to scroll off the title bar, and 3198 // animate the title bar off screen slowly enough that the user can see 3199 // it. 3200 if (cx == 0 && cy == 1 && mScrollX == 0 && mScrollY == 0 3201 && mTitleBar != null) { 3202 // FIXME: 100 should be defined somewhere as our max progress. 3203 if (getProgress() < 100) { 3204 // Wait to scroll the title bar off screen until the page has 3205 // finished loading. Keep track of the URL and the destination 3206 // Y position 3207 mPageThatNeedsToSlideTitleBarOffScreen = getUrl(); 3208 mYDistanceToSlideTitleOffScreen = vy; 3209 } else { 3210 pinScrollTo(vx, vy, true, SLIDE_TITLE_DURATION); 3211 } 3212 // Since we are animating, we have not yet reached the desired 3213 // scroll position. Do not return true to request another attempt 3214 return false; 3215 } 3216 pinScrollTo(vx, vy, false, 0); 3217 // If the request was to scroll to a negative coordinate, treat it as if 3218 // it was a request to scroll to 0 3219 if ((mScrollX != vx && cx >= 0) || (mScrollY != vy && cy >= 0)) { 3220 return true; 3221 } else { 3222 return false; 3223 } 3224 } 3225 3226 // scale from content to view coordinates, and pin 3227 private void spawnContentScrollTo(int cx, int cy) { 3228 if (mDrawHistory) { 3229 // disallow WebView to change the scroll position as History Picture 3230 // is used in the view system. 3231 return; 3232 } 3233 int vx = contentToViewX(cx); 3234 int vy = contentToViewY(cy); 3235 pinScrollTo(vx, vy, true, 0); 3236 } 3237 3238 /** 3239 * These are from webkit, and are in content coordinate system (unzoomed) 3240 */ 3241 private void contentSizeChanged(boolean updateLayout) { 3242 // suppress 0,0 since we usually see real dimensions soon after 3243 // this avoids drawing the prev content in a funny place. If we find a 3244 // way to consolidate these notifications, this check may become 3245 // obsolete 3246 if ((mContentWidth | mContentHeight) == 0) { 3247 return; 3248 } 3249 3250 if (mHeightCanMeasure) { 3251 if (getMeasuredHeight() != contentToViewDimension(mContentHeight) 3252 || updateLayout) { 3253 requestLayout(); 3254 } 3255 } else if (mWidthCanMeasure) { 3256 if (getMeasuredWidth() != contentToViewDimension(mContentWidth) 3257 || updateLayout) { 3258 requestLayout(); 3259 } 3260 } else { 3261 // If we don't request a layout, try to send our view size to the 3262 // native side to ensure that WebCore has the correct dimensions. 3263 sendViewSizeZoom(false); 3264 } 3265 } 3266 3267 /** 3268 * Set the WebViewClient that will receive various notifications and 3269 * requests. This will replace the current handler. 3270 * @param client An implementation of WebViewClient. 3271 */ 3272 public void setWebViewClient(WebViewClient client) { 3273 mCallbackProxy.setWebViewClient(client); 3274 } 3275 3276 /** 3277 * Gets the WebViewClient 3278 * @return the current WebViewClient instance. 3279 * 3280 *@hide pending API council approval. 3281 */ 3282 public WebViewClient getWebViewClient() { 3283 return mCallbackProxy.getWebViewClient(); 3284 } 3285 3286 /** 3287 * Register the interface to be used when content can not be handled by 3288 * the rendering engine, and should be downloaded instead. This will replace 3289 * the current handler. 3290 * @param listener An implementation of DownloadListener. 3291 */ 3292 public void setDownloadListener(DownloadListener listener) { 3293 mCallbackProxy.setDownloadListener(listener); 3294 } 3295 3296 /** 3297 * Set the chrome handler. This is an implementation of WebChromeClient for 3298 * use in handling Javascript dialogs, favicons, titles, and the progress. 3299 * This will replace the current handler. 3300 * @param client An implementation of WebChromeClient. 3301 */ 3302 public void setWebChromeClient(WebChromeClient client) { 3303 mCallbackProxy.setWebChromeClient(client); 3304 } 3305 3306 /** 3307 * Gets the chrome handler. 3308 * @return the current WebChromeClient instance. 3309 * 3310 * @hide API council approval. 3311 */ 3312 public WebChromeClient getWebChromeClient() { 3313 return mCallbackProxy.getWebChromeClient(); 3314 } 3315 3316 /** 3317 * Set the back/forward list client. This is an implementation of 3318 * WebBackForwardListClient for handling new items and changes in the 3319 * history index. 3320 * @param client An implementation of WebBackForwardListClient. 3321 * {@hide} 3322 */ 3323 public void setWebBackForwardListClient(WebBackForwardListClient client) { 3324 mCallbackProxy.setWebBackForwardListClient(client); 3325 } 3326 3327 /** 3328 * Gets the WebBackForwardListClient. 3329 * {@hide} 3330 */ 3331 public WebBackForwardListClient getWebBackForwardListClient() { 3332 return mCallbackProxy.getWebBackForwardListClient(); 3333 } 3334 3335 /** 3336 * Set the Picture listener. This is an interface used to receive 3337 * notifications of a new Picture. 3338 * @param listener An implementation of WebView.PictureListener. 3339 */ 3340 public void setPictureListener(PictureListener listener) { 3341 mPictureListener = listener; 3342 } 3343 3344 /** 3345 * {@hide} 3346 */ 3347 /* FIXME: Debug only! Remove for SDK! */ 3348 public void externalRepresentation(Message callback) { 3349 mWebViewCore.sendMessage(EventHub.REQUEST_EXT_REPRESENTATION, callback); 3350 } 3351 3352 /** 3353 * {@hide} 3354 */ 3355 /* FIXME: Debug only! Remove for SDK! */ 3356 public void documentAsText(Message callback) { 3357 mWebViewCore.sendMessage(EventHub.REQUEST_DOC_AS_TEXT, callback); 3358 } 3359 3360 /** 3361 * Use this function to bind an object to Javascript so that the 3362 * methods can be accessed from Javascript. 3363 * <p><strong>IMPORTANT:</strong> 3364 * <ul> 3365 * <li> Using addJavascriptInterface() allows JavaScript to control your 3366 * application. This can be a very useful feature or a dangerous security 3367 * issue. When the HTML in the WebView is untrustworthy (for example, part 3368 * or all of the HTML is provided by some person or process), then an 3369 * attacker could inject HTML that will execute your code and possibly any 3370 * code of the attacker's choosing.<br> 3371 * Do not use addJavascriptInterface() unless all of the HTML in this 3372 * WebView was written by you.</li> 3373 * <li> The Java object that is bound runs in another thread and not in 3374 * the thread that it was constructed in.</li> 3375 * </ul></p> 3376 * @param obj The class instance to bind to Javascript 3377 * @param interfaceName The name to used to expose the class in Javascript 3378 */ 3379 public void addJavascriptInterface(Object obj, String interfaceName) { 3380 WebViewCore.JSInterfaceData arg = new WebViewCore.JSInterfaceData(); 3381 arg.mObject = obj; 3382 arg.mInterfaceName = interfaceName; 3383 mWebViewCore.sendMessage(EventHub.ADD_JS_INTERFACE, arg); 3384 } 3385 3386 /** 3387 * Return the WebSettings object used to control the settings for this 3388 * WebView. 3389 * @return A WebSettings object that can be used to control this WebView's 3390 * settings. 3391 */ 3392 public WebSettings getSettings() { 3393 return (mWebViewCore != null) ? mWebViewCore.getSettings() : null; 3394 } 3395 3396 /** 3397 * Return the list of currently loaded plugins. 3398 * @return The list of currently loaded plugins. 3399 * 3400 * @deprecated This was used for Gears, which has been deprecated. 3401 */ 3402 @Deprecated 3403 public static synchronized PluginList getPluginList() { 3404 return new PluginList(); 3405 } 3406 3407 /** 3408 * @deprecated This was used for Gears, which has been deprecated. 3409 */ 3410 @Deprecated 3411 public void refreshPlugins(boolean reloadOpenPages) { } 3412 3413 //------------------------------------------------------------------------- 3414 // Override View methods 3415 //------------------------------------------------------------------------- 3416 3417 @Override 3418 protected void finalize() throws Throwable { 3419 try { 3420 destroy(); 3421 } finally { 3422 super.finalize(); 3423 } 3424 } 3425 3426 @Override 3427 protected boolean drawChild(Canvas canvas, View child, long drawingTime) { 3428 if (child == mTitleBar) { 3429 // When drawing the title bar, move it horizontally to always show 3430 // at the top of the WebView. 3431 mTitleBar.offsetLeftAndRight(mScrollX - mTitleBar.getLeft()); 3432 } 3433 return super.drawChild(canvas, child, drawingTime); 3434 } 3435 3436 private void drawContent(Canvas canvas) { 3437 // Update the buttons in the picture, so when we draw the picture 3438 // to the screen, they are in the correct state. 3439 // Tell the native side if user is a) touching the screen, 3440 // b) pressing the trackball down, or c) pressing the enter key 3441 // If the cursor is on a button, we need to draw it in the pressed 3442 // state. 3443 // If mNativeClass is 0, we should not reach here, so we do not 3444 // need to check it again. 3445 nativeRecordButtons(hasFocus() && hasWindowFocus(), 3446 mTouchMode == TOUCH_SHORTPRESS_START_MODE 3447 || mTrackballDown || mGotCenterDown, false); 3448 drawCoreAndCursorRing(canvas, mBackgroundColor, mDrawCursorRing); 3449 } 3450 3451 @Override 3452 protected void onDraw(Canvas canvas) { 3453 // if mNativeClass is 0, the WebView has been destroyed. Do nothing. 3454 if (mNativeClass == 0) { 3455 return; 3456 } 3457 3458 // if both mContentWidth and mContentHeight are 0, it means there is no 3459 // valid Picture passed to WebView yet. This can happen when WebView 3460 // just starts. Draw the background and return. 3461 if ((mContentWidth | mContentHeight) == 0 && mHistoryPicture == null) { 3462 canvas.drawColor(mBackgroundColor); 3463 return; 3464 } 3465 3466 int saveCount = canvas.save(); 3467 if (mTitleBar != null) { 3468 canvas.translate(0, (int) mTitleBar.getHeight()); 3469 } 3470 drawContent(canvas); 3471 canvas.restoreToCount(saveCount); 3472 3473 // Now draw the shadow. 3474 int titleH = getVisibleTitleHeight(); 3475 if (mTitleBar != null && titleH == 0) { 3476 int height = (int) (5f * getContext().getResources() 3477 .getDisplayMetrics().density); 3478 mTitleShadow.setBounds(mScrollX, mScrollY, mScrollX + getWidth(), 3479 mScrollY + height); 3480 mTitleShadow.draw(canvas); 3481 } 3482 if (AUTO_REDRAW_HACK && mAutoRedraw) { 3483 invalidate(); 3484 } 3485 if (inEditingMode()) { 3486 mWebTextView.onDrawSubstitute(); 3487 } 3488 mWebViewCore.signalRepaintDone(); 3489 3490 // paint the highlight in the end 3491 if (!mTouchHighlightRegion.isEmpty()) { 3492 if (mTouchHightlightPaint == null) { 3493 mTouchHightlightPaint = new Paint(); 3494 mTouchHightlightPaint.setColor(mHightlightColor); 3495 mTouchHightlightPaint.setAntiAlias(true); 3496 mTouchHightlightPaint.setPathEffect(new CornerPathEffect( 3497 TOUCH_HIGHLIGHT_ARC)); 3498 } 3499 canvas.drawPath(mTouchHighlightRegion.getBoundaryPath(), 3500 mTouchHightlightPaint); 3501 } 3502 if (DEBUG_TOUCH_HIGHLIGHT) { 3503 if (getSettings().getNavDump()) { 3504 if ((mTouchHighlightX | mTouchHighlightY) != 0) { 3505 if (mTouchCrossHairColor == null) { 3506 mTouchCrossHairColor = new Paint(); 3507 mTouchCrossHairColor.setColor(Color.RED); 3508 } 3509 canvas.drawLine(mTouchHighlightX - mNavSlop, 3510 mTouchHighlightY - mNavSlop, mTouchHighlightX 3511 + mNavSlop + 1, mTouchHighlightY + mNavSlop 3512 + 1, mTouchCrossHairColor); 3513 canvas.drawLine(mTouchHighlightX + mNavSlop + 1, 3514 mTouchHighlightY - mNavSlop, mTouchHighlightX 3515 - mNavSlop, 3516 mTouchHighlightY + mNavSlop + 1, 3517 mTouchCrossHairColor); 3518 } 3519 } 3520 } 3521 } 3522 3523 private void removeTouchHighlight(boolean removePendingMessage) { 3524 if (removePendingMessage) { 3525 mWebViewCore.removeMessages(EventHub.GET_TOUCH_HIGHLIGHT_RECTS); 3526 } 3527 mWebViewCore.sendMessage(EventHub.REMOVE_TOUCH_HIGHLIGHT_RECTS); 3528 } 3529 3530 @Override 3531 public void setLayoutParams(ViewGroup.LayoutParams params) { 3532 if (params.height == LayoutParams.WRAP_CONTENT) { 3533 mWrapContent = true; 3534 } 3535 super.setLayoutParams(params); 3536 } 3537 3538 @Override 3539 public boolean performLongClick() { 3540 // performLongClick() is the result of a delayed message. If we switch 3541 // to windows overview, the WebView will be temporarily removed from the 3542 // view system. In that case, do nothing. 3543 if (getParent() == null) return false; 3544 3545 // A multi-finger gesture can look like a long press; make sure we don't take 3546 // long press actions if we're scaling. 3547 final ScaleGestureDetector detector = mZoomManager.getMultiTouchGestureDetector(); 3548 if (detector != null && detector.isInProgress()) { 3549 return false; 3550 } 3551 3552 if (mNativeClass != 0 && nativeCursorIsTextInput()) { 3553 // Send the click so that the textfield is in focus 3554 centerKeyPressOnTextField(); 3555 rebuildWebTextView(); 3556 } else { 3557 clearTextEntry(); 3558 } 3559 if (inEditingMode()) { 3560 return mWebTextView.performLongClick(); 3561 } 3562 if (mSelectingText) return false; // long click does nothing on selection 3563 /* if long click brings up a context menu, the super function 3564 * returns true and we're done. Otherwise, nothing happened when 3565 * the user clicked. */ 3566 if (super.performLongClick()) { 3567 return true; 3568 } 3569 /* In the case where the application hasn't already handled the long 3570 * click action, look for a word under the click. If one is found, 3571 * animate the text selection into view. 3572 * FIXME: no animation code yet */ 3573 int x = viewToContentX((int) mLastTouchX + mScrollX); 3574 int y = viewToContentY((int) mLastTouchY + mScrollY); 3575 setUpSelect(); 3576 if (mNativeClass != 0 && nativeWordSelection(x, y)) { 3577 nativeSetExtendSelection(); 3578 mDrawSelectionPointer = false; 3579 return true; 3580 } 3581 selectionDone(); 3582 return false; 3583 } 3584 3585 /** 3586 * Keep track of the Callback so we can end its ActionMode or remove its 3587 * titlebar. 3588 */ 3589 private SelectActionModeCallback mSelectCallback; 3590 3591 /** 3592 * Check to see if the focused textfield/textarea is still on screen. If it 3593 * is, update the the dimensions and location of WebTextView. Otherwise, 3594 * remove the WebTextView. Should be called when the zoom level changes. 3595 * @param allowIntersect Whether to consider the textfield/textarea on 3596 * screen if it only intersects the screen (as opposed to being 3597 * completely on screen). 3598 * @return boolean True if the textfield/textarea is still on screen and the 3599 * dimensions/location of WebTextView have been updated. 3600 */ 3601 private boolean didUpdateWebTextViewDimensions(boolean allowIntersect) { 3602 Rect contentBounds = nativeFocusCandidateNodeBounds(); 3603 Rect vBox = contentToViewRect(contentBounds); 3604 Rect visibleRect = new Rect(); 3605 calcOurVisibleRect(visibleRect); 3606 // If the textfield is on screen, place the WebTextView in 3607 // its new place, accounting for our new scroll/zoom values, 3608 // and adjust its textsize. 3609 if (allowIntersect ? Rect.intersects(visibleRect, vBox) 3610 : visibleRect.contains(vBox)) { 3611 mWebTextView.setRect(vBox.left, vBox.top, vBox.width(), 3612 vBox.height()); 3613 mWebTextView.updateTextSize(); 3614 updateWebTextViewPadding(); 3615 return true; 3616 } else { 3617 // The textfield is now off screen. The user probably 3618 // was not zooming to see the textfield better. Remove 3619 // the WebTextView. If the user types a key, and the 3620 // textfield is still in focus, we will reconstruct 3621 // the WebTextView and scroll it back on screen. 3622 mWebTextView.remove(); 3623 return false; 3624 } 3625 } 3626 3627 void setBaseLayer(int layer, Rect invalRect) { 3628 if (mNativeClass == 0) 3629 return; 3630 if (invalRect == null) { 3631 Rect rect = new Rect(0, 0, mContentWidth, mContentHeight); 3632 nativeSetBaseLayer(layer, rect); 3633 } else { 3634 nativeSetBaseLayer(layer, invalRect); 3635 } 3636 } 3637 3638 private void onZoomAnimationStart() { 3639 // If it is in password mode, turn it off so it does not draw misplaced. 3640 if (inEditingMode() && nativeFocusCandidateIsPassword()) { 3641 mWebTextView.setInPassword(false); 3642 } 3643 } 3644 3645 private void onZoomAnimationEnd() { 3646 // adjust the edit text view if needed 3647 if (inEditingMode() && didUpdateWebTextViewDimensions(false) 3648 && nativeFocusCandidateIsPassword()) { 3649 // If it is a password field, start drawing the WebTextView once 3650 // again. 3651 mWebTextView.setInPassword(true); 3652 } 3653 } 3654 3655 void onFixedLengthZoomAnimationStart() { 3656 WebViewCore.pauseUpdatePicture(getWebViewCore()); 3657 onZoomAnimationStart(); 3658 } 3659 3660 void onFixedLengthZoomAnimationEnd() { 3661 WebViewCore.resumeUpdatePicture(mWebViewCore); 3662 onZoomAnimationEnd(); 3663 } 3664 3665 private static final int ZOOM_BITS = Paint.FILTER_BITMAP_FLAG | 3666 Paint.DITHER_FLAG | 3667 Paint.SUBPIXEL_TEXT_FLAG; 3668 private static final int SCROLL_BITS = Paint.FILTER_BITMAP_FLAG | 3669 Paint.DITHER_FLAG; 3670 3671 private final DrawFilter mZoomFilter = 3672 new PaintFlagsDrawFilter(ZOOM_BITS, Paint.LINEAR_TEXT_FLAG); 3673 // If we need to trade better quality for speed, set mScrollFilter to null 3674 private final DrawFilter mScrollFilter = 3675 new PaintFlagsDrawFilter(SCROLL_BITS, 0); 3676 3677 private void drawCoreAndCursorRing(Canvas canvas, int color, 3678 boolean drawCursorRing) { 3679 if (mDrawHistory) { 3680 canvas.scale(mZoomManager.getScale(), mZoomManager.getScale()); 3681 canvas.drawPicture(mHistoryPicture); 3682 return; 3683 } 3684 if (mNativeClass == 0) return; 3685 3686 boolean animateZoom = mZoomManager.isFixedLengthAnimationInProgress(); 3687 boolean animateScroll = ((!mScroller.isFinished() 3688 || mVelocityTracker != null) 3689 && (mTouchMode != TOUCH_DRAG_MODE || 3690 mHeldMotionless != MOTIONLESS_TRUE)) 3691 || mDeferTouchMode == TOUCH_DRAG_MODE; 3692 if (mTouchMode == TOUCH_DRAG_MODE) { 3693 if (mHeldMotionless == MOTIONLESS_PENDING) { 3694 mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS); 3695 mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS); 3696 mHeldMotionless = MOTIONLESS_FALSE; 3697 } 3698 if (mHeldMotionless == MOTIONLESS_FALSE) { 3699 mPrivateHandler.sendMessageDelayed(mPrivateHandler 3700 .obtainMessage(DRAG_HELD_MOTIONLESS), MOTIONLESS_TIME); 3701 mHeldMotionless = MOTIONLESS_PENDING; 3702 } 3703 } 3704 if (animateZoom) { 3705 mZoomManager.animateZoom(canvas); 3706 } else { 3707 canvas.scale(mZoomManager.getScale(), mZoomManager.getScale()); 3708 } 3709 3710 boolean UIAnimationsRunning = false; 3711 // Currently for each draw we compute the animation values; 3712 // We may in the future decide to do that independently. 3713 if (mNativeClass != 0 && nativeEvaluateLayersAnimations()) { 3714 UIAnimationsRunning = true; 3715 // If we have unfinished (or unstarted) animations, 3716 // we ask for a repaint. 3717 invalidate(); 3718 } 3719 3720 // decide which adornments to draw 3721 int extras = DRAW_EXTRAS_NONE; 3722 if (DebugFlags.WEB_VIEW) { 3723 Log.v(LOGTAG, "mFindIsUp=" + mFindIsUp 3724 + " mSelectingText=" + mSelectingText 3725 + " nativePageShouldHandleShiftAndArrows()=" 3726 + nativePageShouldHandleShiftAndArrows() 3727 + " animateZoom=" + animateZoom); 3728 } 3729 if (mFindIsUp) { 3730 extras = DRAW_EXTRAS_FIND; 3731 } else if (mSelectingText) { 3732 extras = DRAW_EXTRAS_SELECTION; 3733 nativeSetSelectionPointer(mDrawSelectionPointer, 3734 mZoomManager.getInvScale(), 3735 mSelectX, mSelectY - getTitleHeight()); 3736 } else if (drawCursorRing) { 3737 extras = DRAW_EXTRAS_CURSOR_RING; 3738 } 3739 3740 if (canvas.isHardwareAccelerated()) { 3741 try { 3742 if (canvas.acquireContext()) { 3743 Rect rect = new Rect(mGLRectViewport.left, 3744 mGLRectViewport.top, 3745 mGLRectViewport.right, 3746 mGLRectViewport.bottom 3747 - getVisibleTitleHeight()); 3748 if (nativeDrawGL(rect, getScale(), extras)) { 3749 invalidate(); 3750 } 3751 } 3752 } finally { 3753 canvas.releaseContext(); 3754 } 3755 } else { 3756 DrawFilter df = null; 3757 if (mZoomManager.isZoomAnimating() || UIAnimationsRunning) { 3758 df = mZoomFilter; 3759 } else if (animateScroll) { 3760 df = mScrollFilter; 3761 } 3762 canvas.setDrawFilter(df); 3763 int content = nativeDraw(canvas, color, extras, true); 3764 canvas.setDrawFilter(null); 3765 if (content != 0) { 3766 mWebViewCore.sendMessage(EventHub.SPLIT_PICTURE_SET, content, 0); 3767 } 3768 } 3769 3770 if (extras == DRAW_EXTRAS_CURSOR_RING) { 3771 if (mTouchMode == TOUCH_SHORTPRESS_START_MODE) { 3772 mTouchMode = TOUCH_SHORTPRESS_MODE; 3773 } 3774 } 3775 if (mFocusSizeChanged) { 3776 mFocusSizeChanged = false; 3777 // If we are zooming, this will get handled above, when the zoom 3778 // finishes. We also do not need to do this unless the WebTextView 3779 // is showing. 3780 if (!animateZoom && inEditingMode()) { 3781 didUpdateWebTextViewDimensions(true); 3782 } 3783 } 3784 } 3785 3786 // draw history 3787 private boolean mDrawHistory = false; 3788 private Picture mHistoryPicture = null; 3789 private int mHistoryWidth = 0; 3790 private int mHistoryHeight = 0; 3791 3792 // Only check the flag, can be called from WebCore thread 3793 boolean drawHistory() { 3794 return mDrawHistory; 3795 } 3796 3797 int getHistoryPictureWidth() { 3798 return (mHistoryPicture != null) ? mHistoryPicture.getWidth() : 0; 3799 } 3800 3801 // Should only be called in UI thread 3802 void switchOutDrawHistory() { 3803 if (null == mWebViewCore) return; // CallbackProxy may trigger this 3804 if (mDrawHistory && (getProgress() == 100 || nativeHasContent())) { 3805 mDrawHistory = false; 3806 mHistoryPicture = null; 3807 invalidate(); 3808 int oldScrollX = mScrollX; 3809 int oldScrollY = mScrollY; 3810 mScrollX = pinLocX(mScrollX); 3811 mScrollY = pinLocY(mScrollY); 3812 if (oldScrollX != mScrollX || oldScrollY != mScrollY) { 3813 mUserScroll = false; 3814 mWebViewCore.sendMessage(EventHub.SYNC_SCROLL, oldScrollX, 3815 oldScrollY); 3816 onScrollChanged(mScrollX, mScrollY, oldScrollX, oldScrollY); 3817 } else { 3818 sendOurVisibleRect(); 3819 } 3820 } 3821 } 3822 3823 WebViewCore.CursorData cursorData() { 3824 WebViewCore.CursorData result = new WebViewCore.CursorData(); 3825 result.mMoveGeneration = nativeMoveGeneration(); 3826 result.mFrame = nativeCursorFramePointer(); 3827 Point position = nativeCursorPosition(); 3828 result.mX = position.x; 3829 result.mY = position.y; 3830 return result; 3831 } 3832 3833 /** 3834 * Delete text from start to end in the focused textfield. If there is no 3835 * focus, or if start == end, silently fail. If start and end are out of 3836 * order, swap them. 3837 * @param start Beginning of selection to delete. 3838 * @param end End of selection to delete. 3839 */ 3840 /* package */ void deleteSelection(int start, int end) { 3841 mTextGeneration++; 3842 WebViewCore.TextSelectionData data 3843 = new WebViewCore.TextSelectionData(start, end); 3844 mWebViewCore.sendMessage(EventHub.DELETE_SELECTION, mTextGeneration, 0, 3845 data); 3846 } 3847 3848 /** 3849 * Set the selection to (start, end) in the focused textfield. If start and 3850 * end are out of order, swap them. 3851 * @param start Beginning of selection. 3852 * @param end End of selection. 3853 */ 3854 /* package */ void setSelection(int start, int end) { 3855 if (mWebViewCore != null) { 3856 mWebViewCore.sendMessage(EventHub.SET_SELECTION, start, end); 3857 } 3858 } 3859 3860 @Override 3861 public InputConnection onCreateInputConnection(EditorInfo outAttrs) { 3862 InputConnection connection = super.onCreateInputConnection(outAttrs); 3863 outAttrs.imeOptions |= EditorInfo.IME_FLAG_NO_FULLSCREEN; 3864 return connection; 3865 } 3866 3867 /** 3868 * Called in response to a message from webkit telling us that the soft 3869 * keyboard should be launched. 3870 */ 3871 private void displaySoftKeyboard(boolean isTextView) { 3872 InputMethodManager imm = (InputMethodManager) 3873 getContext().getSystemService(Context.INPUT_METHOD_SERVICE); 3874 3875 // bring it back to the default level scale so that user can enter text 3876 boolean zoom = mZoomManager.getScale() < mZoomManager.getDefaultScale(); 3877 if (zoom) { 3878 mZoomManager.setZoomCenter(mLastTouchX, mLastTouchY); 3879 mZoomManager.setZoomScale(mZoomManager.getDefaultScale(), false); 3880 } 3881 if (isTextView) { 3882 rebuildWebTextView(); 3883 if (inEditingMode()) { 3884 imm.showSoftInput(mWebTextView, 0); 3885 if (zoom) { 3886 didUpdateWebTextViewDimensions(true); 3887 } 3888 return; 3889 } 3890 } 3891 // Used by plugins and contentEditable. 3892 // Also used if the navigation cache is out of date, and 3893 // does not recognize that a textfield is in focus. In that 3894 // case, use WebView as the targeted view. 3895 // see http://b/issue?id=2457459 3896 imm.showSoftInput(this, 0); 3897 } 3898 3899 // Called by WebKit to instruct the UI to hide the keyboard 3900 private void hideSoftKeyboard() { 3901 InputMethodManager imm = InputMethodManager.peekInstance(); 3902 if (imm != null && (imm.isActive(this) 3903 || (inEditingMode() && imm.isActive(mWebTextView)))) { 3904 imm.hideSoftInputFromWindow(this.getWindowToken(), 0); 3905 } 3906 } 3907 3908 /* 3909 * This method checks the current focus and cursor and potentially rebuilds 3910 * mWebTextView to have the appropriate properties, such as password, 3911 * multiline, and what text it contains. It also removes it if necessary. 3912 */ 3913 /* package */ void rebuildWebTextView() { 3914 // If the WebView does not have focus, do nothing until it gains focus. 3915 if (!hasFocus() && (null == mWebTextView || !mWebTextView.hasFocus())) { 3916 return; 3917 } 3918 boolean alreadyThere = inEditingMode(); 3919 // inEditingMode can only return true if mWebTextView is non-null, 3920 // so we can safely call remove() if (alreadyThere) 3921 if (0 == mNativeClass || !nativeFocusCandidateIsTextInput()) { 3922 if (alreadyThere) { 3923 mWebTextView.remove(); 3924 } 3925 return; 3926 } 3927 // At this point, we know we have found an input field, so go ahead 3928 // and create the WebTextView if necessary. 3929 if (mWebTextView == null) { 3930 mWebTextView = new WebTextView(mContext, WebView.this, mAutoFillData.getQueryId()); 3931 // Initialize our generation number. 3932 mTextGeneration = 0; 3933 } 3934 mWebTextView.updateTextSize(); 3935 Rect visibleRect = new Rect(); 3936 calcOurContentVisibleRect(visibleRect); 3937 // Note that sendOurVisibleRect calls viewToContent, so the coordinates 3938 // should be in content coordinates. 3939 Rect bounds = nativeFocusCandidateNodeBounds(); 3940 Rect vBox = contentToViewRect(bounds); 3941 mWebTextView.setRect(vBox.left, vBox.top, vBox.width(), vBox.height()); 3942 if (!Rect.intersects(bounds, visibleRect)) { 3943 mWebTextView.bringIntoView(); 3944 } 3945 String text = nativeFocusCandidateText(); 3946 int nodePointer = nativeFocusCandidatePointer(); 3947 if (alreadyThere && mWebTextView.isSameTextField(nodePointer)) { 3948 // It is possible that we have the same textfield, but it has moved, 3949 // i.e. In the case of opening/closing the screen. 3950 // In that case, we need to set the dimensions, but not the other 3951 // aspects. 3952 // If the text has been changed by webkit, update it. However, if 3953 // there has been more UI text input, ignore it. We will receive 3954 // another update when that text is recognized. 3955 if (text != null && !text.equals(mWebTextView.getText().toString()) 3956 && nativeTextGeneration() == mTextGeneration) { 3957 mWebTextView.setTextAndKeepSelection(text); 3958 } 3959 } else { 3960 mWebTextView.setGravity(nativeFocusCandidateIsRtlText() ? 3961 Gravity.RIGHT : Gravity.NO_GRAVITY); 3962 // This needs to be called before setType, which may call 3963 // requestFormData, and it needs to have the correct nodePointer. 3964 mWebTextView.setNodePointer(nodePointer); 3965 mWebTextView.setType(nativeFocusCandidateType()); 3966 updateWebTextViewPadding(); 3967 if (null == text) { 3968 if (DebugFlags.WEB_VIEW) { 3969 Log.v(LOGTAG, "rebuildWebTextView null == text"); 3970 } 3971 text = ""; 3972 } 3973 mWebTextView.setTextAndKeepSelection(text); 3974 InputMethodManager imm = InputMethodManager.peekInstance(); 3975 if (imm != null && imm.isActive(mWebTextView)) { 3976 imm.restartInput(mWebTextView); 3977 } 3978 } 3979 if (isFocused()) { 3980 mWebTextView.requestFocus(); 3981 } 3982 } 3983 3984 /** 3985 * Update the padding of mWebTextView based on the native textfield/textarea 3986 */ 3987 void updateWebTextViewPadding() { 3988 Rect paddingRect = nativeFocusCandidatePaddingRect(); 3989 if (paddingRect != null) { 3990 // Use contentToViewDimension since these are the dimensions of 3991 // the padding. 3992 mWebTextView.setPadding( 3993 contentToViewDimension(paddingRect.left), 3994 contentToViewDimension(paddingRect.top), 3995 contentToViewDimension(paddingRect.right), 3996 contentToViewDimension(paddingRect.bottom)); 3997 } 3998 } 3999 4000 /** 4001 * Tell webkit to put the cursor on screen. 4002 */ 4003 /* package */ void revealSelection() { 4004 if (mWebViewCore != null) { 4005 mWebViewCore.sendMessage(EventHub.REVEAL_SELECTION); 4006 } 4007 } 4008 4009 /** 4010 * Called by WebTextView to find saved form data associated with the 4011 * textfield 4012 * @param name Name of the textfield. 4013 * @param nodePointer Pointer to the node of the textfield, so it can be 4014 * compared to the currently focused textfield when the data is 4015 * retrieved. 4016 * @param autoFillable true if WebKit has determined this field is part of 4017 * a form that can be auto filled. 4018 */ 4019 /* package */ void requestFormData(String name, int nodePointer, boolean autoFillable) { 4020 if (mWebViewCore.getSettings().getSaveFormData()) { 4021 Message update = mPrivateHandler.obtainMessage(REQUEST_FORM_DATA); 4022 update.arg1 = nodePointer; 4023 RequestFormData updater = new RequestFormData(name, getUrl(), 4024 update, autoFillable); 4025 Thread t = new Thread(updater); 4026 t.start(); 4027 } 4028 } 4029 4030 /** 4031 * Pass a message to find out the <label> associated with the <input> 4032 * identified by nodePointer 4033 * @param framePointer Pointer to the frame containing the <input> node 4034 * @param nodePointer Pointer to the node for which a <label> is desired. 4035 */ 4036 /* package */ void requestLabel(int framePointer, int nodePointer) { 4037 mWebViewCore.sendMessage(EventHub.REQUEST_LABEL, framePointer, 4038 nodePointer); 4039 } 4040 4041 /* 4042 * This class requests an Adapter for the WebTextView which shows past 4043 * entries stored in the database. It is a Runnable so that it can be done 4044 * in its own thread, without slowing down the UI. 4045 */ 4046 private class RequestFormData implements Runnable { 4047 private String mName; 4048 private String mUrl; 4049 private Message mUpdateMessage; 4050 private boolean mAutoFillable; 4051 4052 public RequestFormData(String name, String url, Message msg, boolean autoFillable) { 4053 mName = name; 4054 mUrl = url; 4055 mUpdateMessage = msg; 4056 mAutoFillable = autoFillable; 4057 } 4058 4059 public void run() { 4060 ArrayList<String> pastEntries = new ArrayList(); 4061 4062 if (mAutoFillable) { 4063 // Note that code inside the adapter click handler in WebTextView depends 4064 // on the AutoFill item being at the top of the drop down list. If you change 4065 // the order, make sure to do it there too! 4066 pastEntries.add(getResources().getText( 4067 com.android.internal.R.string.autofill_this_form).toString() + 4068 " " + 4069 mAutoFillData.getPreviewString()); 4070 } 4071 4072 pastEntries.addAll(mDatabase.getFormData(mUrl, mName)); 4073 4074 if (pastEntries.size() > 0) { 4075 AutoCompleteAdapter adapter = new 4076 AutoCompleteAdapter(mContext, pastEntries); 4077 mUpdateMessage.obj = adapter; 4078 mUpdateMessage.sendToTarget(); 4079 } 4080 } 4081 } 4082 4083 /** 4084 * Dump the display tree to "/sdcard/displayTree.txt" 4085 * 4086 * @hide debug only 4087 */ 4088 public void dumpDisplayTree() { 4089 nativeDumpDisplayTree(getUrl()); 4090 } 4091 4092 /** 4093 * Dump the dom tree to adb shell if "toFile" is False, otherwise dump it to 4094 * "/sdcard/domTree.txt" 4095 * 4096 * @hide debug only 4097 */ 4098 public void dumpDomTree(boolean toFile) { 4099 mWebViewCore.sendMessage(EventHub.DUMP_DOMTREE, toFile ? 1 : 0, 0); 4100 } 4101 4102 /** 4103 * Dump the render tree to adb shell if "toFile" is False, otherwise dump it 4104 * to "/sdcard/renderTree.txt" 4105 * 4106 * @hide debug only 4107 */ 4108 public void dumpRenderTree(boolean toFile) { 4109 mWebViewCore.sendMessage(EventHub.DUMP_RENDERTREE, toFile ? 1 : 0, 0); 4110 } 4111 4112 /** 4113 * Called by DRT on UI thread, need to proxy to WebCore thread. 4114 * 4115 * @hide debug only 4116 */ 4117 public void useMockDeviceOrientation() { 4118 mWebViewCore.sendMessage(EventHub.USE_MOCK_DEVICE_ORIENTATION); 4119 } 4120 4121 /** 4122 * Called by DRT on WebCore thread. 4123 * 4124 * @hide debug only 4125 */ 4126 public void setMockDeviceOrientation(boolean canProvideAlpha, double alpha, 4127 boolean canProvideBeta, double beta, boolean canProvideGamma, double gamma) { 4128 mWebViewCore.setMockDeviceOrientation(canProvideAlpha, alpha, canProvideBeta, beta, 4129 canProvideGamma, gamma); 4130 } 4131 4132 /** 4133 * Dump the V8 counters to standard output. 4134 * Note that you need a build with V8 and WEBCORE_INSTRUMENTATION set to 4135 * true. Otherwise, this will do nothing. 4136 * 4137 * @hide debug only 4138 */ 4139 public void dumpV8Counters() { 4140 mWebViewCore.sendMessage(EventHub.DUMP_V8COUNTERS); 4141 } 4142 4143 // This is used to determine long press with the center key. Does not 4144 // affect long press with the trackball/touch. 4145 private boolean mGotCenterDown = false; 4146 4147 @Override 4148 public boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event) { 4149 // send complex characters to webkit for use by JS and plugins 4150 if (keyCode == KeyEvent.KEYCODE_UNKNOWN && event.getCharacters() != null) { 4151 // pass the key to DOM 4152 mWebViewCore.sendMessage(EventHub.KEY_DOWN, event); 4153 mWebViewCore.sendMessage(EventHub.KEY_UP, event); 4154 // return true as DOM handles the key 4155 return true; 4156 } 4157 return false; 4158 } 4159 4160 @Override 4161 public boolean onKeyDown(int keyCode, KeyEvent event) { 4162 if (DebugFlags.WEB_VIEW) { 4163 Log.v(LOGTAG, "keyDown at " + System.currentTimeMillis() 4164 + ", " + event + ", unicode=" + event.getUnicodeChar()); 4165 } 4166 4167 if (mNativeClass == 0) { 4168 return false; 4169 } 4170 4171 // do this hack up front, so it always works, regardless of touch-mode 4172 if (AUTO_REDRAW_HACK && (keyCode == KeyEvent.KEYCODE_CALL)) { 4173 mAutoRedraw = !mAutoRedraw; 4174 if (mAutoRedraw) { 4175 invalidate(); 4176 } 4177 return true; 4178 } 4179 4180 // Bubble up the key event if 4181 // 1. it is a system key; or 4182 // 2. the host application wants to handle it; 4183 // 3. the accessibility injector is present and wants to handle it; 4184 if (event.isSystem() 4185 || mCallbackProxy.uiOverrideKeyEvent(event) 4186 || (mAccessibilityInjector != null && mAccessibilityInjector.onKeyEvent(event))) { 4187 return false; 4188 } 4189 4190 if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT 4191 || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT) { 4192 if (!pageShouldHandleShiftAndArrows() && !nativeCursorWantsKeyEvents() 4193 && !mSelectingText) { 4194 setUpSelect(); 4195 } 4196 } 4197 4198 if (keyCode == KeyEvent.KEYCODE_PAGE_UP) { 4199 pageUp(false); 4200 return true; 4201 } 4202 4203 if (keyCode == KeyEvent.KEYCODE_PAGE_DOWN) { 4204 pageDown(false); 4205 return true; 4206 } 4207 4208 if (keyCode >= KeyEvent.KEYCODE_DPAD_UP 4209 && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) { 4210 switchOutDrawHistory(); 4211 if (pageShouldHandleShiftAndArrows()) { 4212 letPageHandleNavKey(keyCode, event.getEventTime(), true, event.getMetaState()); 4213 return true; 4214 } 4215 if (mSelectingText) { 4216 int xRate = keyCode == KeyEvent.KEYCODE_DPAD_LEFT 4217 ? -1 : keyCode == KeyEvent.KEYCODE_DPAD_RIGHT ? 1 : 0; 4218 int yRate = keyCode == KeyEvent.KEYCODE_DPAD_UP ? 4219 -1 : keyCode == KeyEvent.KEYCODE_DPAD_DOWN ? 1 : 0; 4220 int multiplier = event.getRepeatCount() + 1; 4221 moveSelection(xRate * multiplier, yRate * multiplier); 4222 return true; 4223 } 4224 if (navHandledKey(keyCode, 1, false, event.getEventTime())) { 4225 playSoundEffect(keyCodeToSoundsEffect(keyCode)); 4226 return true; 4227 } 4228 // Bubble up the key event as WebView doesn't handle it 4229 return false; 4230 } 4231 4232 if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { 4233 switchOutDrawHistory(); 4234 if (event.getRepeatCount() == 0) { 4235 if (mSelectingText) { 4236 return true; // discard press if copy in progress 4237 } 4238 mGotCenterDown = true; 4239 mPrivateHandler.sendMessageDelayed(mPrivateHandler 4240 .obtainMessage(LONG_PRESS_CENTER), LONG_PRESS_TIMEOUT); 4241 // Already checked mNativeClass, so we do not need to check it 4242 // again. 4243 nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true); 4244 return true; 4245 } 4246 // Bubble up the key event as WebView doesn't handle it 4247 return false; 4248 } 4249 4250 if (keyCode != KeyEvent.KEYCODE_SHIFT_LEFT 4251 && keyCode != KeyEvent.KEYCODE_SHIFT_RIGHT) { 4252 // turn off copy select if a shift-key combo is pressed 4253 selectionDone(); 4254 } 4255 4256 if (getSettings().getNavDump()) { 4257 switch (keyCode) { 4258 case KeyEvent.KEYCODE_4: 4259 dumpDisplayTree(); 4260 break; 4261 case KeyEvent.KEYCODE_5: 4262 case KeyEvent.KEYCODE_6: 4263 dumpDomTree(keyCode == KeyEvent.KEYCODE_5); 4264 break; 4265 case KeyEvent.KEYCODE_7: 4266 case KeyEvent.KEYCODE_8: 4267 dumpRenderTree(keyCode == KeyEvent.KEYCODE_7); 4268 break; 4269 case KeyEvent.KEYCODE_9: 4270 nativeInstrumentReport(); 4271 return true; 4272 } 4273 } 4274 4275 if (nativeCursorIsTextInput()) { 4276 // This message will put the node in focus, for the DOM's notion 4277 // of focus, and make the focuscontroller active 4278 mWebViewCore.sendMessage(EventHub.CLICK, nativeCursorFramePointer(), 4279 nativeCursorNodePointer()); 4280 // This will bring up the WebTextView and put it in focus, for 4281 // our view system's notion of focus 4282 rebuildWebTextView(); 4283 // Now we need to pass the event to it 4284 if (inEditingMode()) { 4285 mWebTextView.setDefaultSelection(); 4286 return mWebTextView.dispatchKeyEvent(event); 4287 } 4288 } else if (nativeHasFocusNode()) { 4289 // In this case, the cursor is not on a text input, but the focus 4290 // might be. Check it, and if so, hand over to the WebTextView. 4291 rebuildWebTextView(); 4292 if (inEditingMode()) { 4293 mWebTextView.setDefaultSelection(); 4294 return mWebTextView.dispatchKeyEvent(event); 4295 } 4296 } 4297 4298 // TODO: should we pass all the keys to DOM or check the meta tag 4299 if (nativeCursorWantsKeyEvents() || true) { 4300 // pass the key to DOM 4301 mWebViewCore.sendMessage(EventHub.KEY_DOWN, event); 4302 // return true as DOM handles the key 4303 return true; 4304 } 4305 4306 // Bubble up the key event as WebView doesn't handle it 4307 return false; 4308 } 4309 4310 @Override 4311 public boolean onKeyUp(int keyCode, KeyEvent event) { 4312 if (DebugFlags.WEB_VIEW) { 4313 Log.v(LOGTAG, "keyUp at " + System.currentTimeMillis() 4314 + ", " + event + ", unicode=" + event.getUnicodeChar()); 4315 } 4316 4317 if (mNativeClass == 0) { 4318 return false; 4319 } 4320 4321 // special CALL handling when cursor node's href is "tel:XXX" 4322 if (keyCode == KeyEvent.KEYCODE_CALL && nativeHasCursorNode()) { 4323 String text = nativeCursorText(); 4324 if (!nativeCursorIsTextInput() && text != null 4325 && text.startsWith(SCHEME_TEL)) { 4326 Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(text)); 4327 getContext().startActivity(intent); 4328 return true; 4329 } 4330 } 4331 4332 // Bubble up the key event if 4333 // 1. it is a system key; or 4334 // 2. the host application wants to handle it; 4335 // 3. the accessibility injector is present and wants to handle it; 4336 if (event.isSystem() 4337 || mCallbackProxy.uiOverrideKeyEvent(event) 4338 || (mAccessibilityInjector != null && mAccessibilityInjector.onKeyEvent(event))) { 4339 return false; 4340 } 4341 4342 if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT 4343 || keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT) { 4344 if (!pageShouldHandleShiftAndArrows() && copySelection()) { 4345 selectionDone(); 4346 return true; 4347 } 4348 } 4349 4350 if (keyCode >= KeyEvent.KEYCODE_DPAD_UP 4351 && keyCode <= KeyEvent.KEYCODE_DPAD_RIGHT) { 4352 if (pageShouldHandleShiftAndArrows()) { 4353 letPageHandleNavKey(keyCode, event.getEventTime(), false, event.getMetaState()); 4354 return true; 4355 } 4356 // always handle the navigation keys in the UI thread 4357 // Bubble up the key event as WebView doesn't handle it 4358 return false; 4359 } 4360 4361 if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { 4362 // remove the long press message first 4363 mPrivateHandler.removeMessages(LONG_PRESS_CENTER); 4364 mGotCenterDown = false; 4365 4366 if (mSelectingText) { 4367 if (mExtendSelection) { 4368 copySelection(); 4369 selectionDone(); 4370 } else { 4371 mExtendSelection = true; 4372 nativeSetExtendSelection(); 4373 invalidate(); // draw the i-beam instead of the arrow 4374 } 4375 return true; // discard press if copy in progress 4376 } 4377 4378 // perform the single click 4379 Rect visibleRect = sendOurVisibleRect(); 4380 // Note that sendOurVisibleRect calls viewToContent, so the 4381 // coordinates should be in content coordinates. 4382 if (!nativeCursorIntersects(visibleRect)) { 4383 return false; 4384 } 4385 WebViewCore.CursorData data = cursorData(); 4386 mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE, data); 4387 playSoundEffect(SoundEffectConstants.CLICK); 4388 if (nativeCursorIsTextInput()) { 4389 rebuildWebTextView(); 4390 centerKeyPressOnTextField(); 4391 if (inEditingMode()) { 4392 mWebTextView.setDefaultSelection(); 4393 } 4394 return true; 4395 } 4396 clearTextEntry(); 4397 nativeShowCursorTimed(); 4398 if (!mCallbackProxy.uiOverrideUrlLoading(nativeCursorText())) { 4399 mWebViewCore.sendMessage(EventHub.CLICK, data.mFrame, 4400 nativeCursorNodePointer()); 4401 } 4402 return true; 4403 } 4404 4405 // TODO: should we pass all the keys to DOM or check the meta tag 4406 if (nativeCursorWantsKeyEvents() || true) { 4407 // pass the key to DOM 4408 mWebViewCore.sendMessage(EventHub.KEY_UP, event); 4409 // return true as DOM handles the key 4410 return true; 4411 } 4412 4413 // Bubble up the key event as WebView doesn't handle it 4414 return false; 4415 } 4416 4417 private void setUpSelect() { 4418 if (0 == mNativeClass) return; // client isn't initialized 4419 if (inFullScreenMode()) return; 4420 if (mSelectingText) return; 4421 mExtendSelection = false; 4422 mSelectingText = mDrawSelectionPointer = true; 4423 // don't let the picture change during text selection 4424 WebViewCore.pauseUpdatePicture(mWebViewCore); 4425 nativeResetSelection(); 4426 if (nativeHasCursorNode()) { 4427 Rect rect = nativeCursorNodeBounds(); 4428 mSelectX = contentToViewX(rect.left); 4429 mSelectY = contentToViewY(rect.top); 4430 } else if (mLastTouchY > getVisibleTitleHeight()) { 4431 mSelectX = mScrollX + (int) mLastTouchX; 4432 mSelectY = mScrollY + (int) mLastTouchY; 4433 } else { 4434 mSelectX = mScrollX + getViewWidth() / 2; 4435 mSelectY = mScrollY + getViewHeightWithTitle() / 2; 4436 } 4437 nativeHideCursor(); 4438 mSelectCallback = new SelectActionModeCallback(); 4439 mSelectCallback.setWebView(this); 4440 View titleBar = mTitleBar; 4441 // We do not want to show the embedded title bar during find or 4442 // select, but keep track of it so that it can be replaced when the 4443 // mode is exited. 4444 setEmbeddedTitleBar(null); 4445 mSelectCallback.setTitleBar(titleBar); 4446 startActionMode(mSelectCallback); 4447 } 4448 4449 /** 4450 * Use this method to put the WebView into text selection mode. 4451 * Do not rely on this functionality; it will be deprecated in the future. 4452 */ 4453 public void emulateShiftHeld() { 4454 setUpSelect(); 4455 } 4456 4457 /** 4458 * Select all of the text in this WebView. 4459 */ 4460 void selectAll() { 4461 if (0 == mNativeClass) return; // client isn't initialized 4462 if (inFullScreenMode()) return; 4463 if (!mSelectingText) setUpSelect(); 4464 nativeSelectAll(); 4465 mDrawSelectionPointer = false; 4466 mExtendSelection = true; 4467 invalidate(); 4468 } 4469 4470 /** 4471 * Called when the selection has been removed. 4472 */ 4473 void selectionDone() { 4474 if (mSelectingText) { 4475 mSelectingText = false; 4476 // finish is idempotent, so this is fine even if selectionDone was 4477 // called by mSelectCallback.onDestroyActionMode 4478 mSelectCallback.finish(); 4479 mSelectCallback = null; 4480 WebViewCore.resumeUpdatePicture(mWebViewCore); 4481 invalidate(); // redraw without selection 4482 } 4483 } 4484 4485 /** 4486 * Copy the selection to the clipboard 4487 */ 4488 boolean copySelection() { 4489 boolean copiedSomething = false; 4490 String selection = getSelection(); 4491 if (selection != "") { 4492 if (DebugFlags.WEB_VIEW) { 4493 Log.v(LOGTAG, "copySelection \"" + selection + "\""); 4494 } 4495 Toast.makeText(mContext 4496 , com.android.internal.R.string.text_copied 4497 , Toast.LENGTH_SHORT).show(); 4498 copiedSomething = true; 4499 ClipboardManager cm = (ClipboardManager)getContext() 4500 .getSystemService(Context.CLIPBOARD_SERVICE); 4501 cm.setText(selection); 4502 } 4503 invalidate(); // remove selection region and pointer 4504 return copiedSomething; 4505 } 4506 4507 /** 4508 * Returns the currently highlighted text as a string. 4509 */ 4510 String getSelection() { 4511 if (mNativeClass == 0) return ""; 4512 return nativeGetSelection(); 4513 } 4514 4515 @Override 4516 protected void onAttachedToWindow() { 4517 super.onAttachedToWindow(); 4518 if (hasWindowFocus()) setActive(true); 4519 } 4520 4521 @Override 4522 protected void onDetachedFromWindow() { 4523 clearHelpers(); 4524 mZoomManager.dismissZoomPicker(); 4525 if (hasWindowFocus()) setActive(false); 4526 super.onDetachedFromWindow(); 4527 } 4528 4529 @Override 4530 protected void onVisibilityChanged(View changedView, int visibility) { 4531 super.onVisibilityChanged(changedView, visibility); 4532 // The zoomManager may be null if the webview is created from XML that 4533 // specifies the view's visibility param as not visible (see http://b/2794841) 4534 if (visibility != View.VISIBLE && mZoomManager != null) { 4535 mZoomManager.dismissZoomPicker(); 4536 } 4537 } 4538 4539 /** 4540 * @deprecated WebView no longer needs to implement 4541 * ViewGroup.OnHierarchyChangeListener. This method does nothing now. 4542 */ 4543 @Deprecated 4544 public void onChildViewAdded(View parent, View child) {} 4545 4546 /** 4547 * @deprecated WebView no longer needs to implement 4548 * ViewGroup.OnHierarchyChangeListener. This method does nothing now. 4549 */ 4550 @Deprecated 4551 public void onChildViewRemoved(View p, View child) {} 4552 4553 /** 4554 * @deprecated WebView should not have implemented 4555 * ViewTreeObserver.OnGlobalFocusChangeListener. This method 4556 * does nothing now. 4557 */ 4558 @Deprecated 4559 public void onGlobalFocusChanged(View oldFocus, View newFocus) { 4560 } 4561 4562 private void setActive(boolean active) { 4563 if (active) { 4564 if (hasFocus()) { 4565 // If our window regained focus, and we have focus, then begin 4566 // drawing the cursor ring 4567 mDrawCursorRing = true; 4568 setFocusControllerActive(true); 4569 if (mNativeClass != 0) { 4570 nativeRecordButtons(true, false, true); 4571 } 4572 } else { 4573 if (!inEditingMode()) { 4574 // If our window gained focus, but we do not have it, do not 4575 // draw the cursor ring. 4576 mDrawCursorRing = false; 4577 setFocusControllerActive(false); 4578 } 4579 // We do not call nativeRecordButtons here because we assume 4580 // that when we lost focus, or window focus, it got called with 4581 // false for the first parameter 4582 } 4583 } else { 4584 if (!mZoomManager.isZoomPickerVisible()) { 4585 /* 4586 * The external zoom controls come in their own window, so our 4587 * window loses focus. Our policy is to not draw the cursor ring 4588 * if our window is not focused, but this is an exception since 4589 * the user can still navigate the web page with the zoom 4590 * controls showing. 4591 */ 4592 mDrawCursorRing = false; 4593 } 4594 mGotKeyDown = false; 4595 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 4596 mTouchMode = TOUCH_DONE_MODE; 4597 if (mNativeClass != 0) { 4598 nativeRecordButtons(false, false, true); 4599 } 4600 setFocusControllerActive(false); 4601 } 4602 invalidate(); 4603 } 4604 4605 // To avoid drawing the cursor ring, and remove the TextView when our window 4606 // loses focus. 4607 @Override 4608 public void onWindowFocusChanged(boolean hasWindowFocus) { 4609 setActive(hasWindowFocus); 4610 if (hasWindowFocus) { 4611 JWebCoreJavaBridge.setActiveWebView(this); 4612 } else { 4613 JWebCoreJavaBridge.removeActiveWebView(this); 4614 } 4615 super.onWindowFocusChanged(hasWindowFocus); 4616 } 4617 4618 /* 4619 * Pass a message to WebCore Thread, telling the WebCore::Page's 4620 * FocusController to be "inactive" so that it will 4621 * not draw the blinking cursor. It gets set to "active" to draw the cursor 4622 * in WebViewCore.cpp, when the WebCore thread receives key events/clicks. 4623 */ 4624 /* package */ void setFocusControllerActive(boolean active) { 4625 if (mWebViewCore == null) return; 4626 mWebViewCore.sendMessage(EventHub.SET_ACTIVE, active ? 1 : 0, 0); 4627 } 4628 4629 @Override 4630 protected void onFocusChanged(boolean focused, int direction, 4631 Rect previouslyFocusedRect) { 4632 if (DebugFlags.WEB_VIEW) { 4633 Log.v(LOGTAG, "MT focusChanged " + focused + ", " + direction); 4634 } 4635 if (focused) { 4636 // When we regain focus, if we have window focus, resume drawing 4637 // the cursor ring 4638 if (hasWindowFocus()) { 4639 mDrawCursorRing = true; 4640 if (mNativeClass != 0) { 4641 nativeRecordButtons(true, false, true); 4642 } 4643 setFocusControllerActive(true); 4644 //} else { 4645 // The WebView has gained focus while we do not have 4646 // windowfocus. When our window lost focus, we should have 4647 // called nativeRecordButtons(false...) 4648 } 4649 } else { 4650 // When we lost focus, unless focus went to the TextView (which is 4651 // true if we are in editing mode), stop drawing the cursor ring. 4652 if (!inEditingMode()) { 4653 mDrawCursorRing = false; 4654 if (mNativeClass != 0) { 4655 nativeRecordButtons(false, false, true); 4656 } 4657 setFocusControllerActive(false); 4658 } 4659 mGotKeyDown = false; 4660 } 4661 4662 super.onFocusChanged(focused, direction, previouslyFocusedRect); 4663 } 4664 4665 void setGLRectViewport() { 4666 View window = getRootView(); 4667 int[] location = new int[2]; 4668 getLocationInWindow(location); 4669 mGLRectViewport = new Rect(location[0], window.getHeight() 4670 - (location[1] + getHeight()), 4671 location[0] + getWidth(), 4672 window.getHeight() - location[1]); 4673 } 4674 4675 /** 4676 * @hide 4677 */ 4678 @Override 4679 protected boolean setFrame(int left, int top, int right, int bottom) { 4680 boolean changed = super.setFrame(left, top, right, bottom); 4681 if (!changed && mHeightCanMeasure) { 4682 // When mHeightCanMeasure is true, we will set mLastHeightSent to 0 4683 // in WebViewCore after we get the first layout. We do call 4684 // requestLayout() when we get contentSizeChanged(). But the View 4685 // system won't call onSizeChanged if the dimension is not changed. 4686 // In this case, we need to call sendViewSizeZoom() explicitly to 4687 // notify the WebKit about the new dimensions. 4688 sendViewSizeZoom(false); 4689 } 4690 setGLRectViewport(); 4691 return changed; 4692 } 4693 4694 @Override 4695 protected void onSizeChanged(int w, int h, int ow, int oh) { 4696 super.onSizeChanged(w, h, ow, oh); 4697 4698 // adjust the max viewport width depending on the view dimensions. This 4699 // is to ensure the scaling is not going insane. So do not shrink it if 4700 // the view size is temporarily smaller, e.g. when soft keyboard is up. 4701 int newMaxViewportWidth = (int) (Math.max(w, h) / mZoomManager.getDefaultMinZoomScale()); 4702 if (newMaxViewportWidth > sMaxViewportWidth) { 4703 sMaxViewportWidth = newMaxViewportWidth; 4704 } 4705 4706 mZoomManager.onSizeChanged(w, h, ow, oh); 4707 } 4708 4709 @Override 4710 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 4711 super.onScrollChanged(l, t, oldl, oldt); 4712 sendOurVisibleRect(); 4713 // update WebKit if visible title bar height changed. The logic is same 4714 // as getVisibleTitleHeight. 4715 int titleHeight = getTitleHeight(); 4716 if (Math.max(titleHeight - t, 0) != Math.max(titleHeight - oldt, 0)) { 4717 sendViewSizeZoom(false); 4718 } 4719 } 4720 4721 @Override 4722 public boolean dispatchKeyEvent(KeyEvent event) { 4723 boolean dispatch = true; 4724 4725 // Textfields, plugins, and contentEditable nodes need to receive the 4726 // shift up key even if another key was released while the shift key 4727 // was held down. 4728 if (!inEditingMode() && (mNativeClass == 0 4729 || !nativePageShouldHandleShiftAndArrows())) { 4730 if (event.getAction() == KeyEvent.ACTION_DOWN) { 4731 mGotKeyDown = true; 4732 } else { 4733 if (!mGotKeyDown) { 4734 /* 4735 * We got a key up for which we were not the recipient of 4736 * the original key down. Don't give it to the view. 4737 */ 4738 dispatch = false; 4739 } 4740 mGotKeyDown = false; 4741 } 4742 } 4743 4744 if (dispatch) { 4745 return super.dispatchKeyEvent(event); 4746 } else { 4747 // We didn't dispatch, so let something else handle the key 4748 return false; 4749 } 4750 } 4751 4752 // Here are the snap align logic: 4753 // 1. If it starts nearly horizontally or vertically, snap align; 4754 // 2. If there is a dramitic direction change, let it go; 4755 // 3. If there is a same direction back and forth, lock it. 4756 4757 // adjustable parameters 4758 private int mMinLockSnapReverseDistance; 4759 private static final float MAX_SLOPE_FOR_DIAG = 1.5f; 4760 private static final int MIN_BREAK_SNAP_CROSS_DISTANCE = 80; 4761 4762 private boolean hitFocusedPlugin(int contentX, int contentY) { 4763 if (DebugFlags.WEB_VIEW) { 4764 Log.v(LOGTAG, "nativeFocusIsPlugin()=" + nativeFocusIsPlugin()); 4765 Rect r = nativeFocusNodeBounds(); 4766 Log.v(LOGTAG, "nativeFocusNodeBounds()=(" + r.left + ", " + r.top 4767 + ", " + r.right + ", " + r.bottom + ")"); 4768 } 4769 return nativeFocusIsPlugin() 4770 && nativeFocusNodeBounds().contains(contentX, contentY); 4771 } 4772 4773 private boolean shouldForwardTouchEvent() { 4774 return mFullScreenHolder != null || (mForwardTouchEvents 4775 && !mSelectingText 4776 && mPreventDefault != PREVENT_DEFAULT_IGNORE); 4777 } 4778 4779 private boolean inFullScreenMode() { 4780 return mFullScreenHolder != null; 4781 } 4782 4783 private void dismissFullScreenMode() { 4784 if (inFullScreenMode()) { 4785 mFullScreenHolder.dismiss(); 4786 mFullScreenHolder = null; 4787 } 4788 } 4789 4790 void onPinchToZoomAnimationStart() { 4791 // cancel the single touch handling 4792 cancelTouch(); 4793 onZoomAnimationStart(); 4794 } 4795 4796 void onPinchToZoomAnimationEnd(ScaleGestureDetector detector) { 4797 onZoomAnimationEnd(); 4798 // start a drag, TOUCH_PINCH_DRAG, can't use TOUCH_INIT_MODE as 4799 // it may trigger the unwanted click, can't use TOUCH_DRAG_MODE 4800 // as it may trigger the unwanted fling. 4801 mTouchMode = TOUCH_PINCH_DRAG; 4802 mConfirmMove = true; 4803 startTouch(detector.getFocusX(), detector.getFocusY(), mLastTouchTime); 4804 } 4805 4806 private void startScrollingLayer(float gestureX, float gestureY) { 4807 if (mTouchMode != TOUCH_DRAG_LAYER_MODE) { 4808 int contentX = viewToContentX((int) gestureX + mScrollX); 4809 int contentY = viewToContentY((int) gestureY + mScrollY); 4810 mScrollingLayer = nativeScrollableLayer(contentX, contentY); 4811 if (mScrollingLayer != 0) { 4812 mTouchMode = TOUCH_DRAG_LAYER_MODE; 4813 } 4814 } 4815 } 4816 4817 // 1/(density * density) used to compute the distance between points. 4818 // Computed in init(). 4819 private float DRAG_LAYER_INVERSE_DENSITY_SQUARED; 4820 4821 // The distance between two points reported in onTouchEvent scaled by the 4822 // density of the screen. 4823 private static final int DRAG_LAYER_FINGER_DISTANCE = 20000; 4824 4825 @Override 4826 public boolean onTouchEvent(MotionEvent ev) { 4827 if (mNativeClass == 0 || (!isClickable() && !isLongClickable())) { 4828 return false; 4829 } 4830 4831 if (DebugFlags.WEB_VIEW) { 4832 Log.v(LOGTAG, ev + " at " + ev.getEventTime() 4833 + " mTouchMode=" + mTouchMode 4834 + " numPointers=" + ev.getPointerCount()); 4835 } 4836 4837 int action = ev.getAction(); 4838 float x = ev.getX(); 4839 float y = ev.getY(); 4840 long eventTime = ev.getEventTime(); 4841 4842 final ScaleGestureDetector detector = 4843 mZoomManager.getMultiTouchGestureDetector(); 4844 boolean skipScaleGesture = false; 4845 // Set to the mid-point of a two-finger gesture used to detect if the 4846 // user has touched a layer. 4847 float gestureX = x; 4848 float gestureY = y; 4849 if (detector == null || !detector.isInProgress()) { 4850 // The gesture for scrolling a layer is two fingers close together. 4851 // FIXME: we may consider giving WebKit an option to handle 4852 // multi-touch events later. 4853 if (ev.getPointerCount() > 1) { 4854 float dx = ev.getX(1) - ev.getX(0); 4855 float dy = ev.getY(1) - ev.getY(0); 4856 float dist = (dx * dx + dy * dy) * 4857 DRAG_LAYER_INVERSE_DENSITY_SQUARED; 4858 // Use the approximate center to determine if the gesture is in 4859 // a layer. 4860 gestureX = ev.getX(0) + (dx * .5f); 4861 gestureY = ev.getY(0) + (dy * .5f); 4862 // Now use a consistent point for tracking movement. 4863 if (ev.getX(0) < ev.getX(1)) { 4864 x = ev.getX(0); 4865 y = ev.getY(0); 4866 } else { 4867 x = ev.getX(1); 4868 y = ev.getY(1); 4869 } 4870 action = ev.getActionMasked(); 4871 if (dist < DRAG_LAYER_FINGER_DISTANCE) { 4872 skipScaleGesture = true; 4873 } else if (mTouchMode == TOUCH_DRAG_LAYER_MODE) { 4874 // Fingers moved too far apart while dragging, the user 4875 // might be trying to zoom. 4876 mTouchMode = TOUCH_INIT_MODE; 4877 } 4878 } 4879 } 4880 4881 // If the page disallows zoom, pass multi-pointer events to webkit. 4882 if (!skipScaleGesture && ev.getPointerCount() > 1 4883 && (mZoomManager.isZoomScaleFixed() || mDeferMultitouch)) { 4884 if (DebugFlags.WEB_VIEW) { 4885 Log.v(LOGTAG, "passing " + ev.getPointerCount() + " points to webkit"); 4886 } 4887 passMultiTouchToWebKit(ev); 4888 return true; 4889 } 4890 4891 if (mZoomManager.supportsMultiTouchZoom() && ev.getPointerCount() > 1 && 4892 mTouchMode != TOUCH_DRAG_LAYER_MODE && !skipScaleGesture) { 4893 if (!detector.isInProgress() && 4894 ev.getActionMasked() != MotionEvent.ACTION_POINTER_DOWN) { 4895 // Insert a fake pointer down event in order to start 4896 // the zoom scale detector. 4897 MotionEvent temp = MotionEvent.obtain(ev); 4898 // Clear the original event and set it to 4899 // ACTION_POINTER_DOWN. 4900 try { 4901 temp.setAction(temp.getAction() & 4902 ~MotionEvent.ACTION_MASK | 4903 MotionEvent.ACTION_POINTER_DOWN); 4904 detector.onTouchEvent(temp); 4905 } finally { 4906 temp.recycle(); 4907 } 4908 } 4909 4910 detector.onTouchEvent(ev); 4911 4912 if (detector.isInProgress()) { 4913 mLastTouchTime = eventTime; 4914 cancelLongPress(); 4915 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 4916 if (!mZoomManager.supportsPanDuringZoom()) { 4917 return true; 4918 } 4919 mTouchMode = TOUCH_DRAG_MODE; 4920 if (mVelocityTracker == null) { 4921 mVelocityTracker = VelocityTracker.obtain(); 4922 } 4923 } 4924 4925 x = detector.getFocusX(); 4926 y = detector.getFocusY(); 4927 action = ev.getAction() & MotionEvent.ACTION_MASK; 4928 if (action == MotionEvent.ACTION_POINTER_DOWN) { 4929 cancelTouch(); 4930 action = MotionEvent.ACTION_DOWN; 4931 } else if (action == MotionEvent.ACTION_POINTER_UP) { 4932 // set mLastTouchX/Y to the remaining point 4933 mLastTouchX = x; 4934 mLastTouchY = y; 4935 } else if (action == MotionEvent.ACTION_MOVE) { 4936 // negative x or y indicate it is on the edge, skip it. 4937 if (x < 0 || y < 0) { 4938 return true; 4939 } 4940 } 4941 } 4942 4943 // Due to the touch screen edge effect, a touch closer to the edge 4944 // always snapped to the edge. As getViewWidth() can be different from 4945 // getWidth() due to the scrollbar, adjusting the point to match 4946 // getViewWidth(). Same applied to the height. 4947 x = Math.min(x, getViewWidth() - 1); 4948 y = Math.min(y, getViewHeightWithTitle() - 1); 4949 4950 float fDeltaX = mLastTouchX - x; 4951 float fDeltaY = mLastTouchY - y; 4952 int deltaX = (int) fDeltaX; 4953 int deltaY = (int) fDeltaY; 4954 int contentX = viewToContentX((int) x + mScrollX); 4955 int contentY = viewToContentY((int) y + mScrollY); 4956 4957 switch (action) { 4958 case MotionEvent.ACTION_DOWN: { 4959 mPreventDefault = PREVENT_DEFAULT_NO; 4960 mConfirmMove = false; 4961 if (!mScroller.isFinished()) { 4962 // stop the current scroll animation, but if this is 4963 // the start of a fling, allow it to add to the current 4964 // fling's velocity 4965 mScroller.abortAnimation(); 4966 mTouchMode = TOUCH_DRAG_START_MODE; 4967 mConfirmMove = true; 4968 mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY); 4969 } else if (mPrivateHandler.hasMessages(RELEASE_SINGLE_TAP)) { 4970 mPrivateHandler.removeMessages(RELEASE_SINGLE_TAP); 4971 if (getSettings().supportTouchOnly()) { 4972 removeTouchHighlight(true); 4973 } 4974 if (deltaX * deltaX + deltaY * deltaY < mDoubleTapSlopSquare) { 4975 mTouchMode = TOUCH_DOUBLE_TAP_MODE; 4976 } else { 4977 // commit the short press action for the previous tap 4978 doShortPress(); 4979 mTouchMode = TOUCH_INIT_MODE; 4980 mDeferTouchProcess = (!inFullScreenMode() 4981 && mForwardTouchEvents) ? hitFocusedPlugin( 4982 contentX, contentY) : false; 4983 } 4984 } else { // the normal case 4985 mTouchMode = TOUCH_INIT_MODE; 4986 mDeferTouchProcess = (!inFullScreenMode() 4987 && mForwardTouchEvents) ? hitFocusedPlugin( 4988 contentX, contentY) : false; 4989 mWebViewCore.sendMessage( 4990 EventHub.UPDATE_FRAME_CACHE_IF_LOADING); 4991 if (getSettings().supportTouchOnly()) { 4992 TouchHighlightData data = new TouchHighlightData(); 4993 data.mX = contentX; 4994 data.mY = contentY; 4995 data.mSlop = viewToContentDimension(mNavSlop); 4996 mWebViewCore.sendMessageDelayed( 4997 EventHub.GET_TOUCH_HIGHLIGHT_RECTS, data, 4998 ViewConfiguration.getTapTimeout()); 4999 if (DEBUG_TOUCH_HIGHLIGHT) { 5000 if (getSettings().getNavDump()) { 5001 mTouchHighlightX = (int) x + mScrollX; 5002 mTouchHighlightY = (int) y + mScrollY; 5003 mPrivateHandler.postDelayed(new Runnable() { 5004 public void run() { 5005 mTouchHighlightX = mTouchHighlightY = 0; 5006 invalidate(); 5007 } 5008 }, TOUCH_HIGHLIGHT_ELAPSE_TIME); 5009 } 5010 } 5011 } 5012 if (mLogEvent && eventTime - mLastTouchUpTime < 1000) { 5013 EventLog.writeEvent(EventLogTags.BROWSER_DOUBLE_TAP_DURATION, 5014 (eventTime - mLastTouchUpTime), eventTime); 5015 } 5016 if (mSelectingText) { 5017 mDrawSelectionPointer = false; 5018 mSelectionStarted = nativeStartSelection(contentX, contentY); 5019 if (DebugFlags.WEB_VIEW) { 5020 Log.v(LOGTAG, "select=" + contentX + "," + contentY); 5021 } 5022 invalidate(); 5023 } 5024 } 5025 // Trigger the link 5026 if (mTouchMode == TOUCH_INIT_MODE 5027 || mTouchMode == TOUCH_DOUBLE_TAP_MODE) { 5028 mPrivateHandler.sendEmptyMessageDelayed( 5029 SWITCH_TO_SHORTPRESS, TAP_TIMEOUT); 5030 mPrivateHandler.sendEmptyMessageDelayed( 5031 SWITCH_TO_LONGPRESS, LONG_PRESS_TIMEOUT); 5032 if (inFullScreenMode() || mDeferTouchProcess) { 5033 mPreventDefault = PREVENT_DEFAULT_YES; 5034 } else if (mForwardTouchEvents) { 5035 mPreventDefault = PREVENT_DEFAULT_MAYBE_YES; 5036 } else { 5037 mPreventDefault = PREVENT_DEFAULT_NO; 5038 } 5039 // pass the touch events from UI thread to WebCore thread 5040 if (shouldForwardTouchEvent()) { 5041 TouchEventData ted = new TouchEventData(); 5042 ted.mAction = action; 5043 ted.mPoints = new Point[1]; 5044 ted.mPoints[0] = new Point(contentX, contentY); 5045 ted.mMetaState = ev.getMetaState(); 5046 ted.mReprocess = mDeferTouchProcess; 5047 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 5048 if (mDeferTouchProcess) { 5049 // still needs to set them for compute deltaX/Y 5050 mLastTouchX = x; 5051 mLastTouchY = y; 5052 break; 5053 } 5054 if (!inFullScreenMode()) { 5055 mPrivateHandler.removeMessages(PREVENT_DEFAULT_TIMEOUT); 5056 mPrivateHandler.sendMessageDelayed(mPrivateHandler 5057 .obtainMessage(PREVENT_DEFAULT_TIMEOUT, 5058 action, 0), TAP_TIMEOUT); 5059 } 5060 } 5061 } 5062 startTouch(x, y, eventTime); 5063 break; 5064 } 5065 case MotionEvent.ACTION_MOVE: { 5066 boolean firstMove = false; 5067 if (!mConfirmMove && (deltaX * deltaX + deltaY * deltaY) 5068 >= mTouchSlopSquare) { 5069 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 5070 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 5071 mConfirmMove = true; 5072 firstMove = true; 5073 if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) { 5074 mTouchMode = TOUCH_INIT_MODE; 5075 } 5076 if (getSettings().supportTouchOnly()) { 5077 removeTouchHighlight(true); 5078 } 5079 } 5080 // pass the touch events from UI thread to WebCore thread 5081 if (shouldForwardTouchEvent() && mConfirmMove && (firstMove 5082 || eventTime - mLastSentTouchTime > mCurrentTouchInterval)) { 5083 TouchEventData ted = new TouchEventData(); 5084 ted.mAction = action; 5085 ted.mPoints = new Point[1]; 5086 ted.mPoints[0] = new Point(contentX, contentY); 5087 ted.mMetaState = ev.getMetaState(); 5088 ted.mReprocess = mDeferTouchProcess; 5089 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 5090 mLastSentTouchTime = eventTime; 5091 if (mDeferTouchProcess) { 5092 break; 5093 } 5094 if (firstMove && !inFullScreenMode()) { 5095 mPrivateHandler.sendMessageDelayed(mPrivateHandler 5096 .obtainMessage(PREVENT_DEFAULT_TIMEOUT, 5097 action, 0), TAP_TIMEOUT); 5098 } 5099 } 5100 if (mTouchMode == TOUCH_DONE_MODE 5101 || mPreventDefault == PREVENT_DEFAULT_YES) { 5102 // no dragging during scroll zoom animation, or when prevent 5103 // default is yes 5104 break; 5105 } 5106 if (mVelocityTracker == null) { 5107 Log.e(LOGTAG, "Got null mVelocityTracker when " 5108 + "mPreventDefault = " + mPreventDefault 5109 + " mDeferTouchProcess = " + mDeferTouchProcess 5110 + " mTouchMode = " + mTouchMode); 5111 } 5112 mVelocityTracker.addMovement(ev); 5113 if (mSelectingText && mSelectionStarted) { 5114 if (DebugFlags.WEB_VIEW) { 5115 Log.v(LOGTAG, "extend=" + contentX + "," + contentY); 5116 } 5117 ViewParent parent = getParent(); 5118 if (parent != null) { 5119 parent.requestDisallowInterceptTouchEvent(true); 5120 } 5121 nativeExtendSelection(contentX, contentY); 5122 invalidate(); 5123 break; 5124 } 5125 5126 if (mTouchMode != TOUCH_DRAG_MODE && 5127 mTouchMode != TOUCH_DRAG_LAYER_MODE) { 5128 5129 if (!mConfirmMove) { 5130 break; 5131 } 5132 5133 if (mPreventDefault == PREVENT_DEFAULT_MAYBE_YES 5134 || mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN) { 5135 // track mLastTouchTime as we may need to do fling at 5136 // ACTION_UP 5137 mLastTouchTime = eventTime; 5138 break; 5139 } 5140 5141 // Only lock dragging to one axis if we don't have a scale in progress. 5142 // Scaling implies free-roaming movement. Note this is only ever a question 5143 // if mZoomManager.supportsPanDuringZoom() is true. 5144 if (detector != null && !detector.isInProgress()) { 5145 // if it starts nearly horizontal or vertical, enforce it 5146 int ax = Math.abs(deltaX); 5147 int ay = Math.abs(deltaY); 5148 if (ax > MAX_SLOPE_FOR_DIAG * ay) { 5149 mSnapScrollMode = SNAP_X; 5150 mSnapPositive = deltaX > 0; 5151 } else if (ay > MAX_SLOPE_FOR_DIAG * ax) { 5152 mSnapScrollMode = SNAP_Y; 5153 mSnapPositive = deltaY > 0; 5154 } 5155 } 5156 5157 mTouchMode = TOUCH_DRAG_MODE; 5158 mLastTouchX = x; 5159 mLastTouchY = y; 5160 fDeltaX = 0.0f; 5161 fDeltaY = 0.0f; 5162 deltaX = 0; 5163 deltaY = 0; 5164 5165 if (skipScaleGesture) { 5166 startScrollingLayer(gestureX, gestureY); 5167 } 5168 startDrag(); 5169 } 5170 5171 // do pan 5172 if (mTouchMode != TOUCH_DRAG_LAYER_MODE) { 5173 int newScrollX = pinLocX(mScrollX + deltaX); 5174 int newDeltaX = newScrollX - mScrollX; 5175 if (deltaX != newDeltaX) { 5176 deltaX = newDeltaX; 5177 fDeltaX = (float) newDeltaX; 5178 } 5179 int newScrollY = pinLocY(mScrollY + deltaY); 5180 int newDeltaY = newScrollY - mScrollY; 5181 if (deltaY != newDeltaY) { 5182 deltaY = newDeltaY; 5183 fDeltaY = (float) newDeltaY; 5184 } 5185 } 5186 boolean done = false; 5187 boolean keepScrollBarsVisible = false; 5188 if (Math.abs(fDeltaX) < 1.0f && Math.abs(fDeltaY) < 1.0f) { 5189 mLastTouchX = x; 5190 mLastTouchY = y; 5191 keepScrollBarsVisible = done = true; 5192 } else { 5193 if (mSnapScrollMode == SNAP_X || mSnapScrollMode == SNAP_Y) { 5194 int ax = Math.abs(deltaX); 5195 int ay = Math.abs(deltaY); 5196 if (mSnapScrollMode == SNAP_X) { 5197 // radical change means getting out of snap mode 5198 if (ay > MAX_SLOPE_FOR_DIAG * ax 5199 && ay > MIN_BREAK_SNAP_CROSS_DISTANCE) { 5200 mSnapScrollMode = SNAP_NONE; 5201 } 5202 // reverse direction means lock in the snap mode 5203 if (ax > MAX_SLOPE_FOR_DIAG * ay && 5204 (mSnapPositive 5205 ? deltaX < -mMinLockSnapReverseDistance 5206 : deltaX > mMinLockSnapReverseDistance)) { 5207 mSnapScrollMode |= SNAP_LOCK; 5208 } 5209 } else { 5210 // radical change means getting out of snap mode 5211 if (ax > MAX_SLOPE_FOR_DIAG * ay 5212 && ax > MIN_BREAK_SNAP_CROSS_DISTANCE) { 5213 mSnapScrollMode = SNAP_NONE; 5214 } 5215 // reverse direction means lock in the snap mode 5216 if (ay > MAX_SLOPE_FOR_DIAG * ax && 5217 (mSnapPositive 5218 ? deltaY < -mMinLockSnapReverseDistance 5219 : deltaY > mMinLockSnapReverseDistance)) { 5220 mSnapScrollMode |= SNAP_LOCK; 5221 } 5222 } 5223 } 5224 if (mSnapScrollMode != SNAP_NONE) { 5225 if ((mSnapScrollMode & SNAP_X) == SNAP_X) { 5226 deltaY = 0; 5227 } else { 5228 deltaX = 0; 5229 } 5230 } 5231 if ((deltaX | deltaY) != 0) { 5232 if (deltaX != 0) { 5233 mLastTouchX = x; 5234 } 5235 if (deltaY != 0) { 5236 mLastTouchY = y; 5237 } 5238 mHeldMotionless = MOTIONLESS_FALSE; 5239 } else { 5240 // keep the scrollbar on the screen even there is no 5241 // scroll 5242 mLastTouchX = x; 5243 mLastTouchY = y; 5244 keepScrollBarsVisible = true; 5245 } 5246 mLastTouchTime = eventTime; 5247 mUserScroll = true; 5248 } 5249 5250 doDrag(deltaX, deltaY); 5251 5252 // Turn off scrollbars when dragging a layer. 5253 if (keepScrollBarsVisible && 5254 mTouchMode != TOUCH_DRAG_LAYER_MODE) { 5255 if (mHeldMotionless != MOTIONLESS_TRUE) { 5256 mHeldMotionless = MOTIONLESS_TRUE; 5257 invalidate(); 5258 } 5259 // keep the scrollbar on the screen even there is no scroll 5260 awakenScrollBars(ViewConfiguration.getScrollDefaultDelay(), 5261 false); 5262 // return false to indicate that we can't pan out of the 5263 // view space 5264 return !done; 5265 } 5266 break; 5267 } 5268 case MotionEvent.ACTION_UP: { 5269 if (!isFocused()) requestFocus(); 5270 // pass the touch events from UI thread to WebCore thread 5271 if (shouldForwardTouchEvent()) { 5272 TouchEventData ted = new TouchEventData(); 5273 ted.mAction = action; 5274 ted.mPoints = new Point[1]; 5275 ted.mPoints[0] = new Point(contentX, contentY); 5276 ted.mMetaState = ev.getMetaState(); 5277 ted.mReprocess = mDeferTouchProcess; 5278 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 5279 } 5280 mLastTouchUpTime = eventTime; 5281 switch (mTouchMode) { 5282 case TOUCH_DOUBLE_TAP_MODE: // double tap 5283 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 5284 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 5285 if (inFullScreenMode() || mDeferTouchProcess) { 5286 TouchEventData ted = new TouchEventData(); 5287 ted.mAction = WebViewCore.ACTION_DOUBLETAP; 5288 ted.mPoints = new Point[1]; 5289 ted.mPoints[0] = new Point(contentX, contentY); 5290 ted.mMetaState = ev.getMetaState(); 5291 ted.mReprocess = mDeferTouchProcess; 5292 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 5293 } else if (mPreventDefault != PREVENT_DEFAULT_YES){ 5294 mZoomManager.handleDoubleTap(mLastTouchX, mLastTouchY); 5295 mTouchMode = TOUCH_DONE_MODE; 5296 } 5297 break; 5298 case TOUCH_INIT_MODE: // tap 5299 case TOUCH_SHORTPRESS_START_MODE: 5300 case TOUCH_SHORTPRESS_MODE: 5301 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 5302 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 5303 if (mConfirmMove) { 5304 Log.w(LOGTAG, "Miss a drag as we are waiting for" + 5305 " WebCore's response for touch down."); 5306 if (mPreventDefault != PREVENT_DEFAULT_YES 5307 && (computeMaxScrollX() > 0 5308 || computeMaxScrollY() > 0)) { 5309 // If the user has performed a very quick touch 5310 // sequence it is possible that we may get here 5311 // before WebCore has had a chance to process the events. 5312 // In this case, any call to preventDefault in the 5313 // JS touch handler will not have been executed yet. 5314 // Hence we will see both the UI (now) and WebCore 5315 // (when context switches) handling the event, 5316 // regardless of whether the web developer actually 5317 // doeses preventDefault in their touch handler. This 5318 // is the nature of our asynchronous touch model. 5319 5320 // we will not rewrite drag code here, but we 5321 // will try fling if it applies. 5322 WebViewCore.reducePriority(); 5323 // to get better performance, pause updating the 5324 // picture 5325 WebViewCore.pauseUpdatePicture(mWebViewCore); 5326 // fall through to TOUCH_DRAG_MODE 5327 } else { 5328 // WebKit may consume the touch event and modify 5329 // DOM. drawContentPicture() will be called with 5330 // animateSroll as true for better performance. 5331 // Force redraw in high-quality. 5332 invalidate(); 5333 break; 5334 } 5335 } else { 5336 if (mSelectingText) { 5337 // tapping on selection or controls does nothing 5338 if (!nativeHitSelection(contentX, contentY)) { 5339 selectionDone(); 5340 } 5341 break; 5342 } 5343 // only trigger double tap if the WebView is 5344 // scalable 5345 if (mTouchMode == TOUCH_INIT_MODE 5346 && (canZoomIn() || canZoomOut())) { 5347 mPrivateHandler.sendEmptyMessageDelayed( 5348 RELEASE_SINGLE_TAP, ViewConfiguration 5349 .getDoubleTapTimeout()); 5350 } else { 5351 doShortPress(); 5352 } 5353 break; 5354 } 5355 case TOUCH_DRAG_MODE: 5356 mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS); 5357 mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS); 5358 // if the user waits a while w/o moving before the 5359 // up, we don't want to do a fling 5360 if (eventTime - mLastTouchTime <= MIN_FLING_TIME) { 5361 if (mVelocityTracker == null) { 5362 Log.e(LOGTAG, "Got null mVelocityTracker when " 5363 + "mPreventDefault = " 5364 + mPreventDefault 5365 + " mDeferTouchProcess = " 5366 + mDeferTouchProcess); 5367 } 5368 mVelocityTracker.addMovement(ev); 5369 // set to MOTIONLESS_IGNORE so that it won't keep 5370 // removing and sending message in 5371 // drawCoreAndCursorRing() 5372 mHeldMotionless = MOTIONLESS_IGNORE; 5373 doFling(); 5374 break; 5375 } 5376 // redraw in high-quality, as we're done dragging 5377 mHeldMotionless = MOTIONLESS_TRUE; 5378 invalidate(); 5379 // fall through 5380 case TOUCH_DRAG_START_MODE: 5381 case TOUCH_DRAG_LAYER_MODE: 5382 // TOUCH_DRAG_START_MODE should not happen for the real 5383 // device as we almost certain will get a MOVE. But this 5384 // is possible on emulator. 5385 mLastVelocity = 0; 5386 WebViewCore.resumePriority(); 5387 WebViewCore.resumeUpdatePicture(mWebViewCore); 5388 break; 5389 } 5390 stopTouch(); 5391 break; 5392 } 5393 case MotionEvent.ACTION_CANCEL: { 5394 if (mTouchMode == TOUCH_DRAG_MODE) { 5395 invalidate(); 5396 } 5397 cancelWebCoreTouchEvent(contentX, contentY, false); 5398 cancelTouch(); 5399 break; 5400 } 5401 } 5402 return true; 5403 } 5404 5405 private void passMultiTouchToWebKit(MotionEvent ev) { 5406 TouchEventData ted = new TouchEventData(); 5407 ted.mAction = ev.getAction() & MotionEvent.ACTION_MASK; 5408 final int count = ev.getPointerCount(); 5409 ted.mPoints = new Point[count]; 5410 for (int c = 0; c < count; c++) { 5411 int x = viewToContentX((int) ev.getX(c) + mScrollX); 5412 int y = viewToContentY((int) ev.getY(c) + mScrollY); 5413 ted.mPoints[c] = new Point(x, y); 5414 } 5415 ted.mMetaState = ev.getMetaState(); 5416 ted.mReprocess = mDeferTouchProcess; 5417 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 5418 cancelLongPress(); 5419 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 5420 mPreventDefault = PREVENT_DEFAULT_IGNORE; 5421 } 5422 5423 private void cancelWebCoreTouchEvent(int x, int y, boolean removeEvents) { 5424 if (shouldForwardTouchEvent()) { 5425 if (removeEvents) { 5426 mWebViewCore.removeMessages(EventHub.TOUCH_EVENT); 5427 } 5428 TouchEventData ted = new TouchEventData(); 5429 ted.mPoints = new Point[1]; 5430 ted.mPoints[0] = new Point(x, y); 5431 ted.mAction = MotionEvent.ACTION_CANCEL; 5432 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 5433 mPreventDefault = PREVENT_DEFAULT_IGNORE; 5434 } 5435 } 5436 5437 private void startTouch(float x, float y, long eventTime) { 5438 // Remember where the motion event started 5439 mLastTouchX = x; 5440 mLastTouchY = y; 5441 mLastTouchTime = eventTime; 5442 mVelocityTracker = VelocityTracker.obtain(); 5443 mSnapScrollMode = SNAP_NONE; 5444 } 5445 5446 private void startDrag() { 5447 WebViewCore.reducePriority(); 5448 // to get better performance, pause updating the picture 5449 WebViewCore.pauseUpdatePicture(mWebViewCore); 5450 if (!mDragFromTextInput) { 5451 nativeHideCursor(); 5452 } 5453 5454 if (mHorizontalScrollBarMode != SCROLLBAR_ALWAYSOFF 5455 || mVerticalScrollBarMode != SCROLLBAR_ALWAYSOFF) { 5456 mZoomManager.invokeZoomPicker(); 5457 } 5458 } 5459 5460 private void doDrag(int deltaX, int deltaY) { 5461 if ((deltaX | deltaY) != 0) { 5462 if (mTouchMode == TOUCH_DRAG_LAYER_MODE) { 5463 deltaX = viewToContentDimension(deltaX); 5464 deltaY = viewToContentDimension(deltaY); 5465 if (nativeScrollLayer(mScrollingLayer, deltaX, deltaY)) { 5466 invalidate(); 5467 } 5468 return; 5469 } 5470 scrollBy(deltaX, deltaY); 5471 } 5472 mZoomManager.keepZoomPickerVisible(); 5473 } 5474 5475 private void stopTouch() { 5476 // we also use mVelocityTracker == null to tell us that we are 5477 // not "moving around", so we can take the slower/prettier 5478 // mode in the drawing code 5479 if (mVelocityTracker != null) { 5480 mVelocityTracker.recycle(); 5481 mVelocityTracker = null; 5482 } 5483 } 5484 5485 private void cancelTouch() { 5486 // we also use mVelocityTracker == null to tell us that we are 5487 // not "moving around", so we can take the slower/prettier 5488 // mode in the drawing code 5489 if (mVelocityTracker != null) { 5490 mVelocityTracker.recycle(); 5491 mVelocityTracker = null; 5492 } 5493 if (mTouchMode == TOUCH_DRAG_MODE || 5494 mTouchMode == TOUCH_DRAG_LAYER_MODE) { 5495 WebViewCore.resumePriority(); 5496 WebViewCore.resumeUpdatePicture(mWebViewCore); 5497 } 5498 mPrivateHandler.removeMessages(SWITCH_TO_SHORTPRESS); 5499 mPrivateHandler.removeMessages(SWITCH_TO_LONGPRESS); 5500 mPrivateHandler.removeMessages(DRAG_HELD_MOTIONLESS); 5501 mPrivateHandler.removeMessages(AWAKEN_SCROLL_BARS); 5502 if (getSettings().supportTouchOnly()) { 5503 removeTouchHighlight(true); 5504 } 5505 mHeldMotionless = MOTIONLESS_TRUE; 5506 mTouchMode = TOUCH_DONE_MODE; 5507 nativeHideCursor(); 5508 } 5509 5510 private long mTrackballFirstTime = 0; 5511 private long mTrackballLastTime = 0; 5512 private float mTrackballRemainsX = 0.0f; 5513 private float mTrackballRemainsY = 0.0f; 5514 private int mTrackballXMove = 0; 5515 private int mTrackballYMove = 0; 5516 private boolean mSelectingText = false; 5517 private boolean mSelectionStarted = false; 5518 private boolean mExtendSelection = false; 5519 private boolean mDrawSelectionPointer = false; 5520 private static final int TRACKBALL_KEY_TIMEOUT = 1000; 5521 private static final int TRACKBALL_TIMEOUT = 200; 5522 private static final int TRACKBALL_WAIT = 100; 5523 private static final int TRACKBALL_SCALE = 400; 5524 private static final int TRACKBALL_SCROLL_COUNT = 5; 5525 private static final int TRACKBALL_MOVE_COUNT = 10; 5526 private static final int TRACKBALL_MULTIPLIER = 3; 5527 private static final int SELECT_CURSOR_OFFSET = 16; 5528 private int mSelectX = 0; 5529 private int mSelectY = 0; 5530 private boolean mFocusSizeChanged = false; 5531 private boolean mTrackballDown = false; 5532 private long mTrackballUpTime = 0; 5533 private long mLastCursorTime = 0; 5534 private Rect mLastCursorBounds; 5535 5536 // Set by default; BrowserActivity clears to interpret trackball data 5537 // directly for movement. Currently, the framework only passes 5538 // arrow key events, not trackball events, from one child to the next 5539 private boolean mMapTrackballToArrowKeys = true; 5540 5541 public void setMapTrackballToArrowKeys(boolean setMap) { 5542 mMapTrackballToArrowKeys = setMap; 5543 } 5544 5545 void resetTrackballTime() { 5546 mTrackballLastTime = 0; 5547 } 5548 5549 @Override 5550 public boolean onTrackballEvent(MotionEvent ev) { 5551 long time = ev.getEventTime(); 5552 if ((ev.getMetaState() & KeyEvent.META_ALT_ON) != 0) { 5553 if (ev.getY() > 0) pageDown(true); 5554 if (ev.getY() < 0) pageUp(true); 5555 return true; 5556 } 5557 if (ev.getAction() == MotionEvent.ACTION_DOWN) { 5558 if (mSelectingText) { 5559 return true; // discard press if copy in progress 5560 } 5561 mTrackballDown = true; 5562 if (mNativeClass == 0) { 5563 return false; 5564 } 5565 nativeRecordButtons(hasFocus() && hasWindowFocus(), true, true); 5566 if (time - mLastCursorTime <= TRACKBALL_TIMEOUT 5567 && !mLastCursorBounds.equals(nativeGetCursorRingBounds())) { 5568 nativeSelectBestAt(mLastCursorBounds); 5569 } 5570 if (DebugFlags.WEB_VIEW) { 5571 Log.v(LOGTAG, "onTrackballEvent down ev=" + ev 5572 + " time=" + time 5573 + " mLastCursorTime=" + mLastCursorTime); 5574 } 5575 if (isInTouchMode()) requestFocusFromTouch(); 5576 return false; // let common code in onKeyDown at it 5577 } 5578 if (ev.getAction() == MotionEvent.ACTION_UP) { 5579 // LONG_PRESS_CENTER is set in common onKeyDown 5580 mPrivateHandler.removeMessages(LONG_PRESS_CENTER); 5581 mTrackballDown = false; 5582 mTrackballUpTime = time; 5583 if (mSelectingText) { 5584 if (mExtendSelection) { 5585 copySelection(); 5586 selectionDone(); 5587 } else { 5588 mExtendSelection = true; 5589 nativeSetExtendSelection(); 5590 invalidate(); // draw the i-beam instead of the arrow 5591 } 5592 return true; // discard press if copy in progress 5593 } 5594 if (DebugFlags.WEB_VIEW) { 5595 Log.v(LOGTAG, "onTrackballEvent up ev=" + ev 5596 + " time=" + time 5597 ); 5598 } 5599 return false; // let common code in onKeyUp at it 5600 } 5601 if ((mMapTrackballToArrowKeys && (ev.getMetaState() & KeyEvent.META_SHIFT_ON) == 0) || 5602 (mAccessibilityInjector != null || mAccessibilityScriptInjected)) { 5603 if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent gmail quit"); 5604 return false; 5605 } 5606 if (mTrackballDown) { 5607 if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent down quit"); 5608 return true; // discard move if trackball is down 5609 } 5610 if (time - mTrackballUpTime < TRACKBALL_TIMEOUT) { 5611 if (DebugFlags.WEB_VIEW) Log.v(LOGTAG, "onTrackballEvent up timeout quit"); 5612 return true; 5613 } 5614 // TODO: alternatively we can do panning as touch does 5615 switchOutDrawHistory(); 5616 if (time - mTrackballLastTime > TRACKBALL_TIMEOUT) { 5617 if (DebugFlags.WEB_VIEW) { 5618 Log.v(LOGTAG, "onTrackballEvent time=" 5619 + time + " last=" + mTrackballLastTime); 5620 } 5621 mTrackballFirstTime = time; 5622 mTrackballXMove = mTrackballYMove = 0; 5623 } 5624 mTrackballLastTime = time; 5625 if (DebugFlags.WEB_VIEW) { 5626 Log.v(LOGTAG, "onTrackballEvent ev=" + ev + " time=" + time); 5627 } 5628 mTrackballRemainsX += ev.getX(); 5629 mTrackballRemainsY += ev.getY(); 5630 doTrackball(time, ev.getMetaState()); 5631 return true; 5632 } 5633 5634 void moveSelection(float xRate, float yRate) { 5635 if (mNativeClass == 0) 5636 return; 5637 int width = getViewWidth(); 5638 int height = getViewHeight(); 5639 mSelectX += xRate; 5640 mSelectY += yRate; 5641 int maxX = width + mScrollX; 5642 int maxY = height + mScrollY; 5643 mSelectX = Math.min(maxX, Math.max(mScrollX - SELECT_CURSOR_OFFSET 5644 , mSelectX)); 5645 mSelectY = Math.min(maxY, Math.max(mScrollY - SELECT_CURSOR_OFFSET 5646 , mSelectY)); 5647 if (DebugFlags.WEB_VIEW) { 5648 Log.v(LOGTAG, "moveSelection" 5649 + " mSelectX=" + mSelectX 5650 + " mSelectY=" + mSelectY 5651 + " mScrollX=" + mScrollX 5652 + " mScrollY=" + mScrollY 5653 + " xRate=" + xRate 5654 + " yRate=" + yRate 5655 ); 5656 } 5657 nativeMoveSelection(viewToContentX(mSelectX), viewToContentY(mSelectY)); 5658 int scrollX = mSelectX < mScrollX ? -SELECT_CURSOR_OFFSET 5659 : mSelectX > maxX - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET 5660 : 0; 5661 int scrollY = mSelectY < mScrollY ? -SELECT_CURSOR_OFFSET 5662 : mSelectY > maxY - SELECT_CURSOR_OFFSET ? SELECT_CURSOR_OFFSET 5663 : 0; 5664 pinScrollBy(scrollX, scrollY, true, 0); 5665 Rect select = new Rect(mSelectX, mSelectY, mSelectX + 1, mSelectY + 1); 5666 requestRectangleOnScreen(select); 5667 invalidate(); 5668 } 5669 5670 private int scaleTrackballX(float xRate, int width) { 5671 int xMove = (int) (xRate / TRACKBALL_SCALE * width); 5672 int nextXMove = xMove; 5673 if (xMove > 0) { 5674 if (xMove > mTrackballXMove) { 5675 xMove -= mTrackballXMove; 5676 } 5677 } else if (xMove < mTrackballXMove) { 5678 xMove -= mTrackballXMove; 5679 } 5680 mTrackballXMove = nextXMove; 5681 return xMove; 5682 } 5683 5684 private int scaleTrackballY(float yRate, int height) { 5685 int yMove = (int) (yRate / TRACKBALL_SCALE * height); 5686 int nextYMove = yMove; 5687 if (yMove > 0) { 5688 if (yMove > mTrackballYMove) { 5689 yMove -= mTrackballYMove; 5690 } 5691 } else if (yMove < mTrackballYMove) { 5692 yMove -= mTrackballYMove; 5693 } 5694 mTrackballYMove = nextYMove; 5695 return yMove; 5696 } 5697 5698 private int keyCodeToSoundsEffect(int keyCode) { 5699 switch(keyCode) { 5700 case KeyEvent.KEYCODE_DPAD_UP: 5701 return SoundEffectConstants.NAVIGATION_UP; 5702 case KeyEvent.KEYCODE_DPAD_RIGHT: 5703 return SoundEffectConstants.NAVIGATION_RIGHT; 5704 case KeyEvent.KEYCODE_DPAD_DOWN: 5705 return SoundEffectConstants.NAVIGATION_DOWN; 5706 case KeyEvent.KEYCODE_DPAD_LEFT: 5707 return SoundEffectConstants.NAVIGATION_LEFT; 5708 } 5709 throw new IllegalArgumentException("keyCode must be one of " + 5710 "{KEYCODE_DPAD_UP, KEYCODE_DPAD_RIGHT, KEYCODE_DPAD_DOWN, " + 5711 "KEYCODE_DPAD_LEFT}."); 5712 } 5713 5714 private void doTrackball(long time, int metaState) { 5715 int elapsed = (int) (mTrackballLastTime - mTrackballFirstTime); 5716 if (elapsed == 0) { 5717 elapsed = TRACKBALL_TIMEOUT; 5718 } 5719 float xRate = mTrackballRemainsX * 1000 / elapsed; 5720 float yRate = mTrackballRemainsY * 1000 / elapsed; 5721 int viewWidth = getViewWidth(); 5722 int viewHeight = getViewHeight(); 5723 if (mSelectingText) { 5724 if (!mDrawSelectionPointer) { 5725 // The last selection was made by touch, disabling drawing the 5726 // selection pointer. Allow the trackball to adjust the 5727 // position of the touch control. 5728 mSelectX = contentToViewX(nativeSelectionX()); 5729 mSelectY = contentToViewY(nativeSelectionY()); 5730 mDrawSelectionPointer = mExtendSelection = true; 5731 nativeSetExtendSelection(); 5732 } 5733 moveSelection(scaleTrackballX(xRate, viewWidth), 5734 scaleTrackballY(yRate, viewHeight)); 5735 mTrackballRemainsX = mTrackballRemainsY = 0; 5736 return; 5737 } 5738 float ax = Math.abs(xRate); 5739 float ay = Math.abs(yRate); 5740 float maxA = Math.max(ax, ay); 5741 if (DebugFlags.WEB_VIEW) { 5742 Log.v(LOGTAG, "doTrackball elapsed=" + elapsed 5743 + " xRate=" + xRate 5744 + " yRate=" + yRate 5745 + " mTrackballRemainsX=" + mTrackballRemainsX 5746 + " mTrackballRemainsY=" + mTrackballRemainsY); 5747 } 5748 int width = mContentWidth - viewWidth; 5749 int height = mContentHeight - viewHeight; 5750 if (width < 0) width = 0; 5751 if (height < 0) height = 0; 5752 ax = Math.abs(mTrackballRemainsX * TRACKBALL_MULTIPLIER); 5753 ay = Math.abs(mTrackballRemainsY * TRACKBALL_MULTIPLIER); 5754 maxA = Math.max(ax, ay); 5755 int count = Math.max(0, (int) maxA); 5756 int oldScrollX = mScrollX; 5757 int oldScrollY = mScrollY; 5758 if (count > 0) { 5759 int selectKeyCode = ax < ay ? mTrackballRemainsY < 0 ? 5760 KeyEvent.KEYCODE_DPAD_UP : KeyEvent.KEYCODE_DPAD_DOWN : 5761 mTrackballRemainsX < 0 ? KeyEvent.KEYCODE_DPAD_LEFT : 5762 KeyEvent.KEYCODE_DPAD_RIGHT; 5763 count = Math.min(count, TRACKBALL_MOVE_COUNT); 5764 if (DebugFlags.WEB_VIEW) { 5765 Log.v(LOGTAG, "doTrackball keyCode=" + selectKeyCode 5766 + " count=" + count 5767 + " mTrackballRemainsX=" + mTrackballRemainsX 5768 + " mTrackballRemainsY=" + mTrackballRemainsY); 5769 } 5770 if (mNativeClass != 0 && nativePageShouldHandleShiftAndArrows()) { 5771 for (int i = 0; i < count; i++) { 5772 letPageHandleNavKey(selectKeyCode, time, true, metaState); 5773 } 5774 letPageHandleNavKey(selectKeyCode, time, false, metaState); 5775 } else if (navHandledKey(selectKeyCode, count, false, time)) { 5776 playSoundEffect(keyCodeToSoundsEffect(selectKeyCode)); 5777 } 5778 mTrackballRemainsX = mTrackballRemainsY = 0; 5779 } 5780 if (count >= TRACKBALL_SCROLL_COUNT) { 5781 int xMove = scaleTrackballX(xRate, width); 5782 int yMove = scaleTrackballY(yRate, height); 5783 if (DebugFlags.WEB_VIEW) { 5784 Log.v(LOGTAG, "doTrackball pinScrollBy" 5785 + " count=" + count 5786 + " xMove=" + xMove + " yMove=" + yMove 5787 + " mScrollX-oldScrollX=" + (mScrollX-oldScrollX) 5788 + " mScrollY-oldScrollY=" + (mScrollY-oldScrollY) 5789 ); 5790 } 5791 if (Math.abs(mScrollX - oldScrollX) > Math.abs(xMove)) { 5792 xMove = 0; 5793 } 5794 if (Math.abs(mScrollY - oldScrollY) > Math.abs(yMove)) { 5795 yMove = 0; 5796 } 5797 if (xMove != 0 || yMove != 0) { 5798 pinScrollBy(xMove, yMove, true, 0); 5799 } 5800 mUserScroll = true; 5801 } 5802 } 5803 5804 private int computeMaxScrollX() { 5805 return Math.max(computeHorizontalScrollRange() - getViewWidth(), 0); 5806 } 5807 5808 private int computeMaxScrollY() { 5809 return Math.max(computeVerticalScrollRange() + getTitleHeight() 5810 - getViewHeightWithTitle(), 0); 5811 } 5812 5813 boolean updateScrollCoordinates(int x, int y) { 5814 int oldX = mScrollX; 5815 int oldY = mScrollY; 5816 mScrollX = x; 5817 mScrollY = y; 5818 if (oldX != mScrollX || oldY != mScrollY) { 5819 onScrollChanged(mScrollX, mScrollY, oldX, oldY); 5820 return true; 5821 } else { 5822 return false; 5823 } 5824 } 5825 5826 public void flingScroll(int vx, int vy) { 5827 mScroller.fling(mScrollX, mScrollY, vx, vy, 0, computeMaxScrollX(), 0, 5828 computeMaxScrollY()); 5829 invalidate(); 5830 } 5831 5832 private void doFling() { 5833 if (mVelocityTracker == null) { 5834 return; 5835 } 5836 int maxX = computeMaxScrollX(); 5837 int maxY = computeMaxScrollY(); 5838 5839 mVelocityTracker.computeCurrentVelocity(1000, mMaximumFling); 5840 int vx = (int) mVelocityTracker.getXVelocity(); 5841 int vy = (int) mVelocityTracker.getYVelocity(); 5842 5843 if (mSnapScrollMode != SNAP_NONE) { 5844 if ((mSnapScrollMode & SNAP_X) == SNAP_X) { 5845 vy = 0; 5846 } else { 5847 vx = 0; 5848 } 5849 } 5850 if (true /* EMG release: make our fling more like Maps' */) { 5851 // maps cuts their velocity in half 5852 vx = vx * 3 / 4; 5853 vy = vy * 3 / 4; 5854 } 5855 if ((maxX == 0 && vy == 0) || (maxY == 0 && vx == 0)) { 5856 WebViewCore.resumePriority(); 5857 WebViewCore.resumeUpdatePicture(mWebViewCore); 5858 return; 5859 } 5860 float currentVelocity = mScroller.getCurrVelocity(); 5861 float velocity = (float) Math.hypot(vx, vy); 5862 if (mLastVelocity > 0 && currentVelocity > 0 && velocity 5863 > mLastVelocity * MINIMUM_VELOCITY_RATIO_FOR_ACCELERATION) { 5864 float deltaR = (float) (Math.abs(Math.atan2(mLastVelY, mLastVelX) 5865 - Math.atan2(vy, vx))); 5866 final float circle = (float) (Math.PI) * 2.0f; 5867 if (deltaR > circle * 0.9f || deltaR < circle * 0.1f) { 5868 vx += currentVelocity * mLastVelX / mLastVelocity; 5869 vy += currentVelocity * mLastVelY / mLastVelocity; 5870 velocity = (float) Math.hypot(vx, vy); 5871 if (DebugFlags.WEB_VIEW) { 5872 Log.v(LOGTAG, "doFling vx= " + vx + " vy=" + vy); 5873 } 5874 } else if (DebugFlags.WEB_VIEW) { 5875 Log.v(LOGTAG, "doFling missed " + deltaR / circle); 5876 } 5877 } else if (DebugFlags.WEB_VIEW) { 5878 Log.v(LOGTAG, "doFling start last=" + mLastVelocity 5879 + " current=" + currentVelocity 5880 + " vx=" + vx + " vy=" + vy 5881 + " maxX=" + maxX + " maxY=" + maxY 5882 + " mScrollX=" + mScrollX + " mScrollY=" + mScrollY); 5883 } 5884 mLastVelX = vx; 5885 mLastVelY = vy; 5886 mLastVelocity = velocity; 5887 5888 mScroller.fling(mScrollX, mScrollY, -vx, -vy, 0, maxX, 0, maxY); 5889 final int time = mScroller.getDuration(); 5890 mPrivateHandler.sendEmptyMessageDelayed(RESUME_WEBCORE_PRIORITY, time); 5891 awakenScrollBars(time); 5892 invalidate(); 5893 } 5894 5895 /** 5896 * Returns a view containing zoom controls i.e. +/- buttons. The caller is 5897 * in charge of installing this view to the view hierarchy. This view will 5898 * become visible when the user starts scrolling via touch and fade away if 5899 * the user does not interact with it. 5900 * <p/> 5901 * API version 3 introduces a built-in zoom mechanism that is shown 5902 * automatically by the MapView. This is the preferred approach for 5903 * showing the zoom UI. 5904 * 5905 * @deprecated The built-in zoom mechanism is preferred, see 5906 * {@link WebSettings#setBuiltInZoomControls(boolean)}. 5907 */ 5908 @Deprecated 5909 public View getZoomControls() { 5910 if (!getSettings().supportZoom()) { 5911 Log.w(LOGTAG, "This WebView doesn't support zoom."); 5912 return null; 5913 } 5914 return mZoomManager.getExternalZoomPicker(); 5915 } 5916 5917 void dismissZoomControl() { 5918 mZoomManager.dismissZoomPicker(); 5919 } 5920 5921 float getDefaultZoomScale() { 5922 return mZoomManager.getDefaultScale(); 5923 } 5924 5925 /** 5926 * @return TRUE if the WebView can be zoomed in. 5927 */ 5928 public boolean canZoomIn() { 5929 return mZoomManager.canZoomIn(); 5930 } 5931 5932 /** 5933 * @return TRUE if the WebView can be zoomed out. 5934 */ 5935 public boolean canZoomOut() { 5936 return mZoomManager.canZoomOut(); 5937 } 5938 5939 /** 5940 * Perform zoom in in the webview 5941 * @return TRUE if zoom in succeeds. FALSE if no zoom changes. 5942 */ 5943 public boolean zoomIn() { 5944 return mZoomManager.zoomIn(); 5945 } 5946 5947 /** 5948 * Perform zoom out in the webview 5949 * @return TRUE if zoom out succeeds. FALSE if no zoom changes. 5950 */ 5951 public boolean zoomOut() { 5952 return mZoomManager.zoomOut(); 5953 } 5954 5955 private void updateSelection() { 5956 if (mNativeClass == 0) { 5957 return; 5958 } 5959 // mLastTouchX and mLastTouchY are the point in the current viewport 5960 int contentX = viewToContentX((int) mLastTouchX + mScrollX); 5961 int contentY = viewToContentY((int) mLastTouchY + mScrollY); 5962 Rect rect = new Rect(contentX - mNavSlop, contentY - mNavSlop, 5963 contentX + mNavSlop, contentY + mNavSlop); 5964 nativeSelectBestAt(rect); 5965 } 5966 5967 /** 5968 * Scroll the focused text field/area to match the WebTextView 5969 * @param xPercent New x position of the WebTextView from 0 to 1. 5970 * @param y New y position of the WebTextView in view coordinates 5971 */ 5972 /*package*/ void scrollFocusedTextInput(float xPercent, int y) { 5973 if (!inEditingMode() || mWebViewCore == null) { 5974 return; 5975 } 5976 mWebViewCore.sendMessage(EventHub.SCROLL_TEXT_INPUT, 5977 // Since this position is relative to the top of the text input 5978 // field, we do not need to take the title bar's height into 5979 // consideration. 5980 viewToContentDimension(y), 5981 new Float(xPercent)); 5982 } 5983 5984 /** 5985 * Set our starting point and time for a drag from the WebTextView. 5986 */ 5987 /*package*/ void initiateTextFieldDrag(float x, float y, long eventTime) { 5988 if (!inEditingMode()) { 5989 return; 5990 } 5991 mLastTouchX = x + (float) (mWebTextView.getLeft() - mScrollX); 5992 mLastTouchY = y + (float) (mWebTextView.getTop() - mScrollY); 5993 mLastTouchTime = eventTime; 5994 if (!mScroller.isFinished()) { 5995 abortAnimation(); 5996 mPrivateHandler.removeMessages(RESUME_WEBCORE_PRIORITY); 5997 } 5998 mSnapScrollMode = SNAP_NONE; 5999 mVelocityTracker = VelocityTracker.obtain(); 6000 mTouchMode = TOUCH_DRAG_START_MODE; 6001 } 6002 6003 /** 6004 * Given a motion event from the WebTextView, set its location to our 6005 * coordinates, and handle the event. 6006 */ 6007 /*package*/ boolean textFieldDrag(MotionEvent event) { 6008 if (!inEditingMode()) { 6009 return false; 6010 } 6011 mDragFromTextInput = true; 6012 event.offsetLocation((float) (mWebTextView.getLeft() - mScrollX), 6013 (float) (mWebTextView.getTop() - mScrollY)); 6014 boolean result = onTouchEvent(event); 6015 mDragFromTextInput = false; 6016 return result; 6017 } 6018 6019 /** 6020 * Due a touch up from a WebTextView. This will be handled by webkit to 6021 * change the selection. 6022 * @param event MotionEvent in the WebTextView's coordinates. 6023 */ 6024 /*package*/ void touchUpOnTextField(MotionEvent event) { 6025 if (!inEditingMode()) { 6026 return; 6027 } 6028 int x = viewToContentX((int) event.getX() + mWebTextView.getLeft()); 6029 int y = viewToContentY((int) event.getY() + mWebTextView.getTop()); 6030 nativeMotionUp(x, y, mNavSlop); 6031 } 6032 6033 /** 6034 * Called when pressing the center key or trackball on a textfield. 6035 */ 6036 /*package*/ void centerKeyPressOnTextField() { 6037 mWebViewCore.sendMessage(EventHub.CLICK, nativeCursorFramePointer(), 6038 nativeCursorNodePointer()); 6039 } 6040 6041 private void doShortPress() { 6042 if (mNativeClass == 0) { 6043 return; 6044 } 6045 if (mPreventDefault == PREVENT_DEFAULT_YES) { 6046 return; 6047 } 6048 mTouchMode = TOUCH_DONE_MODE; 6049 switchOutDrawHistory(); 6050 // mLastTouchX and mLastTouchY are the point in the current viewport 6051 int contentX = viewToContentX((int) mLastTouchX + mScrollX); 6052 int contentY = viewToContentY((int) mLastTouchY + mScrollY); 6053 if (getSettings().supportTouchOnly()) { 6054 removeTouchHighlight(false); 6055 WebViewCore.TouchUpData touchUpData = new WebViewCore.TouchUpData(); 6056 // use "0" as generation id to inform WebKit to use the same x/y as 6057 // it used when processing GET_TOUCH_HIGHLIGHT_RECTS 6058 touchUpData.mMoveGeneration = 0; 6059 mWebViewCore.sendMessage(EventHub.TOUCH_UP, touchUpData); 6060 } else if (nativePointInNavCache(contentX, contentY, mNavSlop)) { 6061 WebViewCore.MotionUpData motionUpData = new WebViewCore 6062 .MotionUpData(); 6063 motionUpData.mFrame = nativeCacheHitFramePointer(); 6064 motionUpData.mNode = nativeCacheHitNodePointer(); 6065 motionUpData.mBounds = nativeCacheHitNodeBounds(); 6066 motionUpData.mX = contentX; 6067 motionUpData.mY = contentY; 6068 mWebViewCore.sendMessageAtFrontOfQueue(EventHub.VALID_NODE_BOUNDS, 6069 motionUpData); 6070 } else { 6071 doMotionUp(contentX, contentY); 6072 } 6073 } 6074 6075 private void doMotionUp(int contentX, int contentY) { 6076 if (nativeMotionUp(contentX, contentY, mNavSlop) && mLogEvent) { 6077 EventLog.writeEvent(EventLogTags.BROWSER_SNAP_CENTER); 6078 } 6079 if (nativeHasCursorNode() && !nativeCursorIsTextInput()) { 6080 playSoundEffect(SoundEffectConstants.CLICK); 6081 } 6082 } 6083 6084 /* 6085 * Return true if the view (Plugin) is fully visible and maximized inside 6086 * the WebView. 6087 */ 6088 boolean isPluginFitOnScreen(ViewManager.ChildView view) { 6089 final int viewWidth = getViewWidth(); 6090 final int viewHeight = getViewHeightWithTitle(); 6091 float scale = Math.min((float) viewWidth / view.width, (float) viewHeight / view.height); 6092 scale = mZoomManager.computeScaleWithLimits(scale); 6093 return !mZoomManager.willScaleTriggerZoom(scale) 6094 && contentToViewX(view.x) >= mScrollX 6095 && contentToViewX(view.x + view.width) <= mScrollX + viewWidth 6096 && contentToViewY(view.y) >= mScrollY 6097 && contentToViewY(view.y + view.height) <= mScrollY + viewHeight; 6098 } 6099 6100 /* 6101 * Maximize and center the rectangle, specified in the document coordinate 6102 * space, inside the WebView. If the zoom doesn't need to be changed, do an 6103 * animated scroll to center it. If the zoom needs to be changed, find the 6104 * zoom center and do a smooth zoom transition. 6105 */ 6106 void centerFitRect(int docX, int docY, int docWidth, int docHeight) { 6107 int viewWidth = getViewWidth(); 6108 int viewHeight = getViewHeightWithTitle(); 6109 float scale = Math.min((float) viewWidth / docWidth, (float) viewHeight 6110 / docHeight); 6111 scale = mZoomManager.computeScaleWithLimits(scale); 6112 if (!mZoomManager.willScaleTriggerZoom(scale)) { 6113 pinScrollTo(contentToViewX(docX + docWidth / 2) - viewWidth / 2, 6114 contentToViewY(docY + docHeight / 2) - viewHeight / 2, 6115 true, 0); 6116 } else { 6117 float actualScale = mZoomManager.getScale(); 6118 float oldScreenX = docX * actualScale - mScrollX; 6119 float rectViewX = docX * scale; 6120 float rectViewWidth = docWidth * scale; 6121 float newMaxWidth = mContentWidth * scale; 6122 float newScreenX = (viewWidth - rectViewWidth) / 2; 6123 // pin the newX to the WebView 6124 if (newScreenX > rectViewX) { 6125 newScreenX = rectViewX; 6126 } else if (newScreenX > (newMaxWidth - rectViewX - rectViewWidth)) { 6127 newScreenX = viewWidth - (newMaxWidth - rectViewX); 6128 } 6129 float zoomCenterX = (oldScreenX * scale - newScreenX * actualScale) 6130 / (scale - actualScale); 6131 float oldScreenY = docY * actualScale + getTitleHeight() 6132 - mScrollY; 6133 float rectViewY = docY * scale + getTitleHeight(); 6134 float rectViewHeight = docHeight * scale; 6135 float newMaxHeight = mContentHeight * scale + getTitleHeight(); 6136 float newScreenY = (viewHeight - rectViewHeight) / 2; 6137 // pin the newY to the WebView 6138 if (newScreenY > rectViewY) { 6139 newScreenY = rectViewY; 6140 } else if (newScreenY > (newMaxHeight - rectViewY - rectViewHeight)) { 6141 newScreenY = viewHeight - (newMaxHeight - rectViewY); 6142 } 6143 float zoomCenterY = (oldScreenY * scale - newScreenY * actualScale) 6144 / (scale - actualScale); 6145 mZoomManager.setZoomCenter(zoomCenterX, zoomCenterY); 6146 mZoomManager.startZoomAnimation(scale, false); 6147 } 6148 } 6149 6150 // Called by JNI to handle a touch on a node representing an email address, 6151 // address, or phone number 6152 private void overrideLoading(String url) { 6153 mCallbackProxy.uiOverrideUrlLoading(url); 6154 } 6155 6156 @Override 6157 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 6158 // FIXME: If a subwindow is showing find, and the user touches the 6159 // background window, it can steal focus. 6160 if (mFindIsUp) return false; 6161 boolean result = false; 6162 if (inEditingMode()) { 6163 result = mWebTextView.requestFocus(direction, 6164 previouslyFocusedRect); 6165 } else { 6166 result = super.requestFocus(direction, previouslyFocusedRect); 6167 if (mWebViewCore.getSettings().getNeedInitialFocus()) { 6168 // For cases such as GMail, where we gain focus from a direction, 6169 // we want to move to the first available link. 6170 // FIXME: If there are no visible links, we may not want to 6171 int fakeKeyDirection = 0; 6172 switch(direction) { 6173 case View.FOCUS_UP: 6174 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_UP; 6175 break; 6176 case View.FOCUS_DOWN: 6177 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_DOWN; 6178 break; 6179 case View.FOCUS_LEFT: 6180 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_LEFT; 6181 break; 6182 case View.FOCUS_RIGHT: 6183 fakeKeyDirection = KeyEvent.KEYCODE_DPAD_RIGHT; 6184 break; 6185 default: 6186 return result; 6187 } 6188 if (mNativeClass != 0 && !nativeHasCursorNode()) { 6189 navHandledKey(fakeKeyDirection, 1, true, 0); 6190 } 6191 } 6192 } 6193 return result; 6194 } 6195 6196 @Override 6197 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 6198 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 6199 6200 int heightMode = MeasureSpec.getMode(heightMeasureSpec); 6201 int heightSize = MeasureSpec.getSize(heightMeasureSpec); 6202 int widthMode = MeasureSpec.getMode(widthMeasureSpec); 6203 int widthSize = MeasureSpec.getSize(widthMeasureSpec); 6204 6205 int measuredHeight = heightSize; 6206 int measuredWidth = widthSize; 6207 6208 // Grab the content size from WebViewCore. 6209 int contentHeight = contentToViewDimension(mContentHeight); 6210 int contentWidth = contentToViewDimension(mContentWidth); 6211 6212// Log.d(LOGTAG, "------- measure " + heightMode); 6213 6214 if (heightMode != MeasureSpec.EXACTLY) { 6215 mHeightCanMeasure = true; 6216 measuredHeight = contentHeight; 6217 if (heightMode == MeasureSpec.AT_MOST) { 6218 // If we are larger than the AT_MOST height, then our height can 6219 // no longer be measured and we should scroll internally. 6220 if (measuredHeight > heightSize) { 6221 measuredHeight = heightSize; 6222 mHeightCanMeasure = false; 6223 } 6224 } 6225 } else { 6226 mHeightCanMeasure = false; 6227 } 6228 if (mNativeClass != 0) { 6229 nativeSetHeightCanMeasure(mHeightCanMeasure); 6230 } 6231 // For the width, always use the given size unless unspecified. 6232 if (widthMode == MeasureSpec.UNSPECIFIED) { 6233 mWidthCanMeasure = true; 6234 measuredWidth = contentWidth; 6235 } else { 6236 mWidthCanMeasure = false; 6237 } 6238 6239 synchronized (this) { 6240 setMeasuredDimension(measuredWidth, measuredHeight); 6241 } 6242 } 6243 6244 @Override 6245 public boolean requestChildRectangleOnScreen(View child, 6246 Rect rect, 6247 boolean immediate) { 6248 // don't scroll while in zoom animation. When it is done, we will adjust 6249 // the necessary components (e.g., WebTextView if it is in editing mode) 6250 if (mZoomManager.isFixedLengthAnimationInProgress()) { 6251 return false; 6252 } 6253 6254 rect.offset(child.getLeft() - child.getScrollX(), 6255 child.getTop() - child.getScrollY()); 6256 6257 Rect content = new Rect(viewToContentX(mScrollX), 6258 viewToContentY(mScrollY), 6259 viewToContentX(mScrollX + getWidth() 6260 - getVerticalScrollbarWidth()), 6261 viewToContentY(mScrollY + getViewHeightWithTitle())); 6262 content = nativeSubtractLayers(content); 6263 int screenTop = contentToViewY(content.top); 6264 int screenBottom = contentToViewY(content.bottom); 6265 int height = screenBottom - screenTop; 6266 int scrollYDelta = 0; 6267 6268 if (rect.bottom > screenBottom) { 6269 int oneThirdOfScreenHeight = height / 3; 6270 if (rect.height() > 2 * oneThirdOfScreenHeight) { 6271 // If the rectangle is too tall to fit in the bottom two thirds 6272 // of the screen, place it at the top. 6273 scrollYDelta = rect.top - screenTop; 6274 } else { 6275 // If the rectangle will still fit on screen, we want its 6276 // top to be in the top third of the screen. 6277 scrollYDelta = rect.top - (screenTop + oneThirdOfScreenHeight); 6278 } 6279 } else if (rect.top < screenTop) { 6280 scrollYDelta = rect.top - screenTop; 6281 } 6282 6283 int screenLeft = contentToViewX(content.left); 6284 int screenRight = contentToViewX(content.right); 6285 int width = screenRight - screenLeft; 6286 int scrollXDelta = 0; 6287 6288 if (rect.right > screenRight && rect.left > screenLeft) { 6289 if (rect.width() > width) { 6290 scrollXDelta += (rect.left - screenLeft); 6291 } else { 6292 scrollXDelta += (rect.right - screenRight); 6293 } 6294 } else if (rect.left < screenLeft) { 6295 scrollXDelta -= (screenLeft - rect.left); 6296 } 6297 6298 if ((scrollYDelta | scrollXDelta) != 0) { 6299 return pinScrollBy(scrollXDelta, scrollYDelta, !immediate, 0); 6300 } 6301 6302 return false; 6303 } 6304 6305 /* package */ void replaceTextfieldText(int oldStart, int oldEnd, 6306 String replace, int newStart, int newEnd) { 6307 WebViewCore.ReplaceTextData arg = new WebViewCore.ReplaceTextData(); 6308 arg.mReplace = replace; 6309 arg.mNewStart = newStart; 6310 arg.mNewEnd = newEnd; 6311 mTextGeneration++; 6312 arg.mTextGeneration = mTextGeneration; 6313 mWebViewCore.sendMessage(EventHub.REPLACE_TEXT, oldStart, oldEnd, arg); 6314 } 6315 6316 /* package */ void passToJavaScript(String currentText, KeyEvent event) { 6317 WebViewCore.JSKeyData arg = new WebViewCore.JSKeyData(); 6318 arg.mEvent = event; 6319 arg.mCurrentText = currentText; 6320 // Increase our text generation number, and pass it to webcore thread 6321 mTextGeneration++; 6322 mWebViewCore.sendMessage(EventHub.PASS_TO_JS, mTextGeneration, 0, arg); 6323 // WebKit's document state is not saved until about to leave the page. 6324 // To make sure the host application, like Browser, has the up to date 6325 // document state when it goes to background, we force to save the 6326 // document state. 6327 mWebViewCore.removeMessages(EventHub.SAVE_DOCUMENT_STATE); 6328 mWebViewCore.sendMessageDelayed(EventHub.SAVE_DOCUMENT_STATE, 6329 cursorData(), 1000); 6330 } 6331 6332 /* package */ synchronized WebViewCore getWebViewCore() { 6333 return mWebViewCore; 6334 } 6335 6336 //------------------------------------------------------------------------- 6337 // Methods can be called from a separate thread, like WebViewCore 6338 // If it needs to call the View system, it has to send message. 6339 //------------------------------------------------------------------------- 6340 6341 /** 6342 * General handler to receive message coming from webkit thread 6343 */ 6344 class PrivateHandler extends Handler { 6345 @Override 6346 public void handleMessage(Message msg) { 6347 // exclude INVAL_RECT_MSG_ID since it is frequently output 6348 if (DebugFlags.WEB_VIEW && msg.what != INVAL_RECT_MSG_ID) { 6349 if (msg.what >= FIRST_PRIVATE_MSG_ID 6350 && msg.what <= LAST_PRIVATE_MSG_ID) { 6351 Log.v(LOGTAG, HandlerPrivateDebugString[msg.what 6352 - FIRST_PRIVATE_MSG_ID]); 6353 } else if (msg.what >= FIRST_PACKAGE_MSG_ID 6354 && msg.what <= LAST_PACKAGE_MSG_ID) { 6355 Log.v(LOGTAG, HandlerPackageDebugString[msg.what 6356 - FIRST_PACKAGE_MSG_ID]); 6357 } else { 6358 Log.v(LOGTAG, Integer.toString(msg.what)); 6359 } 6360 } 6361 if (mWebViewCore == null) { 6362 // after WebView's destroy() is called, skip handling messages. 6363 return; 6364 } 6365 switch (msg.what) { 6366 case REMEMBER_PASSWORD: { 6367 mDatabase.setUsernamePassword( 6368 msg.getData().getString("host"), 6369 msg.getData().getString("username"), 6370 msg.getData().getString("password")); 6371 ((Message) msg.obj).sendToTarget(); 6372 break; 6373 } 6374 case NEVER_REMEMBER_PASSWORD: { 6375 mDatabase.setUsernamePassword( 6376 msg.getData().getString("host"), null, null); 6377 ((Message) msg.obj).sendToTarget(); 6378 break; 6379 } 6380 case PREVENT_DEFAULT_TIMEOUT: { 6381 // if timeout happens, cancel it so that it won't block UI 6382 // to continue handling touch events 6383 if ((msg.arg1 == MotionEvent.ACTION_DOWN 6384 && mPreventDefault == PREVENT_DEFAULT_MAYBE_YES) 6385 || (msg.arg1 == MotionEvent.ACTION_MOVE 6386 && mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN)) { 6387 cancelWebCoreTouchEvent( 6388 viewToContentX((int) mLastTouchX + mScrollX), 6389 viewToContentY((int) mLastTouchY + mScrollY), 6390 true); 6391 } 6392 break; 6393 } 6394 case SWITCH_TO_SHORTPRESS: { 6395 if (mTouchMode == TOUCH_INIT_MODE) { 6396 if (!getSettings().supportTouchOnly() 6397 && mPreventDefault != PREVENT_DEFAULT_YES) { 6398 mTouchMode = TOUCH_SHORTPRESS_START_MODE; 6399 updateSelection(); 6400 } else { 6401 // set to TOUCH_SHORTPRESS_MODE so that it won't 6402 // trigger double tap any more 6403 mTouchMode = TOUCH_SHORTPRESS_MODE; 6404 } 6405 } else if (mTouchMode == TOUCH_DOUBLE_TAP_MODE) { 6406 mTouchMode = TOUCH_DONE_MODE; 6407 } 6408 break; 6409 } 6410 case SWITCH_TO_LONGPRESS: { 6411 if (getSettings().supportTouchOnly()) { 6412 removeTouchHighlight(false); 6413 } 6414 if (inFullScreenMode() || mDeferTouchProcess) { 6415 TouchEventData ted = new TouchEventData(); 6416 ted.mAction = WebViewCore.ACTION_LONGPRESS; 6417 ted.mPoints = new Point[1]; 6418 ted.mPoints[0] = new Point(viewToContentX((int) mLastTouchX + mScrollX), 6419 viewToContentY((int) mLastTouchY + mScrollY)); 6420 // metaState for long press is tricky. Should it be the 6421 // state when the press started or when the press was 6422 // released? Or some intermediary key state? For 6423 // simplicity for now, we don't set it. 6424 ted.mMetaState = 0; 6425 ted.mReprocess = mDeferTouchProcess; 6426 mWebViewCore.sendMessage(EventHub.TOUCH_EVENT, ted); 6427 } else if (mPreventDefault != PREVENT_DEFAULT_YES) { 6428 mTouchMode = TOUCH_DONE_MODE; 6429 performLongClick(); 6430 } 6431 break; 6432 } 6433 case RELEASE_SINGLE_TAP: { 6434 doShortPress(); 6435 break; 6436 } 6437 case SCROLL_BY_MSG_ID: 6438 setContentScrollBy(msg.arg1, msg.arg2, (Boolean) msg.obj); 6439 break; 6440 case SYNC_SCROLL_TO_MSG_ID: 6441 if (mUserScroll) { 6442 // if user has scrolled explicitly, don't sync the 6443 // scroll position any more 6444 mUserScroll = false; 6445 break; 6446 } 6447 setContentScrollTo(msg.arg1, msg.arg2); 6448 break; 6449 case SCROLL_TO_MSG_ID: 6450 if (setContentScrollTo(msg.arg1, msg.arg2)) { 6451 // if we can't scroll to the exact position due to pin, 6452 // send a message to WebCore to re-scroll when we get a 6453 // new picture 6454 mUserScroll = false; 6455 mWebViewCore.sendMessage(EventHub.SYNC_SCROLL, 6456 msg.arg1, msg.arg2); 6457 } 6458 break; 6459 case SPAWN_SCROLL_TO_MSG_ID: 6460 spawnContentScrollTo(msg.arg1, msg.arg2); 6461 break; 6462 case UPDATE_ZOOM_RANGE: { 6463 WebViewCore.ViewState viewState = (WebViewCore.ViewState) msg.obj; 6464 // mScrollX contains the new minPrefWidth 6465 mZoomManager.updateZoomRange(viewState, getViewWidth(), viewState.mScrollX); 6466 break; 6467 } 6468 case REPLACE_BASE_CONTENT: { 6469 nativeReplaceBaseContent(msg.arg1); 6470 break; 6471 } 6472 case NEW_PICTURE_MSG_ID: { 6473 // called for new content 6474 mUserScroll = false; 6475 final WebViewCore.DrawData draw = (WebViewCore.DrawData) msg.obj; 6476 setBaseLayer(draw.mBaseLayer, draw.mInvalRegion.getBounds()); 6477 final Point viewSize = draw.mViewSize; 6478 WebViewCore.ViewState viewState = draw.mViewState; 6479 boolean isPictureAfterFirstLayout = viewState != null; 6480 if (isPictureAfterFirstLayout) { 6481 // Reset the last sent data here since dealing with new page. 6482 mLastWidthSent = 0; 6483 mZoomManager.onFirstLayout(draw); 6484 if (!mDrawHistory) { 6485 setContentScrollTo(viewState.mScrollX, viewState.mScrollY); 6486 // As we are on a new page, remove the WebTextView. This 6487 // is necessary for page loads driven by webkit, and in 6488 // particular when the user was on a password field, so 6489 // the WebTextView was visible. 6490 clearTextEntry(); 6491 } 6492 } 6493 6494 // We update the layout (i.e. request a layout from the 6495 // view system) if the last view size that we sent to 6496 // WebCore matches the view size of the picture we just 6497 // received in the fixed dimension. 6498 final boolean updateLayout = viewSize.x == mLastWidthSent 6499 && viewSize.y == mLastHeightSent; 6500 recordNewContentSize(draw.mContentSize.x, 6501 draw.mContentSize.y, updateLayout); 6502 if (DebugFlags.WEB_VIEW) { 6503 Rect b = draw.mInvalRegion.getBounds(); 6504 Log.v(LOGTAG, "NEW_PICTURE_MSG_ID {" + 6505 b.left+","+b.top+","+b.right+","+b.bottom+"}"); 6506 } 6507 invalidateContentRect(draw.mInvalRegion.getBounds()); 6508 6509 if (mPictureListener != null) { 6510 mPictureListener.onNewPicture(WebView.this, capturePicture()); 6511 } 6512 6513 // update the zoom information based on the new picture 6514 mZoomManager.onNewPicture(draw); 6515 6516 if (draw.mFocusSizeChanged && inEditingMode()) { 6517 mFocusSizeChanged = true; 6518 } 6519 if (isPictureAfterFirstLayout) { 6520 mViewManager.postReadyToDrawAll(); 6521 } 6522 break; 6523 } 6524 case WEBCORE_INITIALIZED_MSG_ID: 6525 // nativeCreate sets mNativeClass to a non-zero value 6526 nativeCreate(msg.arg1); 6527 break; 6528 case UPDATE_TEXTFIELD_TEXT_MSG_ID: 6529 // Make sure that the textfield is currently focused 6530 // and representing the same node as the pointer. 6531 if (inEditingMode() && 6532 mWebTextView.isSameTextField(msg.arg1)) { 6533 if (msg.getData().getBoolean("password")) { 6534 Spannable text = (Spannable) mWebTextView.getText(); 6535 int start = Selection.getSelectionStart(text); 6536 int end = Selection.getSelectionEnd(text); 6537 mWebTextView.setInPassword(true); 6538 // Restore the selection, which may have been 6539 // ruined by setInPassword. 6540 Spannable pword = 6541 (Spannable) mWebTextView.getText(); 6542 Selection.setSelection(pword, start, end); 6543 // If the text entry has created more events, ignore 6544 // this one. 6545 } else if (msg.arg2 == mTextGeneration) { 6546 String text = (String) msg.obj; 6547 if (null == text) { 6548 text = ""; 6549 } 6550 mWebTextView.setTextAndKeepSelection(text); 6551 } 6552 } 6553 break; 6554 case REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID: 6555 displaySoftKeyboard(true); 6556 // fall through to UPDATE_TEXT_SELECTION_MSG_ID 6557 case UPDATE_TEXT_SELECTION_MSG_ID: 6558 updateTextSelectionFromMessage(msg.arg1, msg.arg2, 6559 (WebViewCore.TextSelectionData) msg.obj); 6560 break; 6561 case FORM_DID_BLUR: 6562 if (inEditingMode() 6563 && mWebTextView.isSameTextField(msg.arg1)) { 6564 hideSoftKeyboard(); 6565 } 6566 break; 6567 case RETURN_LABEL: 6568 if (inEditingMode() 6569 && mWebTextView.isSameTextField(msg.arg1)) { 6570 mWebTextView.setHint((String) msg.obj); 6571 InputMethodManager imm 6572 = InputMethodManager.peekInstance(); 6573 // The hint is propagated to the IME in 6574 // onCreateInputConnection. If the IME is already 6575 // active, restart it so that its hint text is updated. 6576 if (imm != null && imm.isActive(mWebTextView)) { 6577 imm.restartInput(mWebTextView); 6578 } 6579 } 6580 break; 6581 case UNHANDLED_NAV_KEY: 6582 navHandledKey(msg.arg1, 1, false, 0); 6583 break; 6584 case UPDATE_TEXT_ENTRY_MSG_ID: 6585 // this is sent after finishing resize in WebViewCore. Make 6586 // sure the text edit box is still on the screen. 6587 if (inEditingMode() && nativeCursorIsTextInput()) { 6588 mWebTextView.bringIntoView(); 6589 rebuildWebTextView(); 6590 } 6591 break; 6592 case CLEAR_TEXT_ENTRY: 6593 clearTextEntry(); 6594 break; 6595 case INVAL_RECT_MSG_ID: { 6596 Rect r = (Rect)msg.obj; 6597 if (r == null) { 6598 invalidate(); 6599 } else { 6600 // we need to scale r from content into view coords, 6601 // which viewInvalidate() does for us 6602 viewInvalidate(r.left, r.top, r.right, r.bottom); 6603 } 6604 break; 6605 } 6606 case REQUEST_FORM_DATA: 6607 AutoCompleteAdapter adapter = (AutoCompleteAdapter) msg.obj; 6608 if (mWebTextView.isSameTextField(msg.arg1)) { 6609 mWebTextView.setAdapterCustom(adapter); 6610 } 6611 break; 6612 case RESUME_WEBCORE_PRIORITY: 6613 WebViewCore.resumePriority(); 6614 WebViewCore.resumeUpdatePicture(mWebViewCore); 6615 break; 6616 6617 case LONG_PRESS_CENTER: 6618 // as this is shared by keydown and trackballdown, reset all 6619 // the states 6620 mGotCenterDown = false; 6621 mTrackballDown = false; 6622 performLongClick(); 6623 break; 6624 6625 case WEBCORE_NEED_TOUCH_EVENTS: 6626 mForwardTouchEvents = (msg.arg1 != 0); 6627 break; 6628 6629 case PREVENT_TOUCH_ID: 6630 if (inFullScreenMode()) { 6631 break; 6632 } 6633 if (msg.obj == null) { 6634 if (msg.arg1 == MotionEvent.ACTION_DOWN 6635 && mPreventDefault == PREVENT_DEFAULT_MAYBE_YES) { 6636 // if prevent default is called from WebCore, UI 6637 // will not handle the rest of the touch events any 6638 // more. 6639 mPreventDefault = msg.arg2 == 1 ? PREVENT_DEFAULT_YES 6640 : PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN; 6641 } else if (msg.arg1 == MotionEvent.ACTION_MOVE 6642 && mPreventDefault == PREVENT_DEFAULT_NO_FROM_TOUCH_DOWN) { 6643 // the return for the first ACTION_MOVE will decide 6644 // whether UI will handle touch or not. Currently no 6645 // support for alternating prevent default 6646 mPreventDefault = msg.arg2 == 1 ? PREVENT_DEFAULT_YES 6647 : PREVENT_DEFAULT_NO; 6648 } 6649 if (mPreventDefault == PREVENT_DEFAULT_YES) { 6650 mTouchHighlightRegion.setEmpty(); 6651 } 6652 } else if (msg.arg2 == 0) { 6653 // prevent default is not called in WebCore, so the 6654 // message needs to be reprocessed in UI 6655 TouchEventData ted = (TouchEventData) msg.obj; 6656 switch (ted.mAction) { 6657 case MotionEvent.ACTION_DOWN: 6658 mLastDeferTouchX = contentToViewX(ted.mPoints[0].x) 6659 - mScrollX; 6660 mLastDeferTouchY = contentToViewY(ted.mPoints[0].y) 6661 - mScrollY; 6662 mDeferTouchMode = TOUCH_INIT_MODE; 6663 break; 6664 case MotionEvent.ACTION_MOVE: { 6665 // no snapping in defer process 6666 int x = contentToViewX(ted.mPoints[0].x) - mScrollX; 6667 int y = contentToViewY(ted.mPoints[0].y) - mScrollY; 6668 if (mDeferTouchMode != TOUCH_DRAG_MODE) { 6669 mDeferTouchMode = TOUCH_DRAG_MODE; 6670 mLastDeferTouchX = x; 6671 mLastDeferTouchY = y; 6672 startDrag(); 6673 } 6674 int deltaX = pinLocX((int) (mScrollX 6675 + mLastDeferTouchX - x)) 6676 - mScrollX; 6677 int deltaY = pinLocY((int) (mScrollY 6678 + mLastDeferTouchY - y)) 6679 - mScrollY; 6680 doDrag(deltaX, deltaY); 6681 if (deltaX != 0) mLastDeferTouchX = x; 6682 if (deltaY != 0) mLastDeferTouchY = y; 6683 break; 6684 } 6685 case MotionEvent.ACTION_UP: 6686 case MotionEvent.ACTION_CANCEL: 6687 if (mDeferTouchMode == TOUCH_DRAG_MODE) { 6688 // no fling in defer process 6689 WebViewCore.resumePriority(); 6690 WebViewCore.resumeUpdatePicture(mWebViewCore); 6691 } 6692 mDeferTouchMode = TOUCH_DONE_MODE; 6693 break; 6694 case WebViewCore.ACTION_DOUBLETAP: 6695 // doDoubleTap() needs mLastTouchX/Y as anchor 6696 mLastTouchX = contentToViewX(ted.mPoints[0].x) - mScrollX; 6697 mLastTouchY = contentToViewY(ted.mPoints[0].y) - mScrollY; 6698 mZoomManager.handleDoubleTap(mLastTouchX, mLastTouchY); 6699 mDeferTouchMode = TOUCH_DONE_MODE; 6700 break; 6701 case WebViewCore.ACTION_LONGPRESS: 6702 HitTestResult hitTest = getHitTestResult(); 6703 if (hitTest != null && hitTest.mType 6704 != HitTestResult.UNKNOWN_TYPE) { 6705 performLongClick(); 6706 } 6707 mDeferTouchMode = TOUCH_DONE_MODE; 6708 break; 6709 } 6710 } 6711 break; 6712 6713 case REQUEST_KEYBOARD: 6714 if (msg.arg1 == 0) { 6715 hideSoftKeyboard(); 6716 } else { 6717 displaySoftKeyboard(false); 6718 } 6719 break; 6720 6721 case FIND_AGAIN: 6722 // Ignore if find has been dismissed. 6723 if (mFindIsUp && mFindCallback != null) { 6724 mFindCallback.findAll(); 6725 } 6726 break; 6727 6728 case DRAG_HELD_MOTIONLESS: 6729 mHeldMotionless = MOTIONLESS_TRUE; 6730 invalidate(); 6731 // fall through to keep scrollbars awake 6732 6733 case AWAKEN_SCROLL_BARS: 6734 if (mTouchMode == TOUCH_DRAG_MODE 6735 && mHeldMotionless == MOTIONLESS_TRUE) { 6736 awakenScrollBars(ViewConfiguration 6737 .getScrollDefaultDelay(), false); 6738 mPrivateHandler.sendMessageDelayed(mPrivateHandler 6739 .obtainMessage(AWAKEN_SCROLL_BARS), 6740 ViewConfiguration.getScrollDefaultDelay()); 6741 } 6742 break; 6743 6744 case DO_MOTION_UP: 6745 doMotionUp(msg.arg1, msg.arg2); 6746 break; 6747 6748 case SHOW_FULLSCREEN: { 6749 View view = (View) msg.obj; 6750 int npp = msg.arg1; 6751 6752 if (inFullScreenMode()) { 6753 Log.w(LOGTAG, "Should not have another full screen."); 6754 dismissFullScreenMode(); 6755 } 6756 mFullScreenHolder = new PluginFullScreenHolder(WebView.this, npp); 6757 mFullScreenHolder.setContentView(view); 6758 mFullScreenHolder.setCancelable(false); 6759 mFullScreenHolder.setCanceledOnTouchOutside(false); 6760 mFullScreenHolder.show(); 6761 6762 break; 6763 } 6764 case HIDE_FULLSCREEN: 6765 dismissFullScreenMode(); 6766 break; 6767 6768 case DOM_FOCUS_CHANGED: 6769 if (inEditingMode()) { 6770 nativeClearCursor(); 6771 rebuildWebTextView(); 6772 } 6773 break; 6774 6775 case SHOW_RECT_MSG_ID: { 6776 WebViewCore.ShowRectData data = (WebViewCore.ShowRectData) msg.obj; 6777 int x = mScrollX; 6778 int left = contentToViewX(data.mLeft); 6779 int width = contentToViewDimension(data.mWidth); 6780 int maxWidth = contentToViewDimension(data.mContentWidth); 6781 int viewWidth = getViewWidth(); 6782 if (width < viewWidth) { 6783 // center align 6784 x += left + width / 2 - mScrollX - viewWidth / 2; 6785 } else { 6786 x += (int) (left + data.mXPercentInDoc * width 6787 - mScrollX - data.mXPercentInView * viewWidth); 6788 } 6789 if (DebugFlags.WEB_VIEW) { 6790 Log.v(LOGTAG, "showRectMsg=(left=" + left + ",width=" + 6791 width + ",maxWidth=" + maxWidth + 6792 ",viewWidth=" + viewWidth + ",x=" 6793 + x + ",xPercentInDoc=" + data.mXPercentInDoc + 6794 ",xPercentInView=" + data.mXPercentInView+ ")"); 6795 } 6796 // use the passing content width to cap x as the current 6797 // mContentWidth may not be updated yet 6798 x = Math.max(0, 6799 (Math.min(maxWidth, x + viewWidth)) - viewWidth); 6800 int top = contentToViewY(data.mTop); 6801 int height = contentToViewDimension(data.mHeight); 6802 int maxHeight = contentToViewDimension(data.mContentHeight); 6803 int viewHeight = getViewHeight(); 6804 int y = (int) (top + data.mYPercentInDoc * height - 6805 data.mYPercentInView * viewHeight); 6806 if (DebugFlags.WEB_VIEW) { 6807 Log.v(LOGTAG, "showRectMsg=(top=" + top + ",height=" + 6808 height + ",maxHeight=" + maxHeight + 6809 ",viewHeight=" + viewHeight + ",y=" 6810 + y + ",yPercentInDoc=" + data.mYPercentInDoc + 6811 ",yPercentInView=" + data.mYPercentInView+ ")"); 6812 } 6813 // use the passing content height to cap y as the current 6814 // mContentHeight may not be updated yet 6815 y = Math.max(0, 6816 (Math.min(maxHeight, y + viewHeight) - viewHeight)); 6817 // We need to take into account the visible title height 6818 // when scrolling since y is an absolute view position. 6819 y = Math.max(0, y - getVisibleTitleHeight()); 6820 scrollTo(x, y); 6821 } 6822 break; 6823 6824 case CENTER_FIT_RECT: 6825 Rect r = (Rect)msg.obj; 6826 centerFitRect(r.left, r.top, r.width(), r.height()); 6827 break; 6828 6829 case SET_SCROLLBAR_MODES: 6830 mHorizontalScrollBarMode = msg.arg1; 6831 mVerticalScrollBarMode = msg.arg2; 6832 break; 6833 6834 case SELECTION_STRING_CHANGED: 6835 if (mAccessibilityInjector != null) { 6836 String selectionString = (String) msg.obj; 6837 mAccessibilityInjector.onSelectionStringChange(selectionString); 6838 } 6839 break; 6840 6841 case SET_TOUCH_HIGHLIGHT_RECTS: 6842 invalidate(mTouchHighlightRegion.getBounds()); 6843 mTouchHighlightRegion.setEmpty(); 6844 if (msg.obj != null) { 6845 ArrayList<Rect> rects = (ArrayList<Rect>) msg.obj; 6846 for (Rect rect : rects) { 6847 Rect viewRect = contentToViewRect(rect); 6848 // some sites, like stories in nytimes.com, set 6849 // mouse event handler in the top div. It is not 6850 // user friendly to highlight the div if it covers 6851 // more than half of the screen. 6852 if (viewRect.width() < getWidth() >> 1 6853 || viewRect.height() < getHeight() >> 1) { 6854 mTouchHighlightRegion.union(viewRect); 6855 invalidate(viewRect); 6856 } else { 6857 Log.w(LOGTAG, "Skip the huge selection rect:" 6858 + viewRect); 6859 } 6860 } 6861 } 6862 break; 6863 6864 case SAVE_WEBARCHIVE_FINISHED: 6865 SaveWebArchiveMessage saveMessage = (SaveWebArchiveMessage)msg.obj; 6866 if (saveMessage.mCallback != null) { 6867 saveMessage.mCallback.onReceiveValue(saveMessage.mResultFile); 6868 } 6869 break; 6870 6871 case SET_AUTOFILLABLE: 6872 mAutoFillData = (WebViewCore.AutoFillData) msg.obj; 6873 if (mWebTextView != null) { 6874 mWebTextView.setAutoFillable(mAutoFillData.getQueryId()); 6875 rebuildWebTextView(); 6876 } 6877 break; 6878 6879 default: 6880 super.handleMessage(msg); 6881 break; 6882 } 6883 } 6884 } 6885 6886 /** 6887 * Used when receiving messages for REQUEST_KEYBOARD_WITH_SELECTION_MSG_ID 6888 * and UPDATE_TEXT_SELECTION_MSG_ID. Update the selection of WebTextView. 6889 */ 6890 private void updateTextSelectionFromMessage(int nodePointer, 6891 int textGeneration, WebViewCore.TextSelectionData data) { 6892 if (inEditingMode() 6893 && mWebTextView.isSameTextField(nodePointer) 6894 && textGeneration == mTextGeneration) { 6895 mWebTextView.setSelectionFromWebKit(data.mStart, data.mEnd); 6896 } 6897 } 6898 6899 // Class used to use a dropdown for a <select> element 6900 private class InvokeListBox implements Runnable { 6901 // Whether the listbox allows multiple selection. 6902 private boolean mMultiple; 6903 // Passed in to a list with multiple selection to tell 6904 // which items are selected. 6905 private int[] mSelectedArray; 6906 // Passed in to a list with single selection to tell 6907 // where the initial selection is. 6908 private int mSelection; 6909 6910 private Container[] mContainers; 6911 6912 // Need these to provide stable ids to my ArrayAdapter, 6913 // which normally does not have stable ids. (Bug 1250098) 6914 private class Container extends Object { 6915 /** 6916 * Possible values for mEnabled. Keep in sync with OptionStatus in 6917 * WebViewCore.cpp 6918 */ 6919 final static int OPTGROUP = -1; 6920 final static int OPTION_DISABLED = 0; 6921 final static int OPTION_ENABLED = 1; 6922 6923 String mString; 6924 int mEnabled; 6925 int mId; 6926 6927 public String toString() { 6928 return mString; 6929 } 6930 } 6931 6932 /** 6933 * Subclass ArrayAdapter so we can disable OptionGroupLabels, 6934 * and allow filtering. 6935 */ 6936 private class MyArrayListAdapter extends ArrayAdapter<Container> { 6937 public MyArrayListAdapter(Context context, Container[] objects, boolean multiple) { 6938 super(context, 6939 multiple ? com.android.internal.R.layout.select_dialog_multichoice : 6940 com.android.internal.R.layout.select_dialog_singlechoice, 6941 objects); 6942 } 6943 6944 @Override 6945 public View getView(int position, View convertView, 6946 ViewGroup parent) { 6947 // Always pass in null so that we will get a new CheckedTextView 6948 // Otherwise, an item which was previously used as an <optgroup> 6949 // element (i.e. has no check), could get used as an <option> 6950 // element, which needs a checkbox/radio, but it would not have 6951 // one. 6952 convertView = super.getView(position, null, parent); 6953 Container c = item(position); 6954 if (c != null && Container.OPTION_ENABLED != c.mEnabled) { 6955 // ListView does not draw dividers between disabled and 6956 // enabled elements. Use a LinearLayout to provide dividers 6957 LinearLayout layout = new LinearLayout(mContext); 6958 layout.setOrientation(LinearLayout.VERTICAL); 6959 if (position > 0) { 6960 View dividerTop = new View(mContext); 6961 dividerTop.setBackgroundResource( 6962 android.R.drawable.divider_horizontal_bright); 6963 layout.addView(dividerTop); 6964 } 6965 6966 if (Container.OPTGROUP == c.mEnabled) { 6967 // Currently select_dialog_multichoice and 6968 // select_dialog_singlechoice are CheckedTextViews. If 6969 // that changes, the class cast will no longer be valid. 6970 Assert.assertTrue( 6971 convertView instanceof CheckedTextView); 6972 ((CheckedTextView) convertView).setCheckMarkDrawable( 6973 null); 6974 } else { 6975 // c.mEnabled == Container.OPTION_DISABLED 6976 // Draw the disabled element in a disabled state. 6977 convertView.setEnabled(false); 6978 } 6979 6980 layout.addView(convertView); 6981 if (position < getCount() - 1) { 6982 View dividerBottom = new View(mContext); 6983 dividerBottom.setBackgroundResource( 6984 android.R.drawable.divider_horizontal_bright); 6985 layout.addView(dividerBottom); 6986 } 6987 return layout; 6988 } 6989 return convertView; 6990 } 6991 6992 @Override 6993 public boolean hasStableIds() { 6994 // AdapterView's onChanged method uses this to determine whether 6995 // to restore the old state. Return false so that the old (out 6996 // of date) state does not replace the new, valid state. 6997 return false; 6998 } 6999 7000 private Container item(int position) { 7001 if (position < 0 || position >= getCount()) { 7002 return null; 7003 } 7004 return (Container) getItem(position); 7005 } 7006 7007 @Override 7008 public long getItemId(int position) { 7009 Container item = item(position); 7010 if (item == null) { 7011 return -1; 7012 } 7013 return item.mId; 7014 } 7015 7016 @Override 7017 public boolean areAllItemsEnabled() { 7018 return false; 7019 } 7020 7021 @Override 7022 public boolean isEnabled(int position) { 7023 Container item = item(position); 7024 if (item == null) { 7025 return false; 7026 } 7027 return Container.OPTION_ENABLED == item.mEnabled; 7028 } 7029 } 7030 7031 private InvokeListBox(String[] array, int[] enabled, int[] selected) { 7032 mMultiple = true; 7033 mSelectedArray = selected; 7034 7035 int length = array.length; 7036 mContainers = new Container[length]; 7037 for (int i = 0; i < length; i++) { 7038 mContainers[i] = new Container(); 7039 mContainers[i].mString = array[i]; 7040 mContainers[i].mEnabled = enabled[i]; 7041 mContainers[i].mId = i; 7042 } 7043 } 7044 7045 private InvokeListBox(String[] array, int[] enabled, int selection) { 7046 mSelection = selection; 7047 mMultiple = false; 7048 7049 int length = array.length; 7050 mContainers = new Container[length]; 7051 for (int i = 0; i < length; i++) { 7052 mContainers[i] = new Container(); 7053 mContainers[i].mString = array[i]; 7054 mContainers[i].mEnabled = enabled[i]; 7055 mContainers[i].mId = i; 7056 } 7057 } 7058 7059 /* 7060 * Whenever the data set changes due to filtering, this class ensures 7061 * that the checked item remains checked. 7062 */ 7063 private class SingleDataSetObserver extends DataSetObserver { 7064 private long mCheckedId; 7065 private ListView mListView; 7066 private Adapter mAdapter; 7067 7068 /* 7069 * Create a new observer. 7070 * @param id The ID of the item to keep checked. 7071 * @param l ListView for getting and clearing the checked states 7072 * @param a Adapter for getting the IDs 7073 */ 7074 public SingleDataSetObserver(long id, ListView l, Adapter a) { 7075 mCheckedId = id; 7076 mListView = l; 7077 mAdapter = a; 7078 } 7079 7080 public void onChanged() { 7081 // The filter may have changed which item is checked. Find the 7082 // item that the ListView thinks is checked. 7083 int position = mListView.getCheckedItemPosition(); 7084 long id = mAdapter.getItemId(position); 7085 if (mCheckedId != id) { 7086 // Clear the ListView's idea of the checked item, since 7087 // it is incorrect 7088 mListView.clearChoices(); 7089 // Search for mCheckedId. If it is in the filtered list, 7090 // mark it as checked 7091 int count = mAdapter.getCount(); 7092 for (int i = 0; i < count; i++) { 7093 if (mAdapter.getItemId(i) == mCheckedId) { 7094 mListView.setItemChecked(i, true); 7095 break; 7096 } 7097 } 7098 } 7099 } 7100 7101 public void onInvalidate() {} 7102 } 7103 7104 public void run() { 7105 final ListView listView = (ListView) LayoutInflater.from(mContext) 7106 .inflate(com.android.internal.R.layout.select_dialog, null); 7107 final MyArrayListAdapter adapter = new 7108 MyArrayListAdapter(mContext, mContainers, mMultiple); 7109 AlertDialog.Builder b = new AlertDialog.Builder(mContext) 7110 .setView(listView).setCancelable(true) 7111 .setInverseBackgroundForced(true); 7112 7113 if (mMultiple) { 7114 b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { 7115 public void onClick(DialogInterface dialog, int which) { 7116 mWebViewCore.sendMessage( 7117 EventHub.LISTBOX_CHOICES, 7118 adapter.getCount(), 0, 7119 listView.getCheckedItemPositions()); 7120 }}); 7121 b.setNegativeButton(android.R.string.cancel, 7122 new DialogInterface.OnClickListener() { 7123 public void onClick(DialogInterface dialog, int which) { 7124 mWebViewCore.sendMessage( 7125 EventHub.SINGLE_LISTBOX_CHOICE, -2, 0); 7126 }}); 7127 } 7128 mListBoxDialog = b.create(); 7129 listView.setAdapter(adapter); 7130 listView.setFocusableInTouchMode(true); 7131 // There is a bug (1250103) where the checks in a ListView with 7132 // multiple items selected are associated with the positions, not 7133 // the ids, so the items do not properly retain their checks when 7134 // filtered. Do not allow filtering on multiple lists until 7135 // that bug is fixed. 7136 7137 listView.setTextFilterEnabled(!mMultiple); 7138 if (mMultiple) { 7139 listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); 7140 int length = mSelectedArray.length; 7141 for (int i = 0; i < length; i++) { 7142 listView.setItemChecked(mSelectedArray[i], true); 7143 } 7144 } else { 7145 listView.setOnItemClickListener(new OnItemClickListener() { 7146 public void onItemClick(AdapterView parent, View v, 7147 int position, long id) { 7148 mWebViewCore.sendMessage( 7149 EventHub.SINGLE_LISTBOX_CHOICE, (int)id, 0); 7150 mListBoxDialog.dismiss(); 7151 mListBoxDialog = null; 7152 } 7153 }); 7154 if (mSelection != -1) { 7155 listView.setSelection(mSelection); 7156 listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 7157 listView.setItemChecked(mSelection, true); 7158 DataSetObserver observer = new SingleDataSetObserver( 7159 adapter.getItemId(mSelection), listView, adapter); 7160 adapter.registerDataSetObserver(observer); 7161 } 7162 } 7163 mListBoxDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { 7164 public void onCancel(DialogInterface dialog) { 7165 mWebViewCore.sendMessage( 7166 EventHub.SINGLE_LISTBOX_CHOICE, -2, 0); 7167 mListBoxDialog = null; 7168 } 7169 }); 7170 mListBoxDialog.show(); 7171 } 7172 } 7173 7174 /* 7175 * Request a dropdown menu for a listbox with multiple selection. 7176 * 7177 * @param array Labels for the listbox. 7178 * @param enabledArray State for each element in the list. See static 7179 * integers in Container class. 7180 * @param selectedArray Which positions are initally selected. 7181 */ 7182 void requestListBox(String[] array, int[] enabledArray, int[] 7183 selectedArray) { 7184 mPrivateHandler.post( 7185 new InvokeListBox(array, enabledArray, selectedArray)); 7186 } 7187 7188 /* 7189 * Request a dropdown menu for a listbox with single selection or a single 7190 * <select> element. 7191 * 7192 * @param array Labels for the listbox. 7193 * @param enabledArray State for each element in the list. See static 7194 * integers in Container class. 7195 * @param selection Which position is initally selected. 7196 */ 7197 void requestListBox(String[] array, int[] enabledArray, int selection) { 7198 mPrivateHandler.post( 7199 new InvokeListBox(array, enabledArray, selection)); 7200 } 7201 7202 // called by JNI 7203 private void sendMoveFocus(int frame, int node) { 7204 mWebViewCore.sendMessage(EventHub.SET_MOVE_FOCUS, 7205 new WebViewCore.CursorData(frame, node, 0, 0)); 7206 } 7207 7208 // called by JNI 7209 private void sendMoveMouse(int frame, int node, int x, int y) { 7210 mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE, 7211 new WebViewCore.CursorData(frame, node, x, y)); 7212 } 7213 7214 /* 7215 * Send a mouse move event to the webcore thread. 7216 * 7217 * @param removeFocus Pass true if the "mouse" cursor is now over a node 7218 * which wants key events, but it is not the focus. This 7219 * will make the visual appear as though nothing is in 7220 * focus. Remove the WebTextView, if present, and stop 7221 * drawing the blinking caret. 7222 * called by JNI 7223 */ 7224 private void sendMoveMouseIfLatest(boolean removeFocus) { 7225 if (removeFocus) { 7226 clearTextEntry(); 7227 } 7228 mWebViewCore.sendMessage(EventHub.SET_MOVE_MOUSE_IF_LATEST, 7229 cursorData()); 7230 } 7231 7232 // called by JNI 7233 private void sendMotionUp(int touchGeneration, 7234 int frame, int node, int x, int y) { 7235 WebViewCore.TouchUpData touchUpData = new WebViewCore.TouchUpData(); 7236 touchUpData.mMoveGeneration = touchGeneration; 7237 touchUpData.mFrame = frame; 7238 touchUpData.mNode = node; 7239 touchUpData.mX = x; 7240 touchUpData.mY = y; 7241 mWebViewCore.sendMessage(EventHub.TOUCH_UP, touchUpData); 7242 } 7243 7244 7245 private int getScaledMaxXScroll() { 7246 int width; 7247 if (mHeightCanMeasure == false) { 7248 width = getViewWidth() / 4; 7249 } else { 7250 Rect visRect = new Rect(); 7251 calcOurVisibleRect(visRect); 7252 width = visRect.width() / 2; 7253 } 7254 // FIXME the divisor should be retrieved from somewhere 7255 return viewToContentX(width); 7256 } 7257 7258 private int getScaledMaxYScroll() { 7259 int height; 7260 if (mHeightCanMeasure == false) { 7261 height = getViewHeight() / 4; 7262 } else { 7263 Rect visRect = new Rect(); 7264 calcOurVisibleRect(visRect); 7265 height = visRect.height() / 2; 7266 } 7267 // FIXME the divisor should be retrieved from somewhere 7268 // the closest thing today is hard-coded into ScrollView.java 7269 // (from ScrollView.java, line 363) int maxJump = height/2; 7270 return Math.round(height * mZoomManager.getInvScale()); 7271 } 7272 7273 /** 7274 * Called by JNI to invalidate view 7275 */ 7276 private void viewInvalidate() { 7277 invalidate(); 7278 } 7279 7280 /** 7281 * Pass the key directly to the page. This assumes that 7282 * nativePageShouldHandleShiftAndArrows() returned true. 7283 */ 7284 private void letPageHandleNavKey(int keyCode, long time, boolean down, int metaState) { 7285 int keyEventAction; 7286 int eventHubAction; 7287 if (down) { 7288 keyEventAction = KeyEvent.ACTION_DOWN; 7289 eventHubAction = EventHub.KEY_DOWN; 7290 playSoundEffect(keyCodeToSoundsEffect(keyCode)); 7291 } else { 7292 keyEventAction = KeyEvent.ACTION_UP; 7293 eventHubAction = EventHub.KEY_UP; 7294 } 7295 7296 KeyEvent event = new KeyEvent(time, time, keyEventAction, keyCode, 7297 1, (metaState & KeyEvent.META_SHIFT_ON) 7298 | (metaState & KeyEvent.META_ALT_ON) 7299 | (metaState & KeyEvent.META_SYM_ON) 7300 , KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0); 7301 mWebViewCore.sendMessage(eventHubAction, event); 7302 } 7303 7304 // return true if the key was handled 7305 private boolean navHandledKey(int keyCode, int count, boolean noScroll, 7306 long time) { 7307 if (mNativeClass == 0) { 7308 return false; 7309 } 7310 mLastCursorTime = time; 7311 mLastCursorBounds = nativeGetCursorRingBounds(); 7312 boolean keyHandled 7313 = nativeMoveCursor(keyCode, count, noScroll) == false; 7314 if (DebugFlags.WEB_VIEW) { 7315 Log.v(LOGTAG, "navHandledKey mLastCursorBounds=" + mLastCursorBounds 7316 + " mLastCursorTime=" + mLastCursorTime 7317 + " handled=" + keyHandled); 7318 } 7319 if (keyHandled == false || mHeightCanMeasure == false) { 7320 return keyHandled; 7321 } 7322 Rect contentCursorRingBounds = nativeGetCursorRingBounds(); 7323 if (contentCursorRingBounds.isEmpty()) return keyHandled; 7324 Rect viewCursorRingBounds = contentToViewRect(contentCursorRingBounds); 7325 Rect visRect = new Rect(); 7326 calcOurVisibleRect(visRect); 7327 Rect outset = new Rect(visRect); 7328 int maxXScroll = visRect.width() / 2; 7329 int maxYScroll = visRect.height() / 2; 7330 outset.inset(-maxXScroll, -maxYScroll); 7331 if (Rect.intersects(outset, viewCursorRingBounds) == false) { 7332 return keyHandled; 7333 } 7334 // FIXME: Necessary because ScrollView/ListView do not scroll left/right 7335 int maxH = Math.min(viewCursorRingBounds.right - visRect.right, 7336 maxXScroll); 7337 if (maxH > 0) { 7338 pinScrollBy(maxH, 0, true, 0); 7339 } else { 7340 maxH = Math.max(viewCursorRingBounds.left - visRect.left, 7341 -maxXScroll); 7342 if (maxH < 0) { 7343 pinScrollBy(maxH, 0, true, 0); 7344 } 7345 } 7346 if (mLastCursorBounds.isEmpty()) return keyHandled; 7347 if (mLastCursorBounds.equals(contentCursorRingBounds)) { 7348 return keyHandled; 7349 } 7350 if (DebugFlags.WEB_VIEW) { 7351 Log.v(LOGTAG, "navHandledKey contentCursorRingBounds=" 7352 + contentCursorRingBounds); 7353 } 7354 requestRectangleOnScreen(viewCursorRingBounds); 7355 mUserScroll = true; 7356 return keyHandled; 7357 } 7358 7359 /** 7360 * @return If the page should receive Shift and arrows. 7361 */ 7362 private boolean pageShouldHandleShiftAndArrows() { 7363 // TODO: Maybe the injected script should announce its presence in 7364 // the page meta-tag so the nativePageShouldHandleShiftAndArrows 7365 // will check that as one of the conditions it looks for 7366 return (nativePageShouldHandleShiftAndArrows() || mAccessibilityScriptInjected); 7367 } 7368 7369 /** 7370 * Set the background color. It's white by default. Pass 7371 * zero to make the view transparent. 7372 * @param color the ARGB color described by Color.java 7373 */ 7374 public void setBackgroundColor(int color) { 7375 mBackgroundColor = color; 7376 mWebViewCore.sendMessage(EventHub.SET_BACKGROUND_COLOR, color); 7377 } 7378 7379 public void debugDump() { 7380 nativeDebugDump(); 7381 mWebViewCore.sendMessage(EventHub.DUMP_NAVTREE); 7382 } 7383 7384 /** 7385 * Draw the HTML page into the specified canvas. This call ignores any 7386 * view-specific zoom, scroll offset, or other changes. It does not draw 7387 * any view-specific chrome, such as progress or URL bars. 7388 * 7389 * @hide only needs to be accessible to Browser and testing 7390 */ 7391 public void drawPage(Canvas canvas) { 7392 nativeDraw(canvas, 0, 0, false); 7393 } 7394 7395 /** 7396 * Set the time to wait between passing touches to WebCore. See also the 7397 * TOUCH_SENT_INTERVAL member for further discussion. 7398 * 7399 * @hide This is only used by the DRT test application. 7400 */ 7401 public void setTouchInterval(int interval) { 7402 mCurrentTouchInterval = interval; 7403 } 7404 7405 /** 7406 * Toggle whether multi touch events should be sent to webkit 7407 * no matter if UI wants to handle it first. 7408 * 7409 * @hide This is only used by the webkit layout test. 7410 */ 7411 public void setDeferMultiTouch(boolean value) { 7412 mDeferMultitouch = value; 7413 Log.v(LOGTAG, "set mDeferMultitouch to " + value); 7414 } 7415 7416 /** 7417 * Update our cache with updatedText. 7418 * @param updatedText The new text to put in our cache. 7419 */ 7420 /* package */ void updateCachedTextfield(String updatedText) { 7421 // Also place our generation number so that when we look at the cache 7422 // we recognize that it is up to date. 7423 nativeUpdateCachedTextfield(updatedText, mTextGeneration); 7424 } 7425 7426 /*package*/ void autoFillForm(int autoFillQueryId) { 7427 mWebViewCore.sendMessage(EventHub.AUTOFILL_FORM, autoFillQueryId, /* unused */0); 7428 } 7429 7430 private native int nativeCacheHitFramePointer(); 7431 private native Rect nativeCacheHitNodeBounds(); 7432 private native int nativeCacheHitNodePointer(); 7433 /* package */ native void nativeClearCursor(); 7434 private native void nativeCreate(int ptr); 7435 private native int nativeCursorFramePointer(); 7436 private native Rect nativeCursorNodeBounds(); 7437 private native int nativeCursorNodePointer(); 7438 /* package */ native boolean nativeCursorMatchesFocus(); 7439 private native boolean nativeCursorIntersects(Rect visibleRect); 7440 private native boolean nativeCursorIsAnchor(); 7441 private native boolean nativeCursorIsTextInput(); 7442 private native Point nativeCursorPosition(); 7443 private native String nativeCursorText(); 7444 /** 7445 * Returns true if the native cursor node says it wants to handle key events 7446 * (ala plugins). This can only be called if mNativeClass is non-zero! 7447 */ 7448 private native boolean nativeCursorWantsKeyEvents(); 7449 private native void nativeDebugDump(); 7450 private native void nativeDestroy(); 7451 7452 /** 7453 * Draw the picture set with a background color and extra. If 7454 * "splitIfNeeded" is true and the return value is not 0, the return value 7455 * MUST be passed to WebViewCore with SPLIT_PICTURE_SET message so that the 7456 * native allocation can be freed. 7457 */ 7458 private native int nativeDraw(Canvas canvas, int color, int extra, 7459 boolean splitIfNeeded); 7460 private native void nativeDumpDisplayTree(String urlOrNull); 7461 private native boolean nativeEvaluateLayersAnimations(); 7462 private native boolean nativeDrawGL(Rect rect, float scale, int extras); 7463 private native void nativeExtendSelection(int x, int y); 7464 private native int nativeFindAll(String findLower, String findUpper, 7465 boolean sameAsLastSearch); 7466 private native void nativeFindNext(boolean forward); 7467 /* package */ native int nativeFocusCandidateFramePointer(); 7468 /* package */ native boolean nativeFocusCandidateHasNextTextfield(); 7469 /* package */ native boolean nativeFocusCandidateIsPassword(); 7470 private native boolean nativeFocusCandidateIsRtlText(); 7471 private native boolean nativeFocusCandidateIsTextInput(); 7472 /* package */ native int nativeFocusCandidateMaxLength(); 7473 /* package */ native String nativeFocusCandidateName(); 7474 private native Rect nativeFocusCandidateNodeBounds(); 7475 /** 7476 * @return A Rect with left, top, right, bottom set to the corresponding 7477 * padding values in the focus candidate, if it is a textfield/textarea with 7478 * a style. Otherwise return null. This is not actually a rectangle; Rect 7479 * is being used to pass four integers. 7480 */ 7481 private native Rect nativeFocusCandidatePaddingRect(); 7482 /* package */ native int nativeFocusCandidatePointer(); 7483 private native String nativeFocusCandidateText(); 7484 /* package */ native float nativeFocusCandidateTextSize(); 7485 /** 7486 * Returns an integer corresponding to WebView.cpp::type. 7487 * See WebTextView.setType() 7488 */ 7489 private native int nativeFocusCandidateType(); 7490 private native boolean nativeFocusIsPlugin(); 7491 private native Rect nativeFocusNodeBounds(); 7492 /* package */ native int nativeFocusNodePointer(); 7493 private native Rect nativeGetCursorRingBounds(); 7494 private native String nativeGetSelection(); 7495 private native boolean nativeHasCursorNode(); 7496 private native boolean nativeHasFocusNode(); 7497 private native void nativeHideCursor(); 7498 private native boolean nativeHitSelection(int x, int y); 7499 private native String nativeImageURI(int x, int y); 7500 private native void nativeInstrumentReport(); 7501 /* package */ native boolean nativeMoveCursorToNextTextInput(); 7502 // return true if the page has been scrolled 7503 private native boolean nativeMotionUp(int x, int y, int slop); 7504 // returns false if it handled the key 7505 private native boolean nativeMoveCursor(int keyCode, int count, 7506 boolean noScroll); 7507 private native int nativeMoveGeneration(); 7508 private native void nativeMoveSelection(int x, int y); 7509 /** 7510 * @return true if the page should get the shift and arrow keys, rather 7511 * than select text/navigation. 7512 * 7513 * If the focus is a plugin, or if the focus and cursor match and are 7514 * a contentEditable element, then the page should handle these keys. 7515 */ 7516 private native boolean nativePageShouldHandleShiftAndArrows(); 7517 private native boolean nativePointInNavCache(int x, int y, int slop); 7518 // Like many other of our native methods, you must make sure that 7519 // mNativeClass is not null before calling this method. 7520 private native void nativeRecordButtons(boolean focused, 7521 boolean pressed, boolean invalidate); 7522 private native void nativeResetSelection(); 7523 private native void nativeSelectAll(); 7524 private native void nativeSelectBestAt(Rect rect); 7525 private native int nativeSelectionX(); 7526 private native int nativeSelectionY(); 7527 private native int nativeFindIndex(); 7528 private native void nativeSetExtendSelection(); 7529 private native void nativeSetFindIsEmpty(); 7530 private native void nativeSetFindIsUp(boolean isUp); 7531 private native void nativeSetHeightCanMeasure(boolean measure); 7532 private native void nativeSetBaseLayer(int layer, Rect invalRect); 7533 private native void nativeShowCursorTimed(); 7534 private native void nativeReplaceBaseContent(int content); 7535 private native void nativeCopyBaseContentToPicture(Picture pict); 7536 private native boolean nativeHasContent(); 7537 private native void nativeSetSelectionPointer(boolean set, 7538 float scale, int x, int y); 7539 private native boolean nativeStartSelection(int x, int y); 7540 private native Rect nativeSubtractLayers(Rect content); 7541 private native int nativeTextGeneration(); 7542 // Never call this version except by updateCachedTextfield(String) - 7543 // we always want to pass in our generation number. 7544 private native void nativeUpdateCachedTextfield(String updatedText, 7545 int generation); 7546 private native boolean nativeWordSelection(int x, int y); 7547 // return NO_LEFTEDGE means failure. 7548 static final int NO_LEFTEDGE = -1; 7549 native int nativeGetBlockLeftEdge(int x, int y, float scale); 7550 7551 // Returns a pointer to the scrollable LayerAndroid at the given point. 7552 private native int nativeScrollableLayer(int x, int y); 7553 private native boolean nativeScrollLayer(int layer, int dx, int dy); 7554} 7555