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