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