WebTextView.java revision aa86ac82bc296931d4de6715fa966be8d0f8af2f
1/* 2 * Copyright (C) 2007 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 com.android.internal.widget.EditableInputConnection; 20 21import android.content.Context; 22import android.graphics.Canvas; 23import android.graphics.Color; 24import android.graphics.ColorFilter; 25import android.graphics.Paint; 26import android.graphics.PixelFormat; 27import android.graphics.Rect; 28import android.graphics.drawable.Drawable; 29import android.os.Handler; 30import android.os.Message; 31import android.text.BoringLayout.Metrics; 32import android.text.DynamicLayout; 33import android.text.Editable; 34import android.text.InputFilter; 35import android.text.Layout; 36import android.text.Layout.Alignment; 37import android.text.Selection; 38import android.text.Spannable; 39import android.text.TextPaint; 40import android.text.TextUtils; 41import android.text.method.MovementMethod; 42import android.text.method.Touch; 43import android.util.Log; 44import android.util.TypedValue; 45import android.view.Gravity; 46import android.view.KeyCharacterMap; 47import android.view.KeyEvent; 48import android.view.MotionEvent; 49import android.view.View; 50import android.view.ViewConfiguration; 51import android.view.ViewGroup; 52import android.view.inputmethod.EditorInfo; 53import android.view.inputmethod.InputMethodManager; 54import android.view.inputmethod.InputConnection; 55import android.widget.AbsoluteLayout.LayoutParams; 56import android.widget.AdapterView; 57import android.widget.ArrayAdapter; 58import android.widget.AutoCompleteTextView; 59import android.widget.TextView; 60 61import java.util.ArrayList; 62 63import junit.framework.Assert; 64 65/** 66 * WebTextView is a specialized version of EditText used by WebView 67 * to overlay html textfields (and textareas) to use our standard 68 * text editing. 69 */ 70/* package */ class WebTextView extends AutoCompleteTextView { 71 72 static final String LOGTAG = "webtextview"; 73 74 private WebView mWebView; 75 private boolean mSingle; 76 private int mWidthSpec; 77 private int mHeightSpec; 78 private int mNodePointer; 79 // FIXME: This is a hack for blocking unmatched key ups, in particular 80 // on the enter key. The method for blocking unmatched key ups prevents 81 // the shift key from working properly. 82 private boolean mGotEnterDown; 83 private int mMaxLength; 84 // Keep track of the text before the change so we know whether we actually 85 // need to send down the DOM events. 86 private String mPreChange; 87 private Drawable mBackground; 88 // Variables for keeping track of the touch down, to send to the WebView 89 // when a drag starts 90 private float mDragStartX; 91 private float mDragStartY; 92 private long mDragStartTime; 93 private boolean mDragSent; 94 // True if the most recent drag event has caused either the TextView to 95 // scroll or the web page to scroll. Gets reset after a touch down. 96 private boolean mScrolled; 97 // Whether or not a selection change was generated from webkit. If it was, 98 // we do not need to pass the selection back to webkit. 99 private boolean mFromWebKit; 100 // Whether or not a selection change was generated from the WebTextView 101 // gaining focus. If it is, we do not want to pass it to webkit. This 102 // selection comes from the MovementMethod, but we behave differently. If 103 // WebTextView gained focus from a touch, webkit will determine the 104 // selection. 105 private boolean mFromFocusChange; 106 // Whether or not a selection change was generated from setInputType. We 107 // do not want to pass this change to webkit. 108 private boolean mFromSetInputType; 109 private boolean mGotTouchDown; 110 // Keep track of whether a long press has happened. Only meaningful after 111 // an ACTION_DOWN MotionEvent 112 private boolean mHasPerformedLongClick; 113 private boolean mInSetTextAndKeepSelection; 114 // Array to store the final character added in onTextChanged, so that its 115 // KeyEvents may be determined. 116 private char[] mCharacter = new char[1]; 117 // This is used to reset the length filter when on a textfield 118 // with no max length. 119 // FIXME: This can be replaced with TextView.NO_FILTERS if that 120 // is made public/protected. 121 private static final InputFilter[] NO_FILTERS = new InputFilter[0]; 122 // For keeping track of the fact that the delete key was pressed, so 123 // we can simply pass a delete key instead of calling deleteSelection. 124 private boolean mGotDelete; 125 private int mDelSelStart; 126 private int mDelSelEnd; 127 128 // Keep in sync with native constant in 129 // external/webkit/WebKit/android/WebCoreSupport/autofill/WebAutoFill.cpp 130 /* package */ static final int FORM_NOT_AUTOFILLABLE = -1; 131 132 private boolean mAutoFillable; // Is this textview part of an autofillable form? 133 private int mQueryId; 134 private boolean mAutoFillProfileIsSet; 135 136 // Types used with setType. Keep in sync with CachedInput.h 137 private static final int NORMAL_TEXT_FIELD = 0; 138 private static final int TEXT_AREA = 1; 139 private static final int PASSWORD = 2; 140 private static final int SEARCH = 3; 141 private static final int EMAIL = 4; 142 private static final int NUMBER = 5; 143 private static final int TELEPHONE = 6; 144 private static final int URL = 7; 145 146 private static final int AUTOFILL_FORM = 100; 147 private Handler mHandler; 148 149 /** 150 * Create a new WebTextView. 151 * @param context The Context for this WebTextView. 152 * @param webView The WebView that created this. 153 */ 154 /* package */ WebTextView(Context context, WebView webView, int autoFillQueryId) { 155 super(context, null, com.android.internal.R.attr.webTextViewStyle); 156 mWebView = webView; 157 mMaxLength = -1; 158 setAutoFillable(autoFillQueryId); 159 // Turn on subpixel text, and turn off kerning, so it better matches 160 // the text in webkit. 161 TextPaint paint = getPaint(); 162 int flags = paint.getFlags() & ~Paint.DEV_KERN_TEXT_FLAG 163 | Paint.SUBPIXEL_TEXT_FLAG | Paint.DITHER_FLAG; 164 paint.setFlags(flags); 165 166 // Set the text color to black, regardless of the theme. This ensures 167 // that other applications that use embedded WebViews will properly 168 // display the text in password textfields. 169 setTextColor(DebugFlags.DRAW_WEBTEXTVIEW ? Color.RED : Color.BLACK); 170 // This helps to align the text better with the text in the web page. 171 setIncludeFontPadding(false); 172 173 mHandler = new Handler() { 174 @Override 175 public void handleMessage(Message msg) { 176 switch (msg.what) { 177 case AUTOFILL_FORM: 178 mWebView.autoFillForm(mQueryId); 179 break; 180 } 181 } 182 }; 183 184 } 185 186 public void setAutoFillable(int queryId) { 187 mAutoFillable = mWebView.getSettings().getAutoFillEnabled() 188 && (queryId != FORM_NOT_AUTOFILLABLE); 189 mQueryId = queryId; 190 } 191 192 @Override 193 public boolean dispatchKeyEvent(KeyEvent event) { 194 if (event.isSystem()) { 195 return super.dispatchKeyEvent(event); 196 } 197 // Treat ACTION_DOWN and ACTION MULTIPLE the same 198 boolean down = event.getAction() != KeyEvent.ACTION_UP; 199 int keyCode = event.getKeyCode(); 200 201 boolean isArrowKey = false; 202 switch(keyCode) { 203 case KeyEvent.KEYCODE_DPAD_LEFT: 204 case KeyEvent.KEYCODE_DPAD_RIGHT: 205 case KeyEvent.KEYCODE_DPAD_UP: 206 case KeyEvent.KEYCODE_DPAD_DOWN: 207 if (!mWebView.nativeCursorMatchesFocus()) { 208 return down ? mWebView.onKeyDown(keyCode, event) : mWebView 209 .onKeyUp(keyCode, event); 210 211 } 212 isArrowKey = true; 213 break; 214 } 215 216 if (KeyEvent.KEYCODE_TAB == keyCode) { 217 if (down) { 218 onEditorAction(EditorInfo.IME_ACTION_NEXT); 219 } 220 return true; 221 } 222 Spannable text = (Spannable) getText(); 223 int oldStart = Selection.getSelectionStart(text); 224 int oldEnd = Selection.getSelectionEnd(text); 225 // Normally the delete key's dom events are sent via onTextChanged. 226 // However, if the cursor is at the beginning of the field, which 227 // includes the case where it has zero length, then the text is not 228 // changed, so send the events immediately. 229 if (KeyEvent.KEYCODE_DEL == keyCode) { 230 if (oldStart == 0 && oldEnd == 0) { 231 sendDomEvent(event); 232 return true; 233 } 234 if (down) { 235 mGotDelete = true; 236 mDelSelStart = oldStart; 237 mDelSelEnd = oldEnd; 238 } 239 } 240 241 if (mSingle && (KeyEvent.KEYCODE_ENTER == keyCode 242 || KeyEvent.KEYCODE_NUMPAD_ENTER == keyCode)) { 243 if (isPopupShowing()) { 244 return super.dispatchKeyEvent(event); 245 } 246 if (!down) { 247 // Hide the keyboard, since the user has just submitted this 248 // form. The submission happens thanks to the two calls 249 // to sendDomEvent. 250 InputMethodManager.getInstance(mContext) 251 .hideSoftInputFromWindow(getWindowToken(), 0); 252 sendDomEvent(new KeyEvent(KeyEvent.ACTION_DOWN, keyCode)); 253 sendDomEvent(event); 254 } 255 return super.dispatchKeyEvent(event); 256 } else if (KeyEvent.KEYCODE_DPAD_CENTER == keyCode) { 257 // Note that this handles center key and trackball. 258 if (isPopupShowing()) { 259 return super.dispatchKeyEvent(event); 260 } 261 if (!mWebView.nativeCursorMatchesFocus()) { 262 return down ? mWebView.onKeyDown(keyCode, event) : mWebView 263 .onKeyUp(keyCode, event); 264 } 265 // Center key should be passed to a potential onClick 266 if (!down) { 267 mWebView.centerKeyPressOnTextField(); 268 } 269 // Pass to super to handle longpress. 270 return super.dispatchKeyEvent(event); 271 } 272 273 // Ensure there is a layout so arrow keys are handled properly. 274 if (getLayout() == null) { 275 measure(mWidthSpec, mHeightSpec); 276 } 277 278 int oldLength = text.length(); 279 boolean maxedOut = mMaxLength != -1 && oldLength == mMaxLength; 280 // If we are at max length, and there is a selection rather than a 281 // cursor, we need to store the text to compare later, since the key 282 // may have changed the string. 283 String oldText; 284 if (maxedOut && oldEnd != oldStart) { 285 oldText = text.toString(); 286 } else { 287 oldText = ""; 288 } 289 if (super.dispatchKeyEvent(event)) { 290 // If the WebTextView handled the key it was either an alphanumeric 291 // key, a delete, or a movement within the text. All of those are 292 // ok to pass to javascript. 293 294 // UNLESS there is a max length determined by the html. In that 295 // case, if the string was already at the max length, an 296 // alphanumeric key will be erased by the LengthFilter, 297 // so do not pass down to javascript, and instead 298 // return true. If it is an arrow key or a delete key, we can go 299 // ahead and pass it down. 300 if (KeyEvent.KEYCODE_ENTER == keyCode 301 || KeyEvent.KEYCODE_NUMPAD_ENTER == keyCode) { 302 // For multi-line text boxes, newlines will 303 // trigger onTextChanged for key down (which will send both 304 // key up and key down) but not key up. 305 mGotEnterDown = true; 306 } 307 if (maxedOut && !isArrowKey && keyCode != KeyEvent.KEYCODE_DEL) { 308 if (oldEnd == oldStart) { 309 // Return true so the key gets dropped. 310 return true; 311 } else if (!oldText.equals(getText().toString())) { 312 // FIXME: This makes the text work properly, but it 313 // does not pass down the key event, so it may not 314 // work for a textfield that has the type of 315 // behavior of GoogleSuggest. That said, it is 316 // unlikely that a site would combine the two in 317 // one textfield. 318 Spannable span = (Spannable) getText(); 319 int newStart = Selection.getSelectionStart(span); 320 int newEnd = Selection.getSelectionEnd(span); 321 mWebView.replaceTextfieldText(0, oldLength, span.toString(), 322 newStart, newEnd); 323 return true; 324 } 325 } 326 /* FIXME: 327 * In theory, we would like to send the events for the arrow keys. 328 * However, the TextView can arbitrarily change the selection (i.e. 329 * long press followed by using the trackball). Therefore, we keep 330 * in sync with the TextView via onSelectionChanged. If we also 331 * send the DOM event, we lose the correct selection. 332 if (isArrowKey) { 333 // Arrow key does not change the text, but we still want to send 334 // the DOM events. 335 sendDomEvent(event); 336 } 337 */ 338 return true; 339 } 340 // Ignore the key up event for newlines. This prevents 341 // multiple newlines in the native textarea. 342 if (mGotEnterDown && !down) { 343 return true; 344 } 345 // if it is a navigation key, pass it to WebView 346 if (isArrowKey) { 347 // WebView check the trackballtime in onKeyDown to avoid calling 348 // native from both trackball and key handling. As this is called 349 // from WebTextView, we always want WebView to check with native. 350 // Reset trackballtime to ensure it. 351 mWebView.resetTrackballTime(); 352 return down ? mWebView.onKeyDown(keyCode, event) : mWebView 353 .onKeyUp(keyCode, event); 354 } 355 return false; 356 } 357 358 void ensureLayout() { 359 if (getLayout() == null) { 360 // Ensure we have a Layout 361 measure(mWidthSpec, mHeightSpec); 362 LayoutParams params = (LayoutParams) getLayoutParams(); 363 if (params != null) { 364 layout(params.x, params.y, params.x + params.width, 365 params.y + params.height); 366 } 367 } 368 } 369 370 /** 371 * Determine whether this WebTextView currently represents the node 372 * represented by ptr. 373 * @param ptr Pointer to a node to compare to. 374 * @return boolean Whether this WebTextView already represents the node 375 * pointed to by ptr. 376 */ 377 /* package */ boolean isSameTextField(int ptr) { 378 return ptr == mNodePointer; 379 } 380 381 /** 382 * Ensure that the underlying textfield is lined up with the WebTextView. 383 */ 384 private void lineUpScroll() { 385 Layout layout = getLayout(); 386 if (mWebView != null && layout != null) { 387 float maxScrollX = Touch.getMaxScrollX(this, layout, mScrollY); 388 if (DebugFlags.WEB_TEXT_VIEW) { 389 Log.v(LOGTAG, "onTouchEvent x=" + mScrollX + " y=" 390 + mScrollY + " maxX=" + maxScrollX); 391 } 392 mWebView.scrollFocusedTextInput(maxScrollX > 0 ? 393 mScrollX / maxScrollX : 0, mScrollY); 394 } 395 } 396 397 @Override 398 protected void makeNewLayout(int w, int hintWidth, Metrics boring, 399 Metrics hintBoring, int ellipsisWidth, boolean bringIntoView) { 400 // Necessary to get a Layout to work with, and to do the other work that 401 // makeNewLayout does. 402 super.makeNewLayout(w, hintWidth, boring, hintBoring, ellipsisWidth, 403 bringIntoView); 404 405 // For fields that do not draw, create a layout which is altered so that 406 // the text lines up. 407 if (DebugFlags.DRAW_WEBTEXTVIEW || willNotDraw()) { 408 float lineHeight = -1; 409 if (mWebView != null) { 410 float height = mWebView.nativeFocusCandidateLineHeight(); 411 if (height != -1) { 412 lineHeight = height * mWebView.getScale(); 413 } 414 } 415 CharSequence text = getText(); 416 // Copy from the existing Layout. 417 mLayout = new WebTextViewLayout(text, text, getPaint(), w, 418 mLayout.getAlignment(), mLayout.getSpacingMultiplier(), 419 mLayout.getSpacingAdd(), false, null, ellipsisWidth, 420 lineHeight); 421 } 422 } 423 424 /** 425 * Custom layout which figures out its line spacing. If -1 is passed in for 426 * the height, it will use the ascent and descent from the paint to 427 * determine the line spacing. Otherwise it will use the spacing provided. 428 */ 429 private static class WebTextViewLayout extends DynamicLayout { 430 private float mLineHeight; 431 private float mDifference; 432 public WebTextViewLayout(CharSequence base, CharSequence display, 433 TextPaint paint, 434 int width, Alignment align, 435 float spacingMult, float spacingAdd, 436 boolean includepad, 437 TextUtils.TruncateAt ellipsize, int ellipsizedWidth, 438 float lineHeight) { 439 super(base, display, paint, width, align, spacingMult, spacingAdd, 440 includepad, ellipsize, ellipsizedWidth); 441 float paintLineHeight = paint.descent() - paint.ascent(); 442 if (lineHeight == -1f) { 443 mLineHeight = paintLineHeight; 444 mDifference = 0f; 445 } else { 446 mLineHeight = lineHeight; 447 // Through trial and error, I found this calculation to improve 448 // the accuracy of line placement. 449 mDifference = (lineHeight - paintLineHeight) / 2; 450 } 451 } 452 453 @Override 454 public int getLineTop(int line) { 455 return Math.round(mLineHeight * line - mDifference); 456 } 457 } 458 459 @Override public InputConnection onCreateInputConnection( 460 EditorInfo outAttrs) { 461 InputConnection connection = super.onCreateInputConnection(outAttrs); 462 if (mWebView != null) { 463 // Use the name of the textfield + the url. Use backslash as an 464 // arbitrary separator. 465 outAttrs.fieldName = mWebView.nativeFocusCandidateName() + "\\" 466 + mWebView.getUrl(); 467 } 468 return connection; 469 } 470 471 /** 472 * In general, TextView makes a call to InputMethodManager.updateSelection 473 * in onDraw. However, in the general case of WebTextView, we do not draw. 474 * This method is called by WebView.onDraw to take care of the part that 475 * needs to be called. 476 */ 477 /* package */ void onDrawSubstitute() { 478 if (!willNotDraw()) { 479 // If the WebTextView is set to draw, such as in the case of a 480 // password, onDraw calls updateSelection(), so this code path is 481 // unnecessary. 482 return; 483 } 484 // This code is copied from TextView.onDraw(). That code does not get 485 // executed, however, because the WebTextView does not draw, allowing 486 // webkit's drawing to show through. 487 InputMethodManager imm = InputMethodManager.peekInstance(); 488 if (imm != null && imm.isActive(this)) { 489 Spannable sp = (Spannable) getText(); 490 int selStart = Selection.getSelectionStart(sp); 491 int selEnd = Selection.getSelectionEnd(sp); 492 int candStart = EditableInputConnection.getComposingSpanStart(sp); 493 int candEnd = EditableInputConnection.getComposingSpanEnd(sp); 494 imm.updateSelection(this, selStart, selEnd, candStart, candEnd); 495 } 496 updateCursorControllerPositions(); 497 } 498 499 @Override 500 protected void onDraw(Canvas canvas) { 501 // onDraw should only be called for password fields. If WebTextView is 502 // still drawing, but is no longer corresponding to a password field, 503 // remove it. 504 if (!DebugFlags.DRAW_WEBTEXTVIEW && (mWebView == null 505 || !mWebView.nativeFocusCandidateIsPassword() 506 || !isSameTextField(mWebView.nativeFocusCandidatePointer()))) { 507 // Although calling remove() would seem to make more sense here, 508 // changing it to not be a password field will make it not draw. 509 // Other code will make sure that it is removed completely, but this 510 // way the user will not see it. 511 setInPassword(false); 512 } else { 513 super.onDraw(canvas); 514 } 515 } 516 517 @Override 518 public void onEditorAction(int actionCode) { 519 switch (actionCode) { 520 case EditorInfo.IME_ACTION_NEXT: 521 if (mWebView.nativeMoveCursorToNextTextInput()) { 522 // Preemptively rebuild the WebTextView, so that the action will 523 // be set properly. 524 mWebView.rebuildWebTextView(); 525 setDefaultSelection(); 526 mWebView.invalidate(); 527 } 528 break; 529 case EditorInfo.IME_ACTION_DONE: 530 super.onEditorAction(actionCode); 531 break; 532 case EditorInfo.IME_ACTION_GO: 533 case EditorInfo.IME_ACTION_SEARCH: 534 // Send an enter and hide the soft keyboard 535 InputMethodManager.getInstance(mContext) 536 .hideSoftInputFromWindow(getWindowToken(), 0); 537 sendDomEvent(new KeyEvent(KeyEvent.ACTION_DOWN, 538 KeyEvent.KEYCODE_ENTER)); 539 sendDomEvent(new KeyEvent(KeyEvent.ACTION_UP, 540 KeyEvent.KEYCODE_ENTER)); 541 542 default: 543 break; 544 } 545 } 546 547 @Override 548 protected void onFocusChanged(boolean focused, int direction, 549 Rect previouslyFocusedRect) { 550 mFromFocusChange = true; 551 super.onFocusChanged(focused, direction, previouslyFocusedRect); 552 mFromFocusChange = false; 553 } 554 555 @Override 556 protected void onScrollChanged(int l, int t, int oldl, int oldt) { 557 super.onScrollChanged(l, t, oldl, oldt); 558 lineUpScroll(); 559 } 560 561 @Override 562 protected void onSelectionChanged(int selStart, int selEnd) { 563 if (!mFromWebKit && !mFromFocusChange && !mFromSetInputType 564 && mWebView != null && !mInSetTextAndKeepSelection) { 565 if (DebugFlags.WEB_TEXT_VIEW) { 566 Log.v(LOGTAG, "onSelectionChanged selStart=" + selStart 567 + " selEnd=" + selEnd); 568 } 569 mWebView.setSelection(selStart, selEnd); 570 lineUpScroll(); 571 } 572 } 573 574 @Override 575 protected void onTextChanged(CharSequence s,int start,int before,int count){ 576 super.onTextChanged(s, start, before, count); 577 String postChange = s.toString(); 578 // Prevent calls to setText from invoking onTextChanged (since this will 579 // mean we are on a different textfield). Also prevent the change when 580 // going from a textfield with a string of text to one with a smaller 581 // limit on text length from registering the onTextChanged event. 582 if (mPreChange == null || mPreChange.equals(postChange) || 583 (mMaxLength > -1 && mPreChange.length() > mMaxLength && 584 mPreChange.substring(0, mMaxLength).equals(postChange))) { 585 return; 586 } 587 mPreChange = postChange; 588 if (0 == count) { 589 if (before > 0) { 590 // For this and all changes to the text, update our cache 591 updateCachedTextfield(); 592 if (mGotDelete) { 593 mGotDelete = false; 594 int oldEnd = start + before; 595 if (mDelSelEnd == oldEnd 596 && (mDelSelStart == start 597 || (mDelSelStart == oldEnd && before == 1))) { 598 // If the selection is set up properly before the 599 // delete, send the DOM events. 600 sendDomEvent(new KeyEvent(KeyEvent.ACTION_DOWN, 601 KeyEvent.KEYCODE_DEL)); 602 sendDomEvent(new KeyEvent(KeyEvent.ACTION_UP, 603 KeyEvent.KEYCODE_DEL)); 604 return; 605 } 606 } 607 // This was simply a delete or a cut, so just delete the 608 // selection. 609 mWebView.deleteSelection(start, start + before); 610 } 611 mGotDelete = false; 612 // before should never be negative, so whether it was a cut 613 // (handled above), or before is 0, in which case nothing has 614 // changed, we should return. 615 return; 616 } 617 // Ensure that this flag gets cleared, since with autocorrect on, a 618 // delete key press may have a more complex result than deleting one 619 // character or the existing selection, so it will not get cleared 620 // above. 621 mGotDelete = false; 622 // Find the last character being replaced. If it can be represented by 623 // events, we will pass them to native (after replacing the beginning 624 // of the changed text), so we can see javascript events. 625 // Otherwise, replace the text being changed (including the last 626 // character) in the textfield. 627 TextUtils.getChars(s, start + count - 1, start + count, mCharacter, 0); 628 KeyCharacterMap kmap = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD); 629 KeyEvent[] events = kmap.getEvents(mCharacter); 630 boolean cannotUseKeyEvents = null == events; 631 int charactersFromKeyEvents = cannotUseKeyEvents ? 0 : 1; 632 if (count > 1 || cannotUseKeyEvents) { 633 String replace = s.subSequence(start, 634 start + count - charactersFromKeyEvents).toString(); 635 mWebView.replaceTextfieldText(start, start + before, replace, 636 start + count - charactersFromKeyEvents, 637 start + count - charactersFromKeyEvents); 638 } else { 639 // This corrects the selection which may have been affected by the 640 // trackball or auto-correct. 641 if (DebugFlags.WEB_TEXT_VIEW) { 642 Log.v(LOGTAG, "onTextChanged start=" + start 643 + " start + before=" + (start + before)); 644 } 645 if (!mInSetTextAndKeepSelection) { 646 mWebView.setSelection(start, start + before); 647 } 648 } 649 if (!cannotUseKeyEvents) { 650 int length = events.length; 651 for (int i = 0; i < length; i++) { 652 // We never send modifier keys to native code so don't send them 653 // here either. 654 if (!KeyEvent.isModifierKey(events[i].getKeyCode())) { 655 sendDomEvent(events[i]); 656 } 657 } 658 } 659 updateCachedTextfield(); 660 } 661 662 @Override 663 public boolean onTouchEvent(MotionEvent event) { 664 switch (event.getAction()) { 665 case MotionEvent.ACTION_DOWN: 666 super.onTouchEvent(event); 667 // This event may be the start of a drag, so store it to pass to the 668 // WebView if it is. 669 mDragStartX = event.getX(); 670 mDragStartY = event.getY(); 671 mDragStartTime = event.getEventTime(); 672 mDragSent = false; 673 mScrolled = false; 674 mGotTouchDown = true; 675 mHasPerformedLongClick = false; 676 break; 677 case MotionEvent.ACTION_MOVE: 678 if (mHasPerformedLongClick) { 679 mGotTouchDown = false; 680 return false; 681 } 682 int slop = ViewConfiguration.get(mContext).getScaledTouchSlop(); 683 Spannable buffer = getText(); 684 int initialScrollX = Touch.getInitialScrollX(this, buffer); 685 int initialScrollY = Touch.getInitialScrollY(this, buffer); 686 super.onTouchEvent(event); 687 int dx = Math.abs(mScrollX - initialScrollX); 688 int dy = Math.abs(mScrollY - initialScrollY); 689 // Use a smaller slop when checking to see if we've moved far enough 690 // to scroll the text, because experimentally, slop has shown to be 691 // to big for the case of a small textfield. 692 int smallerSlop = slop/2; 693 if (dx > smallerSlop || dy > smallerSlop) { 694 // Scrolling is handled in onScrollChanged. 695 mScrolled = true; 696 cancelLongPress(); 697 return true; 698 } 699 if (Math.abs((int) event.getX() - mDragStartX) < slop 700 && Math.abs((int) event.getY() - mDragStartY) < slop) { 701 // If the user has not scrolled further than slop, we should not 702 // send the drag. Instead, do nothing, and when the user lifts 703 // their finger, we will change the selection. 704 return true; 705 } 706 if (mWebView != null) { 707 // Only want to set the initial state once. 708 if (!mDragSent) { 709 mWebView.initiateTextFieldDrag(mDragStartX, mDragStartY, 710 mDragStartTime); 711 mDragSent = true; 712 } 713 boolean scrolled = mWebView.textFieldDrag(event); 714 if (scrolled) { 715 mScrolled = true; 716 cancelLongPress(); 717 return true; 718 } 719 } 720 return false; 721 case MotionEvent.ACTION_UP: 722 case MotionEvent.ACTION_CANCEL: 723 super.onTouchEvent(event); 724 if (mHasPerformedLongClick) { 725 mGotTouchDown = false; 726 return false; 727 } 728 if (!mScrolled) { 729 // If the page scrolled, or the TextView scrolled, we do not 730 // want to change the selection 731 cancelLongPress(); 732 if (mGotTouchDown && mWebView != null) { 733 mWebView.touchUpOnTextField(event); 734 } 735 } 736 // Necessary for the WebView to reset its state 737 if (mWebView != null && mDragSent) { 738 mWebView.onTouchEvent(event); 739 } 740 mGotTouchDown = false; 741 break; 742 default: 743 break; 744 } 745 return true; 746 } 747 748 @Override 749 public boolean onTrackballEvent(MotionEvent event) { 750 if (isPopupShowing()) { 751 return super.onTrackballEvent(event); 752 } 753 if (event.getAction() != MotionEvent.ACTION_MOVE) { 754 return false; 755 } 756 // If the Cursor is not on the text input, webview should handle the 757 // trackball 758 if (!mWebView.nativeCursorMatchesFocus()) { 759 return mWebView.onTrackballEvent(event); 760 } 761 Spannable text = (Spannable) getText(); 762 MovementMethod move = getMovementMethod(); 763 if (move != null && getLayout() != null && 764 move.onTrackballEvent(this, text, event)) { 765 // Selection is changed in onSelectionChanged 766 return true; 767 } 768 return false; 769 } 770 771 @Override 772 public boolean performLongClick() { 773 mHasPerformedLongClick = true; 774 return super.performLongClick(); 775 } 776 777 /** 778 * Remove this WebTextView from its host WebView, and return 779 * focus to the host. 780 */ 781 /* package */ void remove() { 782 // hide the soft keyboard when the edit text is out of focus 783 InputMethodManager imm = InputMethodManager.getInstance(mContext); 784 if (imm.isActive(this)) { 785 imm.hideSoftInputFromWindow(getWindowToken(), 0); 786 } 787 mWebView.removeView(this); 788 mWebView.requestFocus(); 789 } 790 791 /** 792 * Move the caret/selection into view. 793 */ 794 /* package */ void bringIntoView() { 795 bringPointIntoView(Selection.getSelectionEnd(getText())); 796 } 797 798 @Override 799 public boolean bringPointIntoView(int offset) { 800 if (mWebView == null) return false; 801 if (mWebView.nativeFocusCandidateIsPassword()) { 802 return getLayout() != null && super.bringPointIntoView(offset); 803 } 804 // For non password text input, tell webkit to move the caret/selection 805 // on screen, since webkit draws them. 806 mWebView.revealSelection(); 807 return true; 808 } 809 810 /** 811 * Send the DOM events for the specified event. 812 * @param event KeyEvent to be translated into a DOM event. 813 */ 814 private void sendDomEvent(KeyEvent event) { 815 mWebView.passToJavaScript(getText().toString(), event); 816 } 817 818 /** 819 * Always use this instead of setAdapter, as this has features specific to 820 * the WebTextView. 821 */ 822 public void setAdapterCustom(AutoCompleteAdapter adapter) { 823 if (adapter != null) { 824 setInputType(getInputType() 825 | EditorInfo.TYPE_TEXT_FLAG_AUTO_COMPLETE); 826 adapter.setTextView(this); 827 } 828 super.setAdapter(adapter); 829 if (mAutoFillable) { 830 setOnItemClickListener(new AdapterView.OnItemClickListener() { 831 @Override 832 public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 833 if (id == 0 && position == 0) { 834 // Blank out the text box while we wait for WebCore to fill the form. 835 replaceText(""); 836 WebSettings settings = mWebView.getSettings(); 837 if (mAutoFillProfileIsSet) { 838 // Call a webview method to tell WebCore to autofill the form. 839 mWebView.autoFillForm(mQueryId); 840 } else { 841 // There is no autofill profile setup yet and the user has 842 // elected to try and set one up. Call through to the 843 // embedder to action that. 844 mWebView.getWebChromeClient().setupAutoFill( 845 mHandler.obtainMessage(AUTOFILL_FORM)); 846 } 847 } 848 } 849 }); 850 } else { 851 setOnItemClickListener(null); 852 } 853 showDropDown(); 854 } 855 856 /** 857 * This is a special version of ArrayAdapter which changes its text size 858 * to match the text size of its host TextView. 859 */ 860 public static class AutoCompleteAdapter extends ArrayAdapter<String> { 861 private TextView mTextView; 862 863 public AutoCompleteAdapter(Context context, ArrayList<String> entries) { 864 super(context, com.android.internal.R.layout 865 .web_text_view_dropdown, entries); 866 } 867 868 /** 869 * {@inheritDoc} 870 */ 871 public View getView(int position, View convertView, ViewGroup parent) { 872 TextView tv = 873 (TextView) super.getView(position, convertView, parent); 874 if (tv != null && mTextView != null) { 875 tv.setTextSize(mTextView.getTextSize()); 876 } 877 return tv; 878 } 879 880 /** 881 * Set the TextView so we can match its text size. 882 */ 883 private void setTextView(TextView tv) { 884 mTextView = tv; 885 } 886 } 887 888 /** 889 * Sets the selection when the user clicks on a textfield or textarea with 890 * the trackball or center key, or starts typing into it without clicking on 891 * it. 892 */ 893 /* package */ void setDefaultSelection() { 894 Spannable text = (Spannable) getText(); 895 int selection = mSingle ? text.length() : 0; 896 if (Selection.getSelectionStart(text) == selection 897 && Selection.getSelectionEnd(text) == selection) { 898 // The selection of the UI copy is set correctly, but the 899 // WebTextView still needs to inform the webkit thread to set the 900 // selection. Normally that is done in onSelectionChanged, but 901 // onSelectionChanged will not be called because the UI copy is not 902 // changing. (This can happen when the WebTextView takes focus. 903 // That onSelectionChanged was blocked because the selection set 904 // when focusing is not necessarily the desirable selection for 905 // WebTextView.) 906 if (mWebView != null) { 907 mWebView.setSelection(selection, selection); 908 } 909 } else { 910 Selection.setSelection(text, selection, selection); 911 } 912 if (mWebView != null) mWebView.incrementTextGeneration(); 913 } 914 915 /** 916 * Determine whether to use the system-wide password disguising method, 917 * or to use none. 918 * @param inPassword True if the textfield is a password field. 919 */ 920 /* package */ void setInPassword(boolean inPassword) { 921 if (inPassword) { 922 setInputType(EditorInfo.TYPE_CLASS_TEXT | EditorInfo. 923 TYPE_TEXT_VARIATION_WEB_PASSWORD); 924 createBackground(); 925 } 926 // For password fields, draw the WebTextView. For others, just show 927 // webkit's drawing. 928 if (!DebugFlags.DRAW_WEBTEXTVIEW) { 929 setWillNotDraw(!inPassword); 930 } 931 setBackgroundDrawable(inPassword ? mBackground : null); 932 } 933 934 /** 935 * Private class used for the background of a password textfield. 936 */ 937 private static class OutlineDrawable extends Drawable { 938 private Paint mBackgroundPaint; 939 private Paint mOutlinePaint; 940 private float[] mLines; 941 public OutlineDrawable() { 942 mBackgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG); 943 mBackgroundPaint.setColor(Color.WHITE); 944 945 mOutlinePaint = new Paint(Paint.ANTI_ALIAS_FLAG); 946 mOutlinePaint.setColor(Color.BLACK); 947 mOutlinePaint.setStyle(Paint.Style.STROKE); 948 949 mLines = new float[16]; 950 } 951 @Override 952 public void setBounds(int left, int top, int right, int bottom) { 953 super.setBounds(left, top, right, bottom); 954 // Top line 955 mLines[0] = left; 956 mLines[1] = top + 1; 957 mLines[2] = right; 958 mLines[3] = top + 1; 959 // Right line 960 mLines[4] = right; 961 mLines[5] = top; 962 mLines[6] = right; 963 mLines[7] = bottom; 964 // Bottom line 965 mLines[8] = left; 966 mLines[9] = bottom; 967 mLines[10] = right; 968 mLines[11] = bottom; 969 // Left line 970 mLines[12] = left + 1; 971 mLines[13] = top; 972 mLines[14] = left + 1; 973 mLines[15] = bottom; 974 } 975 @Override 976 public void draw(Canvas canvas) { 977 // Draw the background. 978 canvas.drawRect(getBounds(), mBackgroundPaint); 979 // Draw the outline. 980 canvas.drawLines(mLines, mOutlinePaint); 981 } 982 // Always want it to be opaque. 983 @Override 984 public int getOpacity() { 985 return PixelFormat.OPAQUE; 986 } 987 // These are needed because they are abstract in Drawable. 988 @Override 989 public void setAlpha(int alpha) { } 990 @Override 991 public void setColorFilter(ColorFilter cf) { } 992 } 993 994 /** 995 * Create a background for the WebTextView and set up the paint for drawing 996 * the text. This way, we can see the password transformation of the 997 * system, which (optionally) shows the actual text before changing to dots. 998 * The background is necessary to hide the webkit-drawn text beneath. 999 */ 1000 private void createBackground() { 1001 if (mBackground != null) { 1002 return; 1003 } 1004 mBackground = new OutlineDrawable(); 1005 1006 setGravity(Gravity.CENTER_VERTICAL); 1007 } 1008 1009 @Override 1010 public void setInputType(int type) { 1011 mFromSetInputType = true; 1012 super.setInputType(type); 1013 mFromSetInputType = false; 1014 } 1015 1016 private void setMaxLength(int maxLength) { 1017 mMaxLength = maxLength; 1018 if (-1 == maxLength) { 1019 setFilters(NO_FILTERS); 1020 } else { 1021 setFilters(new InputFilter[] { 1022 new InputFilter.LengthFilter(maxLength) }); 1023 } 1024 } 1025 1026 /** 1027 * Set the pointer for this node so it can be determined which node this 1028 * WebTextView represents. 1029 * @param ptr Integer representing the pointer to the node which this 1030 * WebTextView represents. 1031 */ 1032 /* package */ void setNodePointer(int ptr) { 1033 mNodePointer = ptr; 1034 } 1035 1036 /** 1037 * Determine the position and size of WebTextView, and add it to the 1038 * WebView's view heirarchy. All parameters are presumed to be in 1039 * view coordinates. Also requests Focus and sets the cursor to not 1040 * request to be in view. 1041 * @param x x-position of the textfield. 1042 * @param y y-position of the textfield. 1043 * @param width width of the textfield. 1044 * @param height height of the textfield. 1045 */ 1046 /* package */ void setRect(int x, int y, int width, int height) { 1047 LayoutParams lp = (LayoutParams) getLayoutParams(); 1048 if (null == lp) { 1049 lp = new LayoutParams(width, height, x, y); 1050 } else { 1051 lp.x = x; 1052 lp.y = y; 1053 lp.width = width; 1054 lp.height = height; 1055 } 1056 if (getParent() == null) { 1057 mWebView.addView(this, lp); 1058 } else { 1059 setLayoutParams(lp); 1060 } 1061 // Set up a measure spec so a layout can always be recreated. 1062 mWidthSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY); 1063 mHeightSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY); 1064 } 1065 1066 /** 1067 * Set the selection, and disable our onSelectionChanged action. 1068 */ 1069 /* package */ void setSelectionFromWebKit(int start, int end) { 1070 if (start < 0 || end < 0) return; 1071 Spannable text = (Spannable) getText(); 1072 int length = text.length(); 1073 if (start > length || end > length) return; 1074 mFromWebKit = true; 1075 Selection.setSelection(text, start, end); 1076 mFromWebKit = false; 1077 } 1078 1079 /** 1080 * Update the text size according to the size of the focus candidate's text 1081 * size in mWebView. Should only be called from mWebView. 1082 */ 1083 /* package */ void updateTextSize() { 1084 Assert.assertNotNull("updateTextSize should only be called from " 1085 + "mWebView, so mWebView should never be null!", mWebView); 1086 // Note that this is approximately WebView.contentToViewDimension, 1087 // without being rounded. 1088 float size = mWebView.nativeFocusCandidateTextSize() 1089 * mWebView.getScale(); 1090 setTextSize(TypedValue.COMPLEX_UNIT_PX, size); 1091 } 1092 1093 /** 1094 * Set the text to the new string, but use the old selection, making sure 1095 * to keep it within the new string. 1096 * @param text The new text to place in the textfield. 1097 */ 1098 /* package */ void setTextAndKeepSelection(String text) { 1099 mPreChange = text.toString(); 1100 Editable edit = (Editable) getText(); 1101 int selStart = Selection.getSelectionStart(edit); 1102 int selEnd = Selection.getSelectionEnd(edit); 1103 mInSetTextAndKeepSelection = true; 1104 edit.replace(0, edit.length(), text); 1105 int newLength = edit.length(); 1106 if (selStart > newLength) selStart = newLength; 1107 if (selEnd > newLength) selEnd = newLength; 1108 Selection.setSelection(edit, selStart, selEnd); 1109 mInSetTextAndKeepSelection = false; 1110 updateCachedTextfield(); 1111 } 1112 1113 /** 1114 * Called by WebView.rebuildWebTextView(). Based on the type of the <input> 1115 * element, set up the WebTextView, its InputType, and IME Options properly. 1116 * @param type int corresponding to enum "Type" defined in CachedInput.h. 1117 * Does not correspond to HTMLInputElement::InputType so this 1118 * is unaffected if that changes, and also because that has no 1119 * type corresponding to textarea (which is its own tag). 1120 */ 1121 /* package */ void setType(int type) { 1122 if (mWebView == null) return; 1123 boolean single = true; 1124 boolean inPassword = false; 1125 int maxLength = -1; 1126 int inputType = EditorInfo.TYPE_CLASS_TEXT 1127 | EditorInfo.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT; 1128 int imeOptions = EditorInfo.IME_FLAG_NO_EXTRACT_UI 1129 | EditorInfo.IME_FLAG_NO_FULLSCREEN; 1130 if (TEXT_AREA != type 1131 && mWebView.nativeFocusCandidateHasNextTextfield()) { 1132 imeOptions |= EditorInfo.IME_FLAG_NAVIGATE_NEXT; 1133 } 1134 switch (type) { 1135 case NORMAL_TEXT_FIELD: 1136 imeOptions |= EditorInfo.IME_ACTION_GO; 1137 break; 1138 case TEXT_AREA: 1139 single = false; 1140 inputType |= EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE 1141 | EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES 1142 | EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT; 1143 imeOptions |= EditorInfo.IME_ACTION_NONE; 1144 break; 1145 case PASSWORD: 1146 inPassword = true; 1147 imeOptions |= EditorInfo.IME_ACTION_GO; 1148 break; 1149 case SEARCH: 1150 imeOptions |= EditorInfo.IME_ACTION_SEARCH; 1151 break; 1152 case EMAIL: 1153 inputType = EditorInfo.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS; 1154 imeOptions |= EditorInfo.IME_ACTION_GO; 1155 break; 1156 case NUMBER: 1157 inputType |= EditorInfo.TYPE_CLASS_NUMBER; 1158 // Number and telephone do not have both a Tab key and an 1159 // action, so set the action to NEXT 1160 imeOptions |= EditorInfo.IME_ACTION_NEXT; 1161 break; 1162 case TELEPHONE: 1163 inputType |= EditorInfo.TYPE_CLASS_PHONE; 1164 imeOptions |= EditorInfo.IME_ACTION_NEXT; 1165 break; 1166 case URL: 1167 // TYPE_TEXT_VARIATION_URI prevents Tab key from showing, so 1168 // exclude it for now. 1169 imeOptions |= EditorInfo.IME_ACTION_GO; 1170 break; 1171 default: 1172 imeOptions |= EditorInfo.IME_ACTION_GO; 1173 break; 1174 } 1175 setHint(null); 1176 if (single) { 1177 mWebView.requestLabel(mWebView.nativeFocusCandidateFramePointer(), 1178 mNodePointer); 1179 maxLength = mWebView.nativeFocusCandidateMaxLength(); 1180 if (type != PASSWORD) { 1181 String name = mWebView.nativeFocusCandidateName(); 1182 if (name != null && name.length() > 0) { 1183 mWebView.requestFormData(name, mNodePointer, mAutoFillable); 1184 } 1185 } 1186 } 1187 mSingle = single; 1188 setMaxLength(maxLength); 1189 setHorizontallyScrolling(single); 1190 setInputType(inputType); 1191 setImeOptions(imeOptions); 1192 setInPassword(inPassword); 1193 AutoCompleteAdapter adapter = null; 1194 setAdapterCustom(adapter); 1195 } 1196 1197 /** 1198 * Update the cache to reflect the current text. 1199 */ 1200 /* package */ void updateCachedTextfield() { 1201 mWebView.updateCachedTextfield(getText().toString()); 1202 } 1203 1204 /* package */ void setAutoFillProfileIsSet(boolean autoFillProfileIsSet) { 1205 mAutoFillProfileIsSet = autoFillProfileIsSet; 1206 } 1207} 1208