WebTextView.java revision 0ca70883d752cce77b918421ef81f3134f6ccd1e
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 android.content.Context; 20import android.graphics.Rect; 21import android.text.Editable; 22import android.text.InputFilter; 23import android.text.Selection; 24import android.text.Spannable; 25import android.text.TextUtils; 26import android.text.method.MovementMethod; 27import android.util.Log; 28import android.view.KeyCharacterMap; 29import android.view.KeyEvent; 30import android.view.MotionEvent; 31import android.view.View; 32import android.view.ViewGroup; 33import android.view.inputmethod.EditorInfo; 34import android.view.inputmethod.InputMethodManager; 35import android.view.inputmethod.InputConnection; 36import android.widget.AbsoluteLayout.LayoutParams; 37import android.widget.ArrayAdapter; 38import android.widget.AutoCompleteTextView; 39import android.widget.TextView; 40 41import java.util.ArrayList; 42 43/** 44 * WebTextView is a specialized version of EditText used by WebView 45 * to overlay html textfields (and textareas) to use our standard 46 * text editing. 47 */ 48/* package */ class WebTextView extends AutoCompleteTextView { 49 50 static final String LOGTAG = "webtextview"; 51 52 private WebView mWebView; 53 private boolean mSingle; 54 private int mWidthSpec; 55 private int mHeightSpec; 56 private int mNodePointer; 57 // FIXME: This is a hack for blocking unmatched key ups, in particular 58 // on the enter key. The method for blocking unmatched key ups prevents 59 // the shift key from working properly. 60 private boolean mGotEnterDown; 61 // mScrollToAccommodateCursor being set to false prevents us from scrolling 62 // the cursor on screen when using the trackball to select a textfield. 63 private boolean mScrollToAccommodateCursor; 64 private int mMaxLength; 65 // Keep track of the text before the change so we know whether we actually 66 // need to send down the DOM events. 67 private String mPreChange; 68 // Array to store the final character added in onTextChanged, so that its 69 // KeyEvents may be determined. 70 private char[] mCharacter = new char[1]; 71 // This is used to reset the length filter when on a textfield 72 // with no max length. 73 // FIXME: This can be replaced with TextView.NO_FILTERS if that 74 // is made public/protected. 75 private static final InputFilter[] NO_FILTERS = new InputFilter[0]; 76 77 /** 78 * Create a new WebTextView. 79 * @param context The Context for this WebTextView. 80 * @param webView The WebView that created this. 81 */ 82 /* package */ WebTextView(Context context, WebView webView) { 83 super(context); 84 mWebView = webView; 85 mMaxLength = -1; 86 setImeOptions(EditorInfo.IME_ACTION_NONE); 87 // Allow webkit's drawing to show through 88 setWillNotDraw(true); 89 setCursorVisible(false); 90 } 91 92 @Override 93 public boolean dispatchKeyEvent(KeyEvent event) { 94 if (event.isSystem()) { 95 return super.dispatchKeyEvent(event); 96 } 97 // Treat ACTION_DOWN and ACTION MULTIPLE the same 98 boolean down = event.getAction() != KeyEvent.ACTION_UP; 99 int keyCode = event.getKeyCode(); 100 Spannable text = (Spannable) getText(); 101 int oldLength = text.length(); 102 // Normally the delete key's dom events are sent via onTextChanged. 103 // However, if the length is zero, the text did not change, so we 104 // go ahead and pass the key down immediately. 105 if (KeyEvent.KEYCODE_DEL == keyCode && 0 == oldLength) { 106 sendDomEvent(event); 107 return true; 108 } 109 110 if ((mSingle && KeyEvent.KEYCODE_ENTER == keyCode)) { 111 if (isPopupShowing()) { 112 return super.dispatchKeyEvent(event); 113 } 114 if (!down) { 115 // Hide the keyboard, since the user has just submitted this 116 // form. The submission happens thanks to the two calls 117 // to sendDomEvent. 118 InputMethodManager.getInstance(mContext) 119 .hideSoftInputFromWindow(getWindowToken(), 0); 120 sendDomEvent(new KeyEvent(KeyEvent.ACTION_DOWN, keyCode)); 121 sendDomEvent(event); 122 } 123 return super.dispatchKeyEvent(event); 124 } else if (KeyEvent.KEYCODE_DPAD_CENTER == keyCode) { 125 // Note that this handles center key and trackball. 126 if (isPopupShowing()) { 127 return super.dispatchKeyEvent(event); 128 } 129 if (!mWebView.nativeCursorMatchesFocus()) { 130 return down ? mWebView.onKeyDown(keyCode, event) : mWebView 131 .onKeyUp(keyCode, event); 132 } 133 // Center key should be passed to a potential onClick 134 if (!down) { 135 mWebView.shortPressOnTextField(); 136 } 137 // Pass to super to handle longpress. 138 return super.dispatchKeyEvent(event); 139 } 140 boolean isArrowKey = false; 141 switch(keyCode) { 142 case KeyEvent.KEYCODE_DPAD_LEFT: 143 case KeyEvent.KEYCODE_DPAD_RIGHT: 144 case KeyEvent.KEYCODE_DPAD_UP: 145 case KeyEvent.KEYCODE_DPAD_DOWN: 146 if (!mWebView.nativeCursorMatchesFocus()) { 147 return down ? mWebView.onKeyDown(keyCode, event) : mWebView 148 .onKeyUp(keyCode, event); 149 150 } 151 isArrowKey = true; 152 break; 153 } 154 155 // Ensure there is a layout so arrow keys are handled properly. 156 if (getLayout() == null) { 157 measure(mWidthSpec, mHeightSpec); 158 } 159 int oldStart = Selection.getSelectionStart(text); 160 int oldEnd = Selection.getSelectionEnd(text); 161 162 boolean maxedOut = mMaxLength != -1 && oldLength == mMaxLength; 163 // If we are at max length, and there is a selection rather than a 164 // cursor, we need to store the text to compare later, since the key 165 // may have changed the string. 166 String oldText; 167 if (maxedOut && oldEnd != oldStart) { 168 oldText = text.toString(); 169 } else { 170 oldText = ""; 171 } 172 if (super.dispatchKeyEvent(event)) { 173 // If the WebTextView handled the key it was either an alphanumeric 174 // key, a delete, or a movement within the text. All of those are 175 // ok to pass to javascript. 176 177 // UNLESS there is a max length determined by the html. In that 178 // case, if the string was already at the max length, an 179 // alphanumeric key will be erased by the LengthFilter, 180 // so do not pass down to javascript, and instead 181 // return true. If it is an arrow key or a delete key, we can go 182 // ahead and pass it down. 183 if (KeyEvent.KEYCODE_ENTER == keyCode) { 184 // For multi-line text boxes, newlines will 185 // trigger onTextChanged for key down (which will send both 186 // key up and key down) but not key up. 187 mGotEnterDown = true; 188 } 189 if (maxedOut && !isArrowKey && keyCode != KeyEvent.KEYCODE_DEL) { 190 if (oldEnd == oldStart) { 191 // Return true so the key gets dropped. 192 mScrollToAccommodateCursor = true; 193 return true; 194 } else if (!oldText.equals(getText().toString())) { 195 // FIXME: This makes the text work properly, but it 196 // does not pass down the key event, so it may not 197 // work for a textfield that has the type of 198 // behavior of GoogleSuggest. That said, it is 199 // unlikely that a site would combine the two in 200 // one textfield. 201 Spannable span = (Spannable) getText(); 202 int newStart = Selection.getSelectionStart(span); 203 int newEnd = Selection.getSelectionEnd(span); 204 mWebView.replaceTextfieldText(0, oldLength, span.toString(), 205 newStart, newEnd); 206 mScrollToAccommodateCursor = true; 207 return true; 208 } 209 } 210 /* FIXME: 211 * In theory, we would like to send the events for the arrow keys. 212 * However, the TextView can arbitrarily change the selection (i.e. 213 * long press followed by using the trackball). Therefore, we keep 214 * in sync with the TextView via onSelectionChanged. If we also 215 * send the DOM event, we lose the correct selection. 216 if (isArrowKey) { 217 // Arrow key does not change the text, but we still want to send 218 // the DOM events. 219 sendDomEvent(event); 220 } 221 */ 222 mScrollToAccommodateCursor = true; 223 return true; 224 } 225 // Ignore the key up event for newlines. This prevents 226 // multiple newlines in the native textarea. 227 if (mGotEnterDown && !down) { 228 return true; 229 } 230 // if it is a navigation key, pass it to WebView 231 if (isArrowKey) { 232 // WebView check the trackballtime in onKeyDown to avoid calling 233 // native from both trackball and key handling. As this is called 234 // from WebTextView, we always want WebView to check with native. 235 // Reset trackballtime to ensure it. 236 mWebView.resetTrackballTime(); 237 return down ? mWebView.onKeyDown(keyCode, event) : mWebView 238 .onKeyUp(keyCode, event); 239 } 240 return false; 241 } 242 243 /** 244 * Create a fake touch up event at (x,y) with respect to this WebTextView. 245 * This is used by WebView to act as though a touch event which happened 246 * before we placed the WebTextView actually hit it, so that it can place 247 * the cursor accordingly. 248 */ 249 /* package */ void fakeTouchEvent(float x, float y) { 250 // We need to ensure that there is a Layout, since the Layout is used 251 // in determining where to place the cursor. 252 if (getLayout() == null) { 253 measure(mWidthSpec, mHeightSpec); 254 } 255 // Create a fake touch up, which is used to place the cursor. 256 MotionEvent ev = MotionEvent.obtain(0, 0, MotionEvent.ACTION_UP, 257 x, y, 0); 258 onTouchEvent(ev); 259 ev.recycle(); 260 } 261 262 /** 263 * Determine whether this WebTextView currently represents the node 264 * represented by ptr. 265 * @param ptr Pointer to a node to compare to. 266 * @return boolean Whether this WebTextView already represents the node 267 * pointed to by ptr. 268 */ 269 /* package */ boolean isSameTextField(int ptr) { 270 return ptr == mNodePointer; 271 } 272 273 @Override public InputConnection onCreateInputConnection( 274 EditorInfo outAttrs) { 275 InputConnection connection = super.onCreateInputConnection(outAttrs); 276 if (mWebView != null) { 277 // Use the name of the textfield + the url. Use backslash as an 278 // arbitrary separator. 279 outAttrs.fieldName = mWebView.nativeFocusCandidateName() + "\\" 280 + mWebView.getUrl(); 281 } 282 return connection; 283 } 284 285 @Override 286 protected void onSelectionChanged(int selStart, int selEnd) { 287 if (mWebView != null) { 288 if (DebugFlags.WEB_TEXT_VIEW) { 289 Log.v(LOGTAG, "onSelectionChanged selStart=" + selStart 290 + " selEnd=" + selEnd); 291 } 292 mWebView.setSelection(selStart, selEnd); 293 } 294 } 295 296 @Override 297 protected void onTextChanged(CharSequence s,int start,int before,int count){ 298 super.onTextChanged(s, start, before, count); 299 String postChange = s.toString(); 300 // Prevent calls to setText from invoking onTextChanged (since this will 301 // mean we are on a different textfield). Also prevent the change when 302 // going from a textfield with a string of text to one with a smaller 303 // limit on text length from registering the onTextChanged event. 304 if (mPreChange == null || mPreChange.equals(postChange) || 305 (mMaxLength > -1 && mPreChange.length() > mMaxLength && 306 mPreChange.substring(0, mMaxLength).equals(postChange))) { 307 return; 308 } 309 mPreChange = postChange; 310 // This was simply a delete or a cut, so just delete the selection. 311 if (before > 0 && 0 == count) { 312 mWebView.deleteSelection(start, start + before); 313 // For this and all changes to the text, update our cache 314 updateCachedTextfield(); 315 return; 316 } 317 // Find the last character being replaced. If it can be represented by 318 // events, we will pass them to native (after replacing the beginning 319 // of the changed text), so we can see javascript events. 320 // Otherwise, replace the text being changed (including the last 321 // character) in the textfield. 322 TextUtils.getChars(s, start + count - 1, start + count, mCharacter, 0); 323 KeyCharacterMap kmap = 324 KeyCharacterMap.load(KeyCharacterMap.BUILT_IN_KEYBOARD); 325 KeyEvent[] events = kmap.getEvents(mCharacter); 326 boolean cannotUseKeyEvents = null == events; 327 int charactersFromKeyEvents = cannotUseKeyEvents ? 0 : 1; 328 if (count > 1 || cannotUseKeyEvents) { 329 String replace = s.subSequence(start, 330 start + count - charactersFromKeyEvents).toString(); 331 mWebView.replaceTextfieldText(start, start + before, replace, 332 start + count - charactersFromKeyEvents, 333 start + count - charactersFromKeyEvents); 334 } else { 335 // This corrects the selection which may have been affected by the 336 // trackball or auto-correct. 337 if (DebugFlags.WEB_TEXT_VIEW) { 338 Log.v(LOGTAG, "onTextChanged start=" + start 339 + " start + before=" + (start + before)); 340 } 341 mWebView.setSelection(start, start + before); 342 } 343 if (!cannotUseKeyEvents) { 344 int length = events.length; 345 for (int i = 0; i < length; i++) { 346 // We never send modifier keys to native code so don't send them 347 // here either. 348 if (!KeyEvent.isModifierKey(events[i].getKeyCode())) { 349 sendDomEvent(events[i]); 350 } 351 } 352 } 353 updateCachedTextfield(); 354 } 355 356 @Override 357 public boolean onTrackballEvent(MotionEvent event) { 358 if (isPopupShowing()) { 359 return super.onTrackballEvent(event); 360 } 361 if (event.getAction() != MotionEvent.ACTION_MOVE) { 362 return false; 363 } 364 // If the Cursor is not on the text input, webview should handle the 365 // trackball 366 if (!mWebView.nativeCursorMatchesFocus()) { 367 return mWebView.onTrackballEvent(event); 368 } 369 Spannable text = (Spannable) getText(); 370 MovementMethod move = getMovementMethod(); 371 if (move != null && getLayout() != null && 372 move.onTrackballEvent(this, text, event)) { 373 // Selection is changed in onSelectionChanged 374 return true; 375 } 376 // If the user is in a textfield, and the movement method is not 377 // handling the trackball events, it means they are at the end of the 378 // field and continuing to move the trackball. In this case, we should 379 // not scroll the cursor on screen bc the user may be attempting to 380 // scroll the page, possibly in the opposite direction of the cursor. 381 mScrollToAccommodateCursor = false; 382 return false; 383 } 384 385 /** 386 * Remove this WebTextView from its host WebView, and return 387 * focus to the host. 388 */ 389 /* package */ void remove() { 390 // hide the soft keyboard when the edit text is out of focus 391 InputMethodManager.getInstance(mContext).hideSoftInputFromWindow( 392 getWindowToken(), 0); 393 mWebView.removeView(this); 394 mWebView.requestFocus(); 395 mScrollToAccommodateCursor = false; 396 } 397 398 /* package */ void enableScrollOnScreen(boolean enable) { 399 mScrollToAccommodateCursor = enable; 400 } 401 402 /* package */ void bringIntoView() { 403 if (getLayout() != null) { 404 bringPointIntoView(Selection.getSelectionEnd(getText())); 405 } 406 } 407 408 @Override 409 public boolean requestRectangleOnScreen(Rect rectangle) { 410 if (mScrollToAccommodateCursor) { 411 return super.requestRectangleOnScreen(rectangle); 412 } 413 return false; 414 } 415 416 /** 417 * Send the DOM events for the specified event. 418 * @param event KeyEvent to be translated into a DOM event. 419 */ 420 private void sendDomEvent(KeyEvent event) { 421 mWebView.passToJavaScript(getText().toString(), event); 422 } 423 424 /** 425 * Always use this instead of setAdapter, as this has features specific to 426 * the WebTextView. 427 */ 428 public void setAdapterCustom(AutoCompleteAdapter adapter) { 429 if (adapter != null) { 430 setInputType(EditorInfo.TYPE_TEXT_FLAG_AUTO_COMPLETE); 431 adapter.setTextView(this); 432 } 433 super.setAdapter(adapter); 434 } 435 436 /** 437 * This is a special version of ArrayAdapter which changes its text size 438 * to match the text size of its host TextView. 439 */ 440 public static class AutoCompleteAdapter extends ArrayAdapter<String> { 441 private TextView mTextView; 442 443 public AutoCompleteAdapter(Context context, ArrayList<String> entries) { 444 super(context, com.android.internal.R.layout 445 .search_dropdown_item_1line, entries); 446 } 447 448 /** 449 * {@inheritDoc} 450 */ 451 public View getView(int position, View convertView, ViewGroup parent) { 452 TextView tv = 453 (TextView) super.getView(position, convertView, parent); 454 if (tv != null && mTextView != null) { 455 tv.setTextSize(mTextView.getTextSize()); 456 } 457 return tv; 458 } 459 460 /** 461 * Set the TextView so we can match its text size. 462 */ 463 private void setTextView(TextView tv) { 464 mTextView = tv; 465 } 466 } 467 468 /** 469 * Determine whether to use the system-wide password disguising method, 470 * or to use none. 471 * @param inPassword True if the textfield is a password field. 472 */ 473 /* package */ void setInPassword(boolean inPassword) { 474 if (inPassword) { 475 setInputType(EditorInfo.TYPE_CLASS_TEXT | EditorInfo. 476 TYPE_TEXT_VARIATION_PASSWORD); 477 } 478 } 479 480 /* package */ void setMaxLength(int maxLength) { 481 mMaxLength = maxLength; 482 if (-1 == maxLength) { 483 setFilters(NO_FILTERS); 484 } else { 485 setFilters(new InputFilter[] { 486 new InputFilter.LengthFilter(maxLength) }); 487 } 488 } 489 490 /** 491 * Set the pointer for this node so it can be determined which node this 492 * WebTextView represents. 493 * @param ptr Integer representing the pointer to the node which this 494 * WebTextView represents. 495 */ 496 /* package */ void setNodePointer(int ptr) { 497 mNodePointer = ptr; 498 } 499 500 /** 501 * Determine the position and size of WebTextView, and add it to the 502 * WebView's view heirarchy. All parameters are presumed to be in 503 * view coordinates. Also requests Focus and sets the cursor to not 504 * request to be in view. 505 * @param x x-position of the textfield. 506 * @param y y-position of the textfield. 507 * @param width width of the textfield. 508 * @param height height of the textfield. 509 */ 510 /* package */ void setRect(int x, int y, int width, int height) { 511 LayoutParams lp = (LayoutParams) getLayoutParams(); 512 if (null == lp) { 513 lp = new LayoutParams(width, height, x, y); 514 } else { 515 lp.x = x; 516 lp.y = y; 517 lp.width = width; 518 lp.height = height; 519 } 520 if (getParent() == null) { 521 mWebView.addView(this, lp); 522 } else { 523 setLayoutParams(lp); 524 } 525 // Set up a measure spec so a layout can always be recreated. 526 mWidthSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY); 527 mHeightSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY); 528 requestFocus(); 529 } 530 531 /** 532 * Set whether this is a single-line textfield or a multi-line textarea. 533 * Textfields scroll horizontally, and do not handle the enter key. 534 * Textareas behave oppositely. 535 * Do NOT call this after calling setInPassword(true). This will result in 536 * removing the password input type. 537 */ 538 public void setSingleLine(boolean single) { 539 int inputType = EditorInfo.TYPE_CLASS_TEXT 540 | EditorInfo.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT; 541 if (!single) { 542 inputType |= EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE 543 | EditorInfo.TYPE_TEXT_FLAG_CAP_SENTENCES 544 | EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT; 545 } 546 mSingle = single; 547 setHorizontallyScrolling(single); 548 setInputType(inputType); 549 } 550 551 /** 552 * Set the text for this WebTextView, and set the selection to (start, end) 553 * @param text Text to go into this WebTextView. 554 * @param start Beginning of the selection. 555 * @param end End of the selection. 556 */ 557 /* package */ void setText(CharSequence text, int start, int end) { 558 mPreChange = text.toString(); 559 setText(text); 560 Spannable span = (Spannable) getText(); 561 int length = span.length(); 562 if (end > length) { 563 end = length; 564 } 565 if (start < 0) { 566 start = 0; 567 } else if (start > length) { 568 start = length; 569 } 570 if (DebugFlags.WEB_TEXT_VIEW) { 571 Log.v(LOGTAG, "setText start=" + start 572 + " end=" + end); 573 } 574 Selection.setSelection(span, start, end); 575 } 576 577 /** 578 * Set the text to the new string, but use the old selection, making sure 579 * to keep it within the new string. 580 * @param text The new text to place in the textfield. 581 */ 582 /* package */ void setTextAndKeepSelection(String text) { 583 mPreChange = text.toString(); 584 Editable edit = (Editable) getText(); 585 edit.replace(0, edit.length(), text); 586 updateCachedTextfield(); 587 } 588 589 /** 590 * Update the cache to reflect the current text. 591 */ 592 /* package */ void updateCachedTextfield() { 593 mWebView.updateCachedTextfield(getText().toString()); 594 } 595} 596