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