BaseInputConnection.java revision a90b7f0125389b9e1040d2be82aad4ef74ea6071
1/* 2 * Copyright (C) 2008 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not 5 * use this file except in compliance with the License. You may obtain a copy of 6 * 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, WITHOUT 12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 * License for the specific language governing permissions and limitations under 14 * the License. 15 */ 16 17package android.view.inputmethod; 18 19import android.content.Context; 20import android.content.res.TypedArray; 21import android.os.Bundle; 22import android.os.Handler; 23import android.os.SystemClock; 24import android.text.Editable; 25import android.text.NoCopySpan; 26import android.text.Selection; 27import android.text.Spannable; 28import android.text.SpannableStringBuilder; 29import android.text.Spanned; 30import android.text.TextUtils; 31import android.text.method.MetaKeyKeyListener; 32import android.util.Log; 33import android.util.LogPrinter; 34import android.view.KeyCharacterMap; 35import android.view.KeyEvent; 36import android.view.View; 37import android.view.ViewRoot; 38 39class ComposingText implements NoCopySpan { 40} 41 42/** 43 * Base class for implementors of the InputConnection interface, taking care 44 * of most of the common behavior for providing a connection to an Editable. 45 * Implementors of this class will want to be sure to implement 46 * {@link #getEditable} to provide access to their own editable object. 47 */ 48public class BaseInputConnection implements InputConnection { 49 private static final boolean DEBUG = false; 50 private static final String TAG = "BaseInputConnection"; 51 static final Object COMPOSING = new ComposingText(); 52 53 final InputMethodManager mIMM; 54 final View mTargetView; 55 final boolean mDummyMode; 56 57 private Object[] mDefaultComposingSpans; 58 59 Editable mEditable; 60 KeyCharacterMap mKeyCharacterMap; 61 62 BaseInputConnection(InputMethodManager mgr, boolean fullEditor) { 63 mIMM = mgr; 64 mTargetView = null; 65 mDummyMode = !fullEditor; 66 } 67 68 public BaseInputConnection(View targetView, boolean fullEditor) { 69 mIMM = (InputMethodManager)targetView.getContext().getSystemService( 70 Context.INPUT_METHOD_SERVICE); 71 mTargetView = targetView; 72 mDummyMode = !fullEditor; 73 } 74 75 public static final void removeComposingSpans(Spannable text) { 76 text.removeSpan(COMPOSING); 77 Object[] sps = text.getSpans(0, text.length(), Object.class); 78 if (sps != null) { 79 for (int i=sps.length-1; i>=0; i--) { 80 Object o = sps[i]; 81 if ((text.getSpanFlags(o)&Spanned.SPAN_COMPOSING) != 0) { 82 text.removeSpan(o); 83 } 84 } 85 } 86 } 87 88 public static void setComposingSpans(Spannable text) { 89 setComposingSpans(text, 0, text.length()); 90 } 91 92 /** @hide */ 93 public static void setComposingSpans(Spannable text, int start, int end) { 94 final Object[] sps = text.getSpans(start, end, Object.class); 95 if (sps != null) { 96 for (int i=sps.length-1; i>=0; i--) { 97 final Object o = sps[i]; 98 if (o == COMPOSING) { 99 text.removeSpan(o); 100 continue; 101 } 102 103 final int fl = text.getSpanFlags(o); 104 if ((fl&(Spanned.SPAN_COMPOSING|Spanned.SPAN_POINT_MARK_MASK)) 105 != (Spanned.SPAN_COMPOSING|Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)) { 106 text.setSpan(o, text.getSpanStart(o), text.getSpanEnd(o), 107 (fl & ~Spanned.SPAN_POINT_MARK_MASK) 108 | Spanned.SPAN_COMPOSING 109 | Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 110 } 111 } 112 } 113 114 text.setSpan(COMPOSING, start, end, 115 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE | Spanned.SPAN_COMPOSING); 116 } 117 118 public static int getComposingSpanStart(Spannable text) { 119 return text.getSpanStart(COMPOSING); 120 } 121 122 public static int getComposingSpanEnd(Spannable text) { 123 return text.getSpanEnd(COMPOSING); 124 } 125 126 /** 127 * Return the target of edit operations. The default implementation 128 * returns its own fake editable that is just used for composing text; 129 * subclasses that are real text editors should override this and 130 * supply their own. 131 */ 132 public Editable getEditable() { 133 if (mEditable == null) { 134 mEditable = Editable.Factory.getInstance().newEditable(""); 135 Selection.setSelection(mEditable, 0); 136 } 137 return mEditable; 138 } 139 140 /** 141 * Default implementation does nothing. 142 */ 143 public boolean beginBatchEdit() { 144 return false; 145 } 146 147 /** 148 * Default implementation does nothing. 149 */ 150 public boolean endBatchEdit() { 151 return false; 152 } 153 154 /** 155 * Default implementation uses 156 * {@link MetaKeyKeyListener#clearMetaKeyState(long, int) 157 * MetaKeyKeyListener.clearMetaKeyState(long, int)} to clear the state. 158 */ 159 public boolean clearMetaKeyStates(int states) { 160 final Editable content = getEditable(); 161 if (content == null) return false; 162 MetaKeyKeyListener.clearMetaKeyState(content, states); 163 return true; 164 } 165 166 /** 167 * Default implementation does nothing. 168 */ 169 public boolean commitCompletion(CompletionInfo text) { 170 return false; 171 } 172 173 /** 174 * Default implementation replaces any existing composing text with 175 * the given text. In addition, only if dummy mode, a key event is 176 * sent for the new text and the current editable buffer cleared. 177 */ 178 public boolean commitText(CharSequence text, int newCursorPosition) { 179 if (DEBUG) Log.v(TAG, "commitText " + text); 180 replaceText(text, newCursorPosition, false); 181 sendCurrentText(); 182 return true; 183 } 184 185 /** 186 * The default implementation performs the deletion around the current 187 * selection position of the editable text. 188 */ 189 public boolean deleteSurroundingText(int leftLength, int rightLength) { 190 if (DEBUG) Log.v(TAG, "deleteSurroundingText " + leftLength 191 + " / " + rightLength); 192 final Editable content = getEditable(); 193 if (content == null) return false; 194 195 beginBatchEdit(); 196 197 int a = Selection.getSelectionStart(content); 198 int b = Selection.getSelectionEnd(content); 199 200 if (a > b) { 201 int tmp = a; 202 a = b; 203 b = tmp; 204 } 205 206 // ignore the composing text. 207 int ca = getComposingSpanStart(content); 208 int cb = getComposingSpanEnd(content); 209 if (cb < ca) { 210 int tmp = ca; 211 ca = cb; 212 cb = tmp; 213 } 214 if (ca != -1 && cb != -1) { 215 if (ca < a) a = ca; 216 if (cb > b) b = cb; 217 } 218 219 int deleted = 0; 220 221 if (leftLength > 0) { 222 int start = a - leftLength; 223 if (start < 0) start = 0; 224 content.delete(start, a); 225 deleted = a - start; 226 } 227 228 if (rightLength > 0) { 229 b = b - deleted; 230 231 int end = b + rightLength; 232 if (end > content.length()) end = content.length(); 233 234 content.delete(b, end); 235 } 236 237 endBatchEdit(); 238 239 return true; 240 } 241 242 /** 243 * The default implementation removes the composing state from the 244 * current editable text. In addition, only if dummy mode, a key event is 245 * sent for the new text and the current editable buffer cleared. 246 */ 247 public boolean finishComposingText() { 248 if (DEBUG) Log.v(TAG, "finishComposingText"); 249 final Editable content = getEditable(); 250 if (content != null) { 251 beginBatchEdit(); 252 removeComposingSpans(content); 253 endBatchEdit(); 254 sendCurrentText(); 255 } 256 return true; 257 } 258 259 /** 260 * The default implementation uses TextUtils.getCapsMode to get the 261 * cursor caps mode for the current selection position in the editable 262 * text, unless in dummy mode in which case 0 is always returned. 263 */ 264 public int getCursorCapsMode(int reqModes) { 265 if (mDummyMode) return 0; 266 267 final Editable content = getEditable(); 268 if (content == null) return 0; 269 270 int a = Selection.getSelectionStart(content); 271 int b = Selection.getSelectionEnd(content); 272 273 if (a > b) { 274 int tmp = a; 275 a = b; 276 b = tmp; 277 } 278 279 return TextUtils.getCapsMode(content, a, reqModes); 280 } 281 282 /** 283 * The default implementation always returns null. 284 */ 285 public ExtractedText getExtractedText(ExtractedTextRequest request, int flags) { 286 return null; 287 } 288 289 /** 290 * The default implementation returns the given amount of text from the 291 * current cursor position in the buffer. 292 */ 293 public CharSequence getTextBeforeCursor(int length, int flags) { 294 final Editable content = getEditable(); 295 if (content == null) return null; 296 297 int a = Selection.getSelectionStart(content); 298 int b = Selection.getSelectionEnd(content); 299 300 if (a > b) { 301 int tmp = a; 302 a = b; 303 b = tmp; 304 } 305 306 if (a <= 0) { 307 return ""; 308 } 309 310 if (length > a) { 311 length = a; 312 } 313 314 if ((flags&GET_TEXT_WITH_STYLES) != 0) { 315 return content.subSequence(a - length, a); 316 } 317 return TextUtils.substring(content, a - length, a); 318 } 319 320 /** 321 * The default implementation returns the text currently selected, or null if none is 322 * selected. 323 */ 324 public CharSequence getSelectedText(int flags) { 325 final Editable content = getEditable(); 326 if (content == null) return null; 327 328 int a = Selection.getSelectionStart(content); 329 int b = Selection.getSelectionEnd(content); 330 331 if (a > b) { 332 int tmp = a; 333 a = b; 334 b = tmp; 335 } 336 337 if (a == b) return null; 338 339 if ((flags&GET_TEXT_WITH_STYLES) != 0) { 340 return content.subSequence(a, b); 341 } 342 return TextUtils.substring(content, a, b); 343 } 344 345 /** 346 * The default implementation returns the given amount of text from the 347 * current cursor position in the buffer. 348 */ 349 public CharSequence getTextAfterCursor(int length, int flags) { 350 final Editable content = getEditable(); 351 if (content == null) return null; 352 353 int a = Selection.getSelectionStart(content); 354 int b = Selection.getSelectionEnd(content); 355 356 if (a > b) { 357 int tmp = a; 358 a = b; 359 b = tmp; 360 } 361 362 // Guard against the case where the cursor has not been positioned yet. 363 if (b < 0) { 364 b = 0; 365 } 366 367 if (b + length > content.length()) { 368 length = content.length() - b; 369 } 370 371 372 if ((flags&GET_TEXT_WITH_STYLES) != 0) { 373 return content.subSequence(b, b + length); 374 } 375 return TextUtils.substring(content, b, b + length); 376 } 377 378 /** 379 * The default implementation turns this into the enter key. 380 */ 381 public boolean performEditorAction(int actionCode) { 382 long eventTime = SystemClock.uptimeMillis(); 383 sendKeyEvent(new KeyEvent(eventTime, eventTime, 384 KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER, 0, 0, 0, 0, 385 KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE 386 | KeyEvent.FLAG_EDITOR_ACTION)); 387 sendKeyEvent(new KeyEvent(SystemClock.uptimeMillis(), eventTime, 388 KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER, 0, 0, 0, 0, 389 KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE 390 | KeyEvent.FLAG_EDITOR_ACTION)); 391 return true; 392 } 393 394 /** 395 * The default implementation does nothing. 396 */ 397 public boolean performContextMenuAction(int id) { 398 return false; 399 } 400 401 /** 402 * The default implementation does nothing. 403 */ 404 public boolean performPrivateCommand(String action, Bundle data) { 405 return false; 406 } 407 408 /** 409 * The default implementation places the given text into the editable, 410 * replacing any existing composing text. The new text is marked as 411 * in a composing state with the composing style. 412 */ 413 public boolean setComposingText(CharSequence text, int newCursorPosition) { 414 if (DEBUG) Log.v(TAG, "setComposingText " + text); 415 replaceText(text, newCursorPosition, true); 416 return true; 417 } 418 419 public boolean setComposingRegion(int start, int end) { 420 final Editable content = getEditable(); 421 if (content != null) { 422 beginBatchEdit(); 423 removeComposingSpans(content); 424 int a = start; 425 int b = end; 426 if (a > b) { 427 int tmp = a; 428 a = b; 429 b = tmp; 430 } 431 if (a < 0) a = 0; 432 if (b > content.length()) b = content.length(); 433 434 ensureDefaultComposingSpans(); 435 if (mDefaultComposingSpans != null) { 436 for (int i = 0; i < mDefaultComposingSpans.length; ++i) { 437 content.setSpan(mDefaultComposingSpans[i], a, b, 438 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE | Spanned.SPAN_COMPOSING); 439 } 440 } 441 442 content.setSpan(COMPOSING, a, b, 443 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE | Spanned.SPAN_COMPOSING); 444 445 endBatchEdit(); 446 sendCurrentText(); 447 } 448 return true; 449 } 450 451 /** 452 * The default implementation changes the selection position in the 453 * current editable text. 454 */ 455 public boolean setSelection(int start, int end) { 456 if (DEBUG) Log.v(TAG, "setSelection " + start + ", " + end); 457 final Editable content = getEditable(); 458 if (content == null) return false; 459 int len = content.length(); 460 if (start > len || end > len) { 461 // If the given selection is out of bounds, just ignore it. 462 // Most likely the text was changed out from under the IME, 463 // the the IME is going to have to update all of its state 464 // anyway. 465 return true; 466 } 467 if (start == end && MetaKeyKeyListener.getMetaState(content, 468 MetaKeyKeyListener.META_SELECTING) != 0) { 469 // If we are in selection mode, then we want to extend the 470 // selection instead of replacing it. 471 Selection.extendSelection(content, start); 472 } else { 473 Selection.setSelection(content, start, end); 474 } 475 return true; 476 } 477 478 /** 479 * Provides standard implementation for sending a key event to the window 480 * attached to the input connection's view. 481 */ 482 public boolean sendKeyEvent(KeyEvent event) { 483 synchronized (mIMM.mH) { 484 Handler h = mTargetView != null ? mTargetView.getHandler() : null; 485 if (h == null) { 486 if (mIMM.mServedView != null) { 487 h = mIMM.mServedView.getHandler(); 488 } 489 } 490 if (h != null) { 491 h.sendMessage(h.obtainMessage(ViewRoot.DISPATCH_KEY_FROM_IME, 492 event)); 493 } 494 } 495 return false; 496 } 497 498 /** 499 * Updates InputMethodManager with the current fullscreen mode. 500 */ 501 public boolean reportFullscreenMode(boolean enabled) { 502 mIMM.setFullscreenMode(enabled); 503 return true; 504 } 505 506 private void sendCurrentText() { 507 if (!mDummyMode) { 508 return; 509 } 510 511 Editable content = getEditable(); 512 if (content != null) { 513 final int N = content.length(); 514 if (N == 0) { 515 return; 516 } 517 if (N == 1) { 518 // If it's 1 character, we have a chance of being 519 // able to generate normal key events... 520 if (mKeyCharacterMap == null) { 521 mKeyCharacterMap = KeyCharacterMap.load( 522 KeyCharacterMap.BUILT_IN_KEYBOARD); 523 } 524 char[] chars = new char[1]; 525 content.getChars(0, 1, chars, 0); 526 KeyEvent[] events = mKeyCharacterMap.getEvents(chars); 527 if (events != null) { 528 for (int i=0; i<events.length; i++) { 529 if (DEBUG) Log.v(TAG, "Sending: " + events[i]); 530 sendKeyEvent(events[i]); 531 } 532 content.clear(); 533 return; 534 } 535 } 536 537 // Otherwise, revert to the special key event containing 538 // the actual characters. 539 KeyEvent event = new KeyEvent(SystemClock.uptimeMillis(), 540 content.toString(), KeyCharacterMap.BUILT_IN_KEYBOARD, 0); 541 sendKeyEvent(event); 542 content.clear(); 543 } 544 } 545 546 private void ensureDefaultComposingSpans() { 547 if (mDefaultComposingSpans == null) { 548 Context context; 549 if (mTargetView != null) { 550 context = mTargetView.getContext(); 551 } else if (mIMM.mServedView != null) { 552 context = mIMM.mServedView.getContext(); 553 } else { 554 context = null; 555 } 556 if (context != null) { 557 TypedArray ta = context.getTheme() 558 .obtainStyledAttributes(new int[] { 559 com.android.internal.R.attr.candidatesTextStyleSpans 560 }); 561 CharSequence style = ta.getText(0); 562 ta.recycle(); 563 if (style != null && style instanceof Spanned) { 564 mDefaultComposingSpans = ((Spanned)style).getSpans( 565 0, style.length(), Object.class); 566 } 567 } 568 } 569 } 570 571 private void replaceText(CharSequence text, int newCursorPosition, 572 boolean composing) { 573 final Editable content = getEditable(); 574 if (content == null) { 575 return; 576 } 577 578 beginBatchEdit(); 579 580 // delete composing text set previously. 581 int a = getComposingSpanStart(content); 582 int b = getComposingSpanEnd(content); 583 584 if (DEBUG) Log.v(TAG, "Composing span: " + a + " to " + b); 585 586 if (b < a) { 587 int tmp = a; 588 a = b; 589 b = tmp; 590 } 591 592 if (a != -1 && b != -1) { 593 removeComposingSpans(content); 594 } else { 595 a = Selection.getSelectionStart(content); 596 b = Selection.getSelectionEnd(content); 597 if (a < 0) a = 0; 598 if (b < 0) b = 0; 599 if (b < a) { 600 int tmp = a; 601 a = b; 602 b = tmp; 603 } 604 } 605 606 if (composing) { 607 Spannable sp = null; 608 if (!(text instanceof Spannable)) { 609 sp = new SpannableStringBuilder(text); 610 text = sp; 611 ensureDefaultComposingSpans(); 612 if (mDefaultComposingSpans != null) { 613 for (int i = 0; i < mDefaultComposingSpans.length; ++i) { 614 sp.setSpan(mDefaultComposingSpans[i], 0, sp.length(), 615 Spanned.SPAN_EXCLUSIVE_EXCLUSIVE | Spanned.SPAN_COMPOSING); 616 } 617 } 618 } else { 619 sp = (Spannable)text; 620 } 621 setComposingSpans(sp); 622 } 623 624 if (DEBUG) Log.v(TAG, "Replacing from " + a + " to " + b + " with \"" 625 + text + "\", composing=" + composing 626 + ", type=" + text.getClass().getCanonicalName()); 627 628 if (DEBUG) { 629 LogPrinter lp = new LogPrinter(Log.VERBOSE, TAG); 630 lp.println("Current text:"); 631 TextUtils.dumpSpans(content, lp, " "); 632 lp.println("Composing text:"); 633 TextUtils.dumpSpans(text, lp, " "); 634 } 635 636 // Position the cursor appropriately, so that after replacing the 637 // desired range of text it will be located in the correct spot. 638 // This allows us to deal with filters performing edits on the text 639 // we are providing here. 640 if (newCursorPosition > 0) { 641 newCursorPosition += b - 1; 642 } else { 643 newCursorPosition += a; 644 } 645 if (newCursorPosition < 0) newCursorPosition = 0; 646 if (newCursorPosition > content.length()) 647 newCursorPosition = content.length(); 648 Selection.setSelection(content, newCursorPosition); 649 650 content.replace(a, b, text); 651 652 if (DEBUG) { 653 LogPrinter lp = new LogPrinter(Log.VERBOSE, TAG); 654 lp.println("Final text:"); 655 TextUtils.dumpSpans(content, lp, " "); 656 } 657 658 endBatchEdit(); 659 } 660} 661