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