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