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