WebTextView.java revision b24e18b1c05ce62b5e6530305dd9980943d459b6
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 if (mWebView != null) mWebView.incrementTextGeneration(); 670 } 671 672 /** 673 * Determine whether to use the system-wide password disguising method, 674 * or to use none. 675 * @param inPassword True if the textfield is a password field. 676 */ 677 /* package */ void setInPassword(boolean inPassword) { 678 if (inPassword) { 679 setInputType(EditorInfo.TYPE_CLASS_TEXT | EditorInfo. 680 TYPE_TEXT_VARIATION_PASSWORD); 681 createBackground(); 682 } 683 // For password fields, draw the WebTextView. For others, just show 684 // webkit's drawing. 685 setWillNotDraw(!inPassword); 686 setBackgroundDrawable(inPassword ? mBackground : null); 687 // For non-password fields, avoid the invals from TextView's blinking 688 // cursor 689 setCursorVisible(inPassword); 690 } 691 692 /** 693 * Private class used for the background of a password textfield. 694 */ 695 private static class OutlineDrawable extends Drawable { 696 public void draw(Canvas canvas) { 697 Rect bounds = getBounds(); 698 Paint paint = new Paint(); 699 paint.setAntiAlias(true); 700 // Draw the background. 701 paint.setColor(Color.WHITE); 702 canvas.drawRect(bounds, paint); 703 // Draw the outline. 704 paint.setStyle(Paint.Style.STROKE); 705 paint.setColor(Color.BLACK); 706 canvas.drawRect(bounds, paint); 707 } 708 // Always want it to be opaque. 709 public int getOpacity() { 710 return PixelFormat.OPAQUE; 711 } 712 // These are needed because they are abstract in Drawable. 713 public void setAlpha(int alpha) { } 714 public void setColorFilter(ColorFilter cf) { } 715 } 716 717 /** 718 * Create a background for the WebTextView and set up the paint for drawing 719 * the text. This way, we can see the password transformation of the 720 * system, which (optionally) shows the actual text before changing to dots. 721 * The background is necessary to hide the webkit-drawn text beneath. 722 */ 723 private void createBackground() { 724 if (mBackground != null) { 725 return; 726 } 727 mBackground = new OutlineDrawable(); 728 729 setGravity(Gravity.CENTER_VERTICAL); 730 // Turn on subpixel text, and turn off kerning, so it better matches 731 // the text in webkit. 732 TextPaint paint = getPaint(); 733 int flags = paint.getFlags() | Paint.SUBPIXEL_TEXT_FLAG | 734 Paint.ANTI_ALIAS_FLAG & ~Paint.DEV_KERN_TEXT_FLAG; 735 paint.setFlags(flags); 736 // Set the text color to black, regardless of the theme. This ensures 737 // that other applications that use embedded WebViews will properly 738 // display the text in password textfields. 739 setTextColor(Color.BLACK); 740 } 741 742 @Override 743 public void setInputType(int type) { 744 mFromSetInputType = true; 745 super.setInputType(type); 746 mFromSetInputType = false; 747 } 748 749 private void setMaxLength(int maxLength) { 750 mMaxLength = maxLength; 751 if (-1 == maxLength) { 752 setFilters(NO_FILTERS); 753 } else { 754 setFilters(new InputFilter[] { 755 new InputFilter.LengthFilter(maxLength) }); 756 } 757 } 758 759 /** 760 * Set the pointer for this node so it can be determined which node this 761 * WebTextView represents. 762 * @param ptr Integer representing the pointer to the node which this 763 * WebTextView represents. 764 */ 765 /* package */ void setNodePointer(int ptr) { 766 mNodePointer = ptr; 767 } 768 769 /** 770 * Determine the position and size of WebTextView, and add it to the 771 * WebView's view heirarchy. All parameters are presumed to be in 772 * view coordinates. Also requests Focus and sets the cursor to not 773 * request to be in view. 774 * @param x x-position of the textfield. 775 * @param y y-position of the textfield. 776 * @param width width of the textfield. 777 * @param height height of the textfield. 778 */ 779 /* package */ void setRect(int x, int y, int width, int height) { 780 LayoutParams lp = (LayoutParams) getLayoutParams(); 781 if (null == lp) { 782 lp = new LayoutParams(width, height, x, y); 783 } else { 784 lp.x = x; 785 lp.y = y; 786 lp.width = width; 787 lp.height = height; 788 } 789 if (getParent() == null) { 790 mWebView.addView(this, lp); 791 } else { 792 setLayoutParams(lp); 793 } 794 // Set up a measure spec so a layout can always be recreated. 795 mWidthSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY); 796 mHeightSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY); 797 } 798 799 /** 800 * Set the selection, and disable our onSelectionChanged action. 801 */ 802 /* package */ void setSelectionFromWebKit(int start, int end) { 803 if (start < 0 || end < 0) return; 804 Spannable text = (Spannable) getText(); 805 int length = text.length(); 806 if (start > length || end > length) return; 807 mFromWebKit = true; 808 Selection.setSelection(text, start, end); 809 mFromWebKit = false; 810 } 811 812 /** 813 * Set the text to the new string, but use the old selection, making sure 814 * to keep it within the new string. 815 * @param text The new text to place in the textfield. 816 */ 817 /* package */ void setTextAndKeepSelection(String text) { 818 mPreChange = text.toString(); 819 Editable edit = (Editable) getText(); 820 int selStart = Selection.getSelectionStart(edit); 821 int selEnd = Selection.getSelectionEnd(edit); 822 mInSetTextAndKeepSelection = true; 823 edit.replace(0, edit.length(), text); 824 int newLength = edit.length(); 825 if (selStart > newLength) selStart = newLength; 826 if (selEnd > newLength) selEnd = newLength; 827 Selection.setSelection(edit, selStart, selEnd); 828 mInSetTextAndKeepSelection = false; 829 updateCachedTextfield(); 830 } 831 832 /** 833 * Called by WebView.rebuildWebTextView(). Based on the type of the <input> 834 * element, set up the WebTextView, its InputType, and IME Options properly. 835 * @param type int corresponding to enum "type" defined in WebView.cpp. 836 * Does not correspond to HTMLInputElement::InputType so this 837 * is unaffected if that changes, and also because that has no 838 * type corresponding to textarea (which is its own tag). 839 */ 840 /* package */ void setType(int type) { 841 if (mWebView == null) return; 842 boolean single = true; 843 boolean inPassword = false; 844 int maxLength = -1; 845 int inputType = EditorInfo.TYPE_CLASS_TEXT; 846 if (mWebView.nativeFocusCandidateHasNextTextfield()) { 847 inputType |= EditorInfo.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT; 848 } 849 int imeOptions = EditorInfo.IME_FLAG_NO_EXTRACT_UI 850 | EditorInfo.IME_FLAG_NO_FULLSCREEN; 851 switch (type) { 852 case 0: // NORMAL_TEXT_FIELD 853 imeOptions |= EditorInfo.IME_ACTION_GO; 854 break; 855 case 1: // TEXT_AREA 856 single = false; 857 inputType = EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE 858 | EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES 859 | EditorInfo.TYPE_CLASS_TEXT 860 | EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT; 861 imeOptions |= EditorInfo.IME_ACTION_NONE; 862 break; 863 case 2: // PASSWORD 864 inPassword = true; 865 imeOptions |= EditorInfo.IME_ACTION_GO; 866 break; 867 case 3: // SEARCH 868 imeOptions |= EditorInfo.IME_ACTION_SEARCH; 869 break; 870 case 4: // EMAIL 871 // TYPE_TEXT_VARIATION_WEB_EDIT_TEXT prevents EMAIL_ADDRESS 872 // from working, so exclude it for now. 873 imeOptions |= EditorInfo.IME_ACTION_GO; 874 break; 875 case 5: // NUMBER 876 inputType |= EditorInfo.TYPE_CLASS_NUMBER; 877 // Number and telephone do not have both a Tab key and an 878 // action, so set the action to NEXT 879 imeOptions |= EditorInfo.IME_ACTION_NEXT; 880 break; 881 case 6: // TELEPHONE 882 inputType |= EditorInfo.TYPE_CLASS_PHONE; 883 imeOptions |= EditorInfo.IME_ACTION_NEXT; 884 break; 885 case 7: // URL 886 // TYPE_TEXT_VARIATION_URI prevents Tab key from showing, so 887 // exclude it for now. 888 imeOptions |= EditorInfo.IME_ACTION_GO; 889 break; 890 default: 891 imeOptions |= EditorInfo.IME_ACTION_GO; 892 break; 893 } 894 setHint(null); 895 if (single) { 896 mWebView.requestLabel(mWebView.nativeFocusCandidateFramePointer(), 897 mNodePointer); 898 maxLength = mWebView.nativeFocusCandidateMaxLength(); 899 if (type != 2 /* PASSWORD */) { 900 String name = mWebView.nativeFocusCandidateName(); 901 if (name != null && name.length() > 0) { 902 mWebView.requestFormData(name, mNodePointer); 903 } 904 } 905 } 906 mSingle = single; 907 setMaxLength(maxLength); 908 setHorizontallyScrolling(single); 909 setInputType(inputType); 910 setImeOptions(imeOptions); 911 setInPassword(inPassword); 912 AutoCompleteAdapter adapter = null; 913 setAdapterCustom(adapter); 914 } 915 916 /** 917 * Update the cache to reflect the current text. 918 */ 919 /* package */ void updateCachedTextfield() { 920 mWebView.updateCachedTextfield(getText().toString()); 921 } 922 923 @Override 924 public boolean requestRectangleOnScreen(Rect rectangle) { 925 // don't scroll while in zoom animation. When it is done, we will adjust 926 // the WebTextView if it is in editing mode. 927 if (!mWebView.inAnimateZoom()) { 928 return super.requestRectangleOnScreen(rectangle); 929 } 930 return false; 931 } 932} 933