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