WebTextView.java revision 23cb86a47d566db413d9c7679984ef3cfdfee848
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 @Override public InputConnection onCreateInputConnection( 292 EditorInfo outAttrs) { 293 InputConnection connection = super.onCreateInputConnection(outAttrs); 294 if (mWebView != null) { 295 // Use the name of the textfield + the url. Use backslash as an 296 // arbitrary separator. 297 outAttrs.fieldName = mWebView.nativeFocusCandidateName() + "\\" 298 + mWebView.getUrl(); 299 } 300 return connection; 301 } 302 303 @Override 304 protected void onDraw(Canvas canvas) { 305 // onDraw should only be called for password fields. If WebTextView is 306 // still drawing, but is no longer corresponding to a password field, 307 // remove it. 308 if (mWebView == null || !mWebView.nativeFocusCandidateIsPassword() 309 || !isSameTextField(mWebView.nativeFocusCandidatePointer())) { 310 // Although calling remove() would seem to make more sense here, 311 // changing it to not be a password field will make it not draw. 312 // Other code will make sure that it is removed completely, but this 313 // way the user will not see it. 314 setInPassword(false); 315 } else { 316 super.onDraw(canvas); 317 } 318 } 319 320 @Override 321 public void onEditorAction(int actionCode) { 322 switch (actionCode) { 323 case EditorInfo.IME_ACTION_NEXT: 324 if (mWebView.nativeMoveCursorToNextTextInput()) { 325 // Since the cursor will no longer be in the same place as the 326 // focus, set the focus controller back to inactive 327 mWebView.setFocusControllerInactive(); 328 // Preemptively rebuild the WebTextView, so that the action will 329 // be set properly. 330 mWebView.rebuildWebTextView(); 331 setDefaultSelection(); 332 mWebView.invalidate(); 333 } 334 break; 335 case EditorInfo.IME_ACTION_DONE: 336 super.onEditorAction(actionCode); 337 break; 338 case EditorInfo.IME_ACTION_GO: 339 case EditorInfo.IME_ACTION_SEARCH: 340 // Send an enter and hide the soft keyboard 341 InputMethodManager.getInstance(mContext) 342 .hideSoftInputFromWindow(getWindowToken(), 0); 343 sendDomEvent(new KeyEvent(KeyEvent.ACTION_DOWN, 344 KeyEvent.KEYCODE_ENTER)); 345 sendDomEvent(new KeyEvent(KeyEvent.ACTION_UP, 346 KeyEvent.KEYCODE_ENTER)); 347 348 default: 349 break; 350 } 351 } 352 353 @Override 354 protected void onFocusChanged(boolean focused, int direction, 355 Rect previouslyFocusedRect) { 356 mFromFocusChange = true; 357 super.onFocusChanged(focused, direction, previouslyFocusedRect); 358 mFromFocusChange = false; 359 } 360 361 @Override 362 protected void onSelectionChanged(int selStart, int selEnd) { 363 if (mInSetTextAndKeepSelection) return; 364 // This code is copied from TextView.onDraw(). That code does not get 365 // executed, however, because the WebTextView does not draw, allowing 366 // webkit's drawing to show through. 367 InputMethodManager imm = InputMethodManager.peekInstance(); 368 if (imm != null && imm.isActive(this)) { 369 Spannable sp = (Spannable) getText(); 370 int candStart = EditableInputConnection.getComposingSpanStart(sp); 371 int candEnd = EditableInputConnection.getComposingSpanEnd(sp); 372 imm.updateSelection(this, selStart, selEnd, candStart, candEnd); 373 } 374 if (!mFromWebKit && !mFromFocusChange && !mFromSetInputType 375 && mWebView != null) { 376 if (DebugFlags.WEB_TEXT_VIEW) { 377 Log.v(LOGTAG, "onSelectionChanged selStart=" + selStart 378 + " selEnd=" + selEnd); 379 } 380 mWebView.setSelection(selStart, selEnd); 381 } 382 } 383 384 @Override 385 protected void onTextChanged(CharSequence s,int start,int before,int count){ 386 super.onTextChanged(s, start, before, count); 387 String postChange = s.toString(); 388 // Prevent calls to setText from invoking onTextChanged (since this will 389 // mean we are on a different textfield). Also prevent the change when 390 // going from a textfield with a string of text to one with a smaller 391 // limit on text length from registering the onTextChanged event. 392 if (mPreChange == null || mPreChange.equals(postChange) || 393 (mMaxLength > -1 && mPreChange.length() > mMaxLength && 394 mPreChange.substring(0, mMaxLength).equals(postChange))) { 395 return; 396 } 397 mPreChange = postChange; 398 if (0 == count) { 399 if (before > 0) { 400 // This was simply a delete or a cut, so just delete the 401 // selection. 402 mWebView.deleteSelection(start, start + before); 403 // For this and all changes to the text, update our cache 404 updateCachedTextfield(); 405 } 406 // before should never be negative, so whether it was a cut 407 // (handled above), or before is 0, in which case nothing has 408 // changed, we should return. 409 return; 410 } 411 // Find the last character being replaced. If it can be represented by 412 // events, we will pass them to native (after replacing the beginning 413 // of the changed text), so we can see javascript events. 414 // Otherwise, replace the text being changed (including the last 415 // character) in the textfield. 416 TextUtils.getChars(s, start + count - 1, start + count, mCharacter, 0); 417 KeyCharacterMap kmap = 418 KeyCharacterMap.load(KeyCharacterMap.BUILT_IN_KEYBOARD); 419 KeyEvent[] events = kmap.getEvents(mCharacter); 420 boolean cannotUseKeyEvents = null == events; 421 int charactersFromKeyEvents = cannotUseKeyEvents ? 0 : 1; 422 if (count > 1 || cannotUseKeyEvents) { 423 String replace = s.subSequence(start, 424 start + count - charactersFromKeyEvents).toString(); 425 mWebView.replaceTextfieldText(start, start + before, replace, 426 start + count - charactersFromKeyEvents, 427 start + count - charactersFromKeyEvents); 428 } else { 429 // This corrects the selection which may have been affected by the 430 // trackball or auto-correct. 431 if (DebugFlags.WEB_TEXT_VIEW) { 432 Log.v(LOGTAG, "onTextChanged start=" + start 433 + " start + before=" + (start + before)); 434 } 435 if (!mInSetTextAndKeepSelection) { 436 mWebView.setSelection(start, start + before); 437 } 438 } 439 if (!cannotUseKeyEvents) { 440 int length = events.length; 441 for (int i = 0; i < length; i++) { 442 // We never send modifier keys to native code so don't send them 443 // here either. 444 if (!KeyEvent.isModifierKey(events[i].getKeyCode())) { 445 sendDomEvent(events[i]); 446 } 447 } 448 } 449 updateCachedTextfield(); 450 } 451 452 @Override 453 public boolean onTouchEvent(MotionEvent event) { 454 switch (event.getAction()) { 455 case MotionEvent.ACTION_DOWN: 456 super.onTouchEvent(event); 457 // This event may be the start of a drag, so store it to pass to the 458 // WebView if it is. 459 mDragStartX = event.getX(); 460 mDragStartY = event.getY(); 461 mDragStartTime = event.getEventTime(); 462 mDragSent = false; 463 mScrolled = false; 464 mGotTouchDown = true; 465 mHasPerformedLongClick = false; 466 break; 467 case MotionEvent.ACTION_MOVE: 468 if (mHasPerformedLongClick) { 469 mGotTouchDown = false; 470 return false; 471 } 472 int slop = ViewConfiguration.get(mContext).getScaledTouchSlop(); 473 Spannable buffer = getText(); 474 int initialScrollX = Touch.getInitialScrollX(this, buffer); 475 int initialScrollY = Touch.getInitialScrollY(this, buffer); 476 super.onTouchEvent(event); 477 int dx = Math.abs(mScrollX - initialScrollX); 478 int dy = Math.abs(mScrollY - initialScrollY); 479 // Use a smaller slop when checking to see if we've moved far enough 480 // to scroll the text, because experimentally, slop has shown to be 481 // to big for the case of a small textfield. 482 int smallerSlop = slop/2; 483 if (dx > smallerSlop || dy > smallerSlop) { 484 if (mWebView != null) { 485 float maxScrollX = (float) Touch.getMaxScrollX(this, 486 getLayout(), mScrollY); 487 if (DebugFlags.WEB_TEXT_VIEW) { 488 Log.v(LOGTAG, "onTouchEvent x=" + mScrollX + " y=" 489 + mScrollY + " maxX=" + maxScrollX); 490 } 491 mWebView.scrollFocusedTextInput(maxScrollX > 0 ? 492 mScrollX / maxScrollX : 0, mScrollY); 493 } 494 mScrolled = true; 495 cancelLongPress(); 496 return true; 497 } 498 if (Math.abs((int) event.getX() - mDragStartX) < slop 499 && Math.abs((int) event.getY() - mDragStartY) < slop) { 500 // If the user has not scrolled further than slop, we should not 501 // send the drag. Instead, do nothing, and when the user lifts 502 // their finger, we will change the selection. 503 return true; 504 } 505 if (mWebView != null) { 506 // Only want to set the initial state once. 507 if (!mDragSent) { 508 mWebView.initiateTextFieldDrag(mDragStartX, mDragStartY, 509 mDragStartTime); 510 mDragSent = true; 511 } 512 boolean scrolled = mWebView.textFieldDrag(event); 513 if (scrolled) { 514 mScrolled = true; 515 cancelLongPress(); 516 return true; 517 } 518 } 519 return false; 520 case MotionEvent.ACTION_UP: 521 case MotionEvent.ACTION_CANCEL: 522 super.onTouchEvent(event); 523 if (mHasPerformedLongClick) { 524 mGotTouchDown = false; 525 return false; 526 } 527 if (!mScrolled) { 528 // If the page scrolled, or the TextView scrolled, we do not 529 // want to change the selection 530 cancelLongPress(); 531 if (mGotTouchDown && mWebView != null) { 532 mWebView.touchUpOnTextField(event); 533 } 534 } 535 // Necessary for the WebView to reset its state 536 if (mWebView != null && mDragSent) { 537 mWebView.onTouchEvent(event); 538 } 539 mGotTouchDown = false; 540 break; 541 default: 542 break; 543 } 544 return true; 545 } 546 547 @Override 548 public boolean onTrackballEvent(MotionEvent event) { 549 if (isPopupShowing()) { 550 return super.onTrackballEvent(event); 551 } 552 if (event.getAction() != MotionEvent.ACTION_MOVE) { 553 return false; 554 } 555 // If the Cursor is not on the text input, webview should handle the 556 // trackball 557 if (!mWebView.nativeCursorMatchesFocus()) { 558 return mWebView.onTrackballEvent(event); 559 } 560 Spannable text = (Spannable) getText(); 561 MovementMethod move = getMovementMethod(); 562 if (move != null && getLayout() != null && 563 move.onTrackballEvent(this, text, event)) { 564 // Selection is changed in onSelectionChanged 565 return true; 566 } 567 return false; 568 } 569 570 @Override 571 public boolean performLongClick() { 572 mHasPerformedLongClick = true; 573 return super.performLongClick(); 574 } 575 576 /** 577 * Remove this WebTextView from its host WebView, and return 578 * focus to the host. 579 */ 580 /* package */ void remove() { 581 // hide the soft keyboard when the edit text is out of focus 582 InputMethodManager.getInstance(mContext).hideSoftInputFromWindow( 583 getWindowToken(), 0); 584 mWebView.removeView(this); 585 mWebView.requestFocus(); 586 } 587 588 /* package */ void bringIntoView() { 589 if (getLayout() != null) { 590 bringPointIntoView(Selection.getSelectionEnd(getText())); 591 } 592 } 593 594 /** 595 * Send the DOM events for the specified event. 596 * @param event KeyEvent to be translated into a DOM event. 597 */ 598 private void sendDomEvent(KeyEvent event) { 599 mWebView.passToJavaScript(getText().toString(), event); 600 } 601 602 /** 603 * Always use this instead of setAdapter, as this has features specific to 604 * the WebTextView. 605 */ 606 public void setAdapterCustom(AutoCompleteAdapter adapter) { 607 if (adapter != null) { 608 setInputType(getInputType() 609 | EditorInfo.TYPE_TEXT_FLAG_AUTO_COMPLETE); 610 adapter.setTextView(this); 611 } 612 super.setAdapter(adapter); 613 } 614 615 /** 616 * This is a special version of ArrayAdapter which changes its text size 617 * to match the text size of its host TextView. 618 */ 619 public static class AutoCompleteAdapter extends ArrayAdapter<String> { 620 private TextView mTextView; 621 622 public AutoCompleteAdapter(Context context, ArrayList<String> entries) { 623 super(context, com.android.internal.R.layout 624 .search_dropdown_item_1line, entries); 625 } 626 627 /** 628 * {@inheritDoc} 629 */ 630 public View getView(int position, View convertView, ViewGroup parent) { 631 TextView tv = 632 (TextView) super.getView(position, convertView, parent); 633 if (tv != null && mTextView != null) { 634 tv.setTextSize(mTextView.getTextSize()); 635 } 636 return tv; 637 } 638 639 /** 640 * Set the TextView so we can match its text size. 641 */ 642 private void setTextView(TextView tv) { 643 mTextView = tv; 644 } 645 } 646 647 /** 648 * Sets the selection when the user clicks on a textfield or textarea with 649 * the trackball or center key, or starts typing into it without clicking on 650 * it. 651 */ 652 /* package */ void setDefaultSelection() { 653 Spannable text = (Spannable) getText(); 654 int selection = mSingle ? text.length() : 0; 655 if (Selection.getSelectionStart(text) == selection 656 && Selection.getSelectionEnd(text) == selection) { 657 // The selection of the UI copy is set correctly, but the 658 // WebTextView still needs to inform the webkit thread to set the 659 // selection. Normally that is done in onSelectionChanged, but 660 // onSelectionChanged will not be called because the UI copy is not 661 // changing. (This can happen when the WebTextView takes focus. 662 // That onSelectionChanged was blocked because the selection set 663 // when focusing is not necessarily the desirable selection for 664 // WebTextView.) 665 if (mWebView != null) { 666 mWebView.setSelection(selection, selection); 667 } 668 } else { 669 Selection.setSelection(text, selection, selection); 670 } 671 } 672 673 /** 674 * Determine whether to use the system-wide password disguising method, 675 * or to use none. 676 * @param inPassword True if the textfield is a password field. 677 */ 678 /* package */ void setInPassword(boolean inPassword) { 679 if (inPassword) { 680 setInputType(EditorInfo.TYPE_CLASS_TEXT | EditorInfo. 681 TYPE_TEXT_VARIATION_PASSWORD); 682 createBackground(); 683 } 684 // For password fields, draw the WebTextView. For others, just show 685 // webkit's drawing. 686 setWillNotDraw(!inPassword); 687 setBackgroundDrawable(inPassword ? mBackground : null); 688 } 689 690 /** 691 * Private class used for the background of a password textfield. 692 */ 693 private static class OutlineDrawable extends Drawable { 694 public void draw(Canvas canvas) { 695 Rect bounds = getBounds(); 696 Paint paint = new Paint(); 697 paint.setAntiAlias(true); 698 // Draw the background. 699 paint.setColor(Color.WHITE); 700 canvas.drawRect(bounds, paint); 701 // Draw the outline. 702 paint.setStyle(Paint.Style.STROKE); 703 paint.setColor(Color.BLACK); 704 canvas.drawRect(bounds, paint); 705 } 706 // Always want it to be opaque. 707 public int getOpacity() { 708 return PixelFormat.OPAQUE; 709 } 710 // These are needed because they are abstract in Drawable. 711 public void setAlpha(int alpha) { } 712 public void setColorFilter(ColorFilter cf) { } 713 } 714 715 /** 716 * Create a background for the WebTextView and set up the paint for drawing 717 * the text. This way, we can see the password transformation of the 718 * system, which (optionally) shows the actual text before changing to dots. 719 * The background is necessary to hide the webkit-drawn text beneath. 720 */ 721 private void createBackground() { 722 if (mBackground != null) { 723 return; 724 } 725 mBackground = new OutlineDrawable(); 726 727 setGravity(Gravity.CENTER_VERTICAL); 728 // Turn on subpixel text, and turn off kerning, so it better matches 729 // the text in webkit. 730 TextPaint paint = getPaint(); 731 int flags = paint.getFlags() | Paint.SUBPIXEL_TEXT_FLAG | 732 Paint.ANTI_ALIAS_FLAG & ~Paint.DEV_KERN_TEXT_FLAG; 733 paint.setFlags(flags); 734 // Set the text color to black, regardless of the theme. This ensures 735 // that other applications that use embedded WebViews will properly 736 // display the text in password textfields. 737 setTextColor(Color.BLACK); 738 } 739 740 @Override 741 public void setInputType(int type) { 742 mFromSetInputType = true; 743 super.setInputType(type); 744 mFromSetInputType = false; 745 } 746 747 private void setMaxLength(int maxLength) { 748 mMaxLength = maxLength; 749 if (-1 == maxLength) { 750 setFilters(NO_FILTERS); 751 } else { 752 setFilters(new InputFilter[] { 753 new InputFilter.LengthFilter(maxLength) }); 754 } 755 } 756 757 /** 758 * Set the pointer for this node so it can be determined which node this 759 * WebTextView represents. 760 * @param ptr Integer representing the pointer to the node which this 761 * WebTextView represents. 762 */ 763 /* package */ void setNodePointer(int ptr) { 764 mNodePointer = ptr; 765 } 766 767 /** 768 * Determine the position and size of WebTextView, and add it to the 769 * WebView's view heirarchy. All parameters are presumed to be in 770 * view coordinates. Also requests Focus and sets the cursor to not 771 * request to be in view. 772 * @param x x-position of the textfield. 773 * @param y y-position of the textfield. 774 * @param width width of the textfield. 775 * @param height height of the textfield. 776 */ 777 /* package */ void setRect(int x, int y, int width, int height) { 778 LayoutParams lp = (LayoutParams) getLayoutParams(); 779 if (null == lp) { 780 lp = new LayoutParams(width, height, x, y); 781 } else { 782 lp.x = x; 783 lp.y = y; 784 lp.width = width; 785 lp.height = height; 786 } 787 if (getParent() == null) { 788 mWebView.addView(this, lp); 789 } else { 790 setLayoutParams(lp); 791 } 792 // Set up a measure spec so a layout can always be recreated. 793 mWidthSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY); 794 mHeightSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY); 795 } 796 797 /** 798 * Set the selection, and disable our onSelectionChanged action. 799 */ 800 /* package */ void setSelectionFromWebKit(int start, int end) { 801 if (start < 0 || end < 0) return; 802 Spannable text = (Spannable) getText(); 803 int length = text.length(); 804 if (start > length || end > length) return; 805 mFromWebKit = true; 806 Selection.setSelection(text, start, end); 807 mFromWebKit = false; 808 } 809 810 /** 811 * Set the text to the new string, but use the old selection, making sure 812 * to keep it within the new string. 813 * @param text The new text to place in the textfield. 814 */ 815 /* package */ void setTextAndKeepSelection(String text) { 816 mPreChange = text.toString(); 817 Editable edit = (Editable) getText(); 818 int selStart = Selection.getSelectionStart(edit); 819 int selEnd = Selection.getSelectionEnd(edit); 820 mInSetTextAndKeepSelection = true; 821 edit.replace(0, edit.length(), text); 822 int newLength = edit.length(); 823 if (selStart > newLength) selStart = newLength; 824 if (selEnd > newLength) selEnd = newLength; 825 Selection.setSelection(edit, selStart, selEnd); 826 mInSetTextAndKeepSelection = false; 827 updateCachedTextfield(); 828 } 829 830 /** 831 * Called by WebView.rebuildWebTextView(). Based on the type of the <input> 832 * element, set up the WebTextView, its InputType, and IME Options properly. 833 * @param type int corresponding to enum "type" defined in WebView.cpp. 834 * Does not correspond to HTMLInputElement::InputType so this 835 * is unaffected if that changes, and also because that has no 836 * type corresponding to textarea (which is its own tag). 837 */ 838 /* package */ void setType(int type) { 839 if (mWebView == null) return; 840 boolean single = true; 841 boolean inPassword = false; 842 int maxLength = -1; 843 int inputType = EditorInfo.TYPE_CLASS_TEXT; 844 if (mWebView.nativeFocusCandidateHasNextTextfield()) { 845 inputType |= EditorInfo.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT; 846 } 847 int imeOptions = EditorInfo.IME_FLAG_NO_EXTRACT_UI 848 | EditorInfo.IME_FLAG_NO_FULLSCREEN; 849 switch (type) { 850 case 0: // NORMAL_TEXT_FIELD 851 imeOptions |= EditorInfo.IME_ACTION_GO; 852 break; 853 case 1: // TEXT_AREA 854 single = false; 855 inputType = EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE 856 | EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES 857 | EditorInfo.TYPE_CLASS_TEXT 858 | EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT; 859 imeOptions |= EditorInfo.IME_ACTION_NONE; 860 break; 861 case 2: // PASSWORD 862 inPassword = true; 863 imeOptions |= EditorInfo.IME_ACTION_GO; 864 break; 865 case 3: // SEARCH 866 imeOptions |= EditorInfo.IME_ACTION_SEARCH; 867 break; 868 case 4: // EMAIL 869 // TYPE_TEXT_VARIATION_WEB_EDIT_TEXT prevents EMAIL_ADDRESS 870 // from working, so exclude it for now. 871 imeOptions |= EditorInfo.IME_ACTION_GO; 872 break; 873 case 5: // NUMBER 874 inputType |= EditorInfo.TYPE_CLASS_NUMBER; 875 // Number and telephone do not have both a Tab key and an 876 // action, so set the action to NEXT 877 imeOptions |= EditorInfo.IME_ACTION_NEXT; 878 break; 879 case 6: // TELEPHONE 880 inputType |= EditorInfo.TYPE_CLASS_PHONE; 881 imeOptions |= EditorInfo.IME_ACTION_NEXT; 882 break; 883 case 7: // URL 884 // TYPE_TEXT_VARIATION_URI prevents Tab key from showing, so 885 // exclude it for now. 886 imeOptions |= EditorInfo.IME_ACTION_GO; 887 break; 888 default: 889 imeOptions |= EditorInfo.IME_ACTION_GO; 890 break; 891 } 892 setHint(null); 893 if (single) { 894 mWebView.requestLabel(mWebView.nativeFocusCandidateFramePointer(), 895 mNodePointer); 896 maxLength = mWebView.nativeFocusCandidateMaxLength(); 897 if (type != 2 /* PASSWORD */) { 898 String name = mWebView.nativeFocusCandidateName(); 899 if (name != null && name.length() > 0) { 900 mWebView.requestFormData(name, mNodePointer); 901 } 902 } 903 } 904 mSingle = single; 905 setMaxLength(maxLength); 906 setHorizontallyScrolling(single); 907 setInputType(inputType); 908 setImeOptions(imeOptions); 909 setInPassword(inPassword); 910 AutoCompleteAdapter adapter = null; 911 setAdapterCustom(adapter); 912 } 913 914 /** 915 * Update the cache to reflect the current text. 916 */ 917 /* package */ void updateCachedTextfield() { 918 mWebView.updateCachedTextfield(getText().toString()); 919 } 920 921 @Override 922 public boolean requestRectangleOnScreen(Rect rectangle) { 923 // don't scroll while in zoom animation. When it is done, we will adjust 924 // the WebTextView if it is in editing mode. 925 if (!mWebView.inAnimateZoom()) { 926 return super.requestRectangleOnScreen(rectangle); 927 } 928 return false; 929 } 930} 931