1 /* 2 * Copyright (C) 2008 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 17 package android.view.inputmethod; 18 19 import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL; 20 21 import android.annotation.IntDef; 22 import android.annotation.NonNull; 23 import android.annotation.Nullable; 24 import android.annotation.RequiresPermission; 25 import android.os.Bundle; 26 import android.os.LocaleList; 27 import android.os.Parcel; 28 import android.os.Parcelable; 29 import android.os.UserHandle; 30 import android.text.Editable; 31 import android.text.InputType; 32 import android.text.TextUtils; 33 import android.util.Printer; 34 import android.view.View; 35 import android.view.autofill.AutofillId; 36 37 import com.android.internal.annotations.VisibleForTesting; 38 39 import java.lang.annotation.Retention; 40 import java.lang.annotation.RetentionPolicy; 41 import java.util.Arrays; 42 import java.util.Objects; 43 44 /** 45 * An EditorInfo describes several attributes of a text editing object 46 * that an input method is communicating with (typically an EditText), most 47 * importantly the type of text content it contains and the current cursor position. 48 */ 49 public class EditorInfo implements InputType, Parcelable { 50 /** 51 * Masks for {@link inputType} 52 * 53 * <pre> 54 * |-------|-------|-------|-------| 55 * 1111 TYPE_MASK_CLASS 56 * 11111111 TYPE_MASK_VARIATION 57 * 111111111111 TYPE_MASK_FLAGS 58 * |-------|-------|-------|-------| 59 * TYPE_NULL 60 * |-------|-------|-------|-------| 61 * 1 TYPE_CLASS_TEXT 62 * 1 TYPE_TEXT_VARIATION_URI 63 * 1 TYPE_TEXT_VARIATION_EMAIL_ADDRESS 64 * 11 TYPE_TEXT_VARIATION_EMAIL_SUBJECT 65 * 1 TYPE_TEXT_VARIATION_SHORT_MESSAGE 66 * 1 1 TYPE_TEXT_VARIATION_LONG_MESSAGE 67 * 11 TYPE_TEXT_VARIATION_PERSON_NAME 68 * 111 TYPE_TEXT_VARIATION_POSTAL_ADDRESS 69 * 1 TYPE_TEXT_VARIATION_PASSWORD 70 * 1 1 TYPE_TEXT_VARIATION_VISIBLE_PASSWORD 71 * 1 1 TYPE_TEXT_VARIATION_WEB_EDIT_TEXT 72 * 1 11 TYPE_TEXT_VARIATION_FILTER 73 * 11 TYPE_TEXT_VARIATION_PHONETIC 74 * 11 1 TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS 75 * 111 TYPE_TEXT_VARIATION_WEB_PASSWORD 76 * 1 TYPE_TEXT_FLAG_CAP_CHARACTERS 77 * 1 TYPE_TEXT_FLAG_CAP_WORDS 78 * 1 TYPE_TEXT_FLAG_CAP_SENTENCES 79 * 1 TYPE_TEXT_FLAG_AUTO_CORRECT 80 * 1 TYPE_TEXT_FLAG_AUTO_COMPLETE 81 * 1 TYPE_TEXT_FLAG_MULTI_LINE 82 * 1 TYPE_TEXT_FLAG_IME_MULTI_LINE 83 * 1 TYPE_TEXT_FLAG_NO_SUGGESTIONS 84 * |-------|-------|-------|-------| 85 * 1 TYPE_CLASS_NUMBER 86 * 1 TYPE_NUMBER_VARIATION_PASSWORD 87 * 1 TYPE_NUMBER_FLAG_SIGNED 88 * 1 TYPE_NUMBER_FLAG_DECIMAL 89 * |-------|-------|-------|-------| 90 * 11 TYPE_CLASS_PHONE 91 * |-------|-------|-------|-------| 92 * 1 TYPE_CLASS_DATETIME 93 * 1 TYPE_DATETIME_VARIATION_DATE 94 * 1 TYPE_DATETIME_VARIATION_TIME 95 * |-------|-------|-------|-------|</pre> 96 */ 97 98 /** 99 * The content type of the text box, whose bits are defined by 100 * {@link InputType}. 101 * 102 * @see InputType 103 * @see #TYPE_MASK_CLASS 104 * @see #TYPE_MASK_VARIATION 105 * @see #TYPE_MASK_FLAGS 106 */ 107 public int inputType = TYPE_NULL; 108 109 /** 110 * Set of bits in {@link #imeOptions} that provide alternative actions 111 * associated with the "enter" key. This both helps the IME provide 112 * better feedback about what the enter key will do, and also allows it 113 * to provide alternative mechanisms for providing that command. 114 */ 115 public static final int IME_MASK_ACTION = 0x000000ff; 116 117 /** 118 * Bits of {@link #IME_MASK_ACTION}: no specific action has been 119 * associated with this editor, let the editor come up with its own if 120 * it can. 121 */ 122 public static final int IME_ACTION_UNSPECIFIED = 0x00000000; 123 124 /** 125 * Bits of {@link #IME_MASK_ACTION}: there is no available action. 126 */ 127 public static final int IME_ACTION_NONE = 0x00000001; 128 129 /** 130 * Bits of {@link #IME_MASK_ACTION}: the action key performs a "go" 131 * operation to take the user to the target of the text they typed. 132 * Typically used, for example, when entering a URL. 133 */ 134 public static final int IME_ACTION_GO = 0x00000002; 135 136 /** 137 * Bits of {@link #IME_MASK_ACTION}: the action key performs a "search" 138 * operation, taking the user to the results of searching for the text 139 * they have typed (in whatever context is appropriate). 140 */ 141 public static final int IME_ACTION_SEARCH = 0x00000003; 142 143 /** 144 * Bits of {@link #IME_MASK_ACTION}: the action key performs a "send" 145 * operation, delivering the text to its target. This is typically used 146 * when composing a message in IM or SMS where sending is immediate. 147 */ 148 public static final int IME_ACTION_SEND = 0x00000004; 149 150 /** 151 * Bits of {@link #IME_MASK_ACTION}: the action key performs a "next" 152 * operation, taking the user to the next field that will accept text. 153 */ 154 public static final int IME_ACTION_NEXT = 0x00000005; 155 156 /** 157 * Bits of {@link #IME_MASK_ACTION}: the action key performs a "done" 158 * operation, typically meaning there is nothing more to input and the 159 * IME will be closed. 160 */ 161 public static final int IME_ACTION_DONE = 0x00000006; 162 163 /** 164 * Bits of {@link #IME_MASK_ACTION}: like {@link #IME_ACTION_NEXT}, but 165 * for moving to the previous field. This will normally not be used to 166 * specify an action (since it precludes {@link #IME_ACTION_NEXT}), but 167 * can be returned to the app if it sets {@link #IME_FLAG_NAVIGATE_PREVIOUS}. 168 */ 169 public static final int IME_ACTION_PREVIOUS = 0x00000007; 170 171 /** 172 * Flag of {@link #imeOptions}: used to request that the IME should not update any personalized 173 * data such as typing history and personalized language model based on what the user typed on 174 * this text editing object. Typical use cases are: 175 * <ul> 176 * <li>When the application is in a special mode, where user's activities are expected to be 177 * not recorded in the application's history. Some web browsers and chat applications may 178 * have this kind of modes.</li> 179 * <li>When storing typing history does not make much sense. Specifying this flag in typing 180 * games may help to avoid typing history from being filled up with words that the user is 181 * less likely to type in their daily life. Another example is that when the application 182 * already knows that the expected input is not a valid word (e.g. a promotion code that is 183 * not a valid word in any natural language).</li> 184 * </ul> 185 * 186 * <p>Applications need to be aware that the flag is not a guarantee, and some IMEs may not 187 * respect it.</p> 188 */ 189 public static final int IME_FLAG_NO_PERSONALIZED_LEARNING = 0x1000000; 190 191 /** 192 * Flag of {@link #imeOptions}: used to request that the IME never go 193 * into fullscreen mode. 194 * By default, IMEs may go into full screen mode when they think 195 * it's appropriate, for example on small screens in landscape 196 * orientation where displaying a software keyboard may occlude 197 * such a large portion of the screen that the remaining part is 198 * too small to meaningfully display the application UI. 199 * If this flag is set, compliant IMEs will never go into full screen mode, 200 * and always leave some space to display the application UI. 201 * Applications need to be aware that the flag is not a guarantee, and 202 * some IMEs may ignore it. 203 */ 204 public static final int IME_FLAG_NO_FULLSCREEN = 0x2000000; 205 206 /** 207 * Flag of {@link #imeOptions}: like {@link #IME_FLAG_NAVIGATE_NEXT}, but 208 * specifies there is something interesting that a backward navigation 209 * can focus on. If the user selects the IME's facility to backward 210 * navigate, this will show up in the application as an {@link #IME_ACTION_PREVIOUS} 211 * at {@link InputConnection#performEditorAction(int) 212 * InputConnection.performEditorAction(int)}. 213 */ 214 public static final int IME_FLAG_NAVIGATE_PREVIOUS = 0x4000000; 215 216 /** 217 * Flag of {@link #imeOptions}: used to specify that there is something 218 * interesting that a forward navigation can focus on. This is like using 219 * {@link #IME_ACTION_NEXT}, except allows the IME to be multiline (with 220 * an enter key) as well as provide forward navigation. Note that some 221 * IMEs may not be able to do this, especially when running on a small 222 * screen where there is little space. In that case it does not need to 223 * present a UI for this option. Like {@link #IME_ACTION_NEXT}, if the 224 * user selects the IME's facility to forward navigate, this will show up 225 * in the application at {@link InputConnection#performEditorAction(int) 226 * InputConnection.performEditorAction(int)}. 227 */ 228 public static final int IME_FLAG_NAVIGATE_NEXT = 0x8000000; 229 230 /** 231 * Flag of {@link #imeOptions}: used to specify that the IME does not need 232 * to show its extracted text UI. For input methods that may be fullscreen, 233 * often when in landscape mode, this allows them to be smaller and let part 234 * of the application be shown behind, through transparent UI parts in the 235 * fullscreen IME. The part of the UI visible to the user may not be responsive 236 * to touch because the IME will receive touch events, which may confuse the 237 * user; use {@link #IME_FLAG_NO_FULLSCREEN} instead for a better experience. 238 * Using this flag is discouraged and it may become deprecated in the future. 239 * Its meaning is unclear in some situations and it may not work appropriately 240 * on older versions of the platform. 241 */ 242 public static final int IME_FLAG_NO_EXTRACT_UI = 0x10000000; 243 244 /** 245 * Flag of {@link #imeOptions}: used in conjunction with one of the actions 246 * masked by {@link #IME_MASK_ACTION}, this indicates that the action 247 * should not be available as an accessory button on the right of the extracted 248 * text when the input method is full-screen. Note that by setting this flag, 249 * there can be cases where the action is simply never available to the 250 * user. Setting this generally means that you think that in fullscreen mode, 251 * where there is little space to show the text, it's not worth taking some 252 * screen real estate to display the action and it should be used instead 253 * to show more text. 254 */ 255 public static final int IME_FLAG_NO_ACCESSORY_ACTION = 0x20000000; 256 257 /** 258 * Flag of {@link #imeOptions}: used in conjunction with one of the actions 259 * masked by {@link #IME_MASK_ACTION}. If this flag is not set, IMEs will 260 * normally replace the "enter" key with the action supplied. This flag 261 * indicates that the action should not be available in-line as a replacement 262 * for the "enter" key. Typically this is because the action has such a 263 * significant impact or is not recoverable enough that accidentally hitting 264 * it should be avoided, such as sending a message. Note that 265 * {@link android.widget.TextView} will automatically set this flag for you 266 * on multi-line text views. 267 */ 268 public static final int IME_FLAG_NO_ENTER_ACTION = 0x40000000; 269 270 /** 271 * Flag of {@link #imeOptions}: used to request an IME that is capable of 272 * inputting ASCII characters. The intention of this flag is to ensure that 273 * the user can type Roman alphabet characters in a {@link android.widget.TextView}. 274 * It is typically used for an account ID or password input. A lot of the time, 275 * IMEs are already able to input ASCII even without being told so (such IMEs 276 * already respect this flag in a sense), but there are cases when this is not 277 * the default. For instance, users of languages using a different script like 278 * Arabic, Greek, Hebrew or Russian typically have a keyboard that can't 279 * input ASCII characters by default. Applications need to be 280 * aware that the flag is not a guarantee, and some IMEs may not respect it. 281 * However, it is strongly recommended for IME authors to respect this flag 282 * especially when their IME could end up with a state where only languages 283 * using non-ASCII are enabled. 284 */ 285 public static final int IME_FLAG_FORCE_ASCII = 0x80000000; 286 287 /** 288 * Generic unspecified type for {@link #imeOptions}. 289 */ 290 public static final int IME_NULL = 0x00000000; 291 292 /** 293 * Masks for {@link imeOptions} 294 * 295 * <pre> 296 * |-------|-------|-------|-------| 297 * 1111 IME_MASK_ACTION 298 * |-------|-------|-------|-------| 299 * IME_ACTION_UNSPECIFIED 300 * 1 IME_ACTION_NONE 301 * 1 IME_ACTION_GO 302 * 11 IME_ACTION_SEARCH 303 * 1 IME_ACTION_SEND 304 * 1 1 IME_ACTION_NEXT 305 * 11 IME_ACTION_DONE 306 * 111 IME_ACTION_PREVIOUS 307 * 1 IME_FLAG_NO_PERSONALIZED_LEARNING 308 * 1 IME_FLAG_NO_FULLSCREEN 309 * 1 IME_FLAG_NAVIGATE_PREVIOUS 310 * 1 IME_FLAG_NAVIGATE_NEXT 311 * 1 IME_FLAG_NO_EXTRACT_UI 312 * 1 IME_FLAG_NO_ACCESSORY_ACTION 313 * 1 IME_FLAG_NO_ENTER_ACTION 314 * 1 IME_FLAG_FORCE_ASCII 315 * |-------|-------|-------|-------|</pre> 316 */ 317 318 /** 319 * Extended type information for the editor, to help the IME better 320 * integrate with it. 321 */ 322 public int imeOptions = IME_NULL; 323 324 /** 325 * A string supplying additional information options that are 326 * private to a particular IME implementation. The string must be 327 * scoped to a package owned by the implementation, to ensure there are 328 * no conflicts between implementations, but other than that you can put 329 * whatever you want in it to communicate with the IME. For example, 330 * you could have a string that supplies an argument like 331 * <code>"com.example.myapp.SpecialMode=3"</code>. This field is can be 332 * filled in from the {@link android.R.attr#privateImeOptions} 333 * attribute of a TextView. 334 */ 335 public String privateImeOptions = null; 336 337 /** 338 * In some cases an IME may be able to display an arbitrary label for 339 * a command the user can perform, which you can specify here. This is 340 * typically used as the label for the action to use in-line as a replacement 341 * for the "enter" key (see {@link #actionId}). Remember the key where 342 * this will be displayed is typically very small, and there are significant 343 * localization challenges to make this fit in all supported languages. Also 344 * you can not count absolutely on this being used, as some IMEs may 345 * ignore this. 346 */ 347 public CharSequence actionLabel = null; 348 349 /** 350 * If {@link #actionLabel} has been given, this is the id for that command 351 * when the user presses its button that is delivered back with 352 * {@link InputConnection#performEditorAction(int) 353 * InputConnection.performEditorAction()}. 354 */ 355 public int actionId = 0; 356 357 /** 358 * The text offset of the start of the selection at the time editing 359 * begins; -1 if not known. Keep in mind that, without knowing the cursor 360 * position, many IMEs will not be able to offer their full feature set and 361 * may even behave in unpredictable ways: pass the actual cursor position 362 * here if possible at all. 363 * 364 * <p>Also, this needs to be the cursor position <strong>right now</strong>, 365 * not at some point in the past, even if input is starting in the same text field 366 * as before. When the app is filling this object, input is about to start by 367 * definition, and this value will override any value the app may have passed to 368 * {@link InputMethodManager#updateSelection(android.view.View, int, int, int, int)} 369 * before.</p> 370 */ 371 public int initialSelStart = -1; 372 373 /** 374 * <p>The text offset of the end of the selection at the time editing 375 * begins; -1 if not known. Keep in mind that, without knowing the cursor 376 * position, many IMEs will not be able to offer their full feature set and 377 * may behave in unpredictable ways: pass the actual cursor position 378 * here if possible at all.</p> 379 * 380 * <p>Also, this needs to be the cursor position <strong>right now</strong>, 381 * not at some point in the past, even if input is starting in the same text field 382 * as before. When the app is filling this object, input is about to start by 383 * definition, and this value will override any value the app may have passed to 384 * {@link InputMethodManager#updateSelection(android.view.View, int, int, int, int)} 385 * before.</p> 386 */ 387 public int initialSelEnd = -1; 388 389 /** 390 * The capitalization mode of the first character being edited in the 391 * text. Values may be any combination of 392 * {@link TextUtils#CAP_MODE_CHARACTERS TextUtils.CAP_MODE_CHARACTERS}, 393 * {@link TextUtils#CAP_MODE_WORDS TextUtils.CAP_MODE_WORDS}, and 394 * {@link TextUtils#CAP_MODE_SENTENCES TextUtils.CAP_MODE_SENTENCES}, though 395 * you should generally just take a non-zero value to mean "start out in 396 * caps mode". 397 */ 398 public int initialCapsMode = 0; 399 400 /** 401 * The "hint" text of the text view, typically shown in-line when the 402 * text is empty to tell the user what to enter. 403 */ 404 public CharSequence hintText; 405 406 /** 407 * A label to show to the user describing the text they are writing. 408 */ 409 public CharSequence label; 410 411 /** 412 * Name of the package that owns this editor. 413 * 414 * <p><strong>IME authors:</strong> In API level 22 415 * {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1} and prior, do not trust this package 416 * name. The system had not verified the consistency between the package name here and 417 * application's uid. Consider to use {@link InputBinding#getUid()}, which is trustworthy. 418 * Starting from {@link android.os.Build.VERSION_CODES#M}, the system verifies the consistency 419 * between this package name and application uid before {@link EditorInfo} is passed to the 420 * input method.</p> 421 * 422 * <p><strong>Editor authors:</strong> Starting from {@link android.os.Build.VERSION_CODES#M}, 423 * the application is no longer 424 * able to establish input connections if the package name provided here is inconsistent with 425 * application's uid.</p> 426 */ 427 public String packageName; 428 429 /** 430 * Autofill Id for the field that's currently on focus. 431 * 432 * <p> Marked as hide since it's only used by framework.</p> 433 * @hide 434 */ 435 public AutofillId autofillId; 436 437 /** 438 * Identifier for the editor's field. This is optional, and may be 439 * 0. By default it is filled in with the result of 440 * {@link android.view.View#getId() View.getId()} on the View that 441 * is being edited. 442 */ 443 public int fieldId; 444 445 /** 446 * Additional name for the editor's field. This can supply additional 447 * name information for the field. By default it is null. The actual 448 * contents have no meaning. 449 */ 450 public String fieldName; 451 452 /** 453 * Any extra data to supply to the input method. This is for extended 454 * communication with specific input methods; the name fields in the 455 * bundle should be scoped (such as "com.mydomain.im.SOME_FIELD") so 456 * that they don't conflict with others. This field can be 457 * filled in from the {@link android.R.attr#editorExtras} 458 * attribute of a TextView. 459 */ 460 public Bundle extras; 461 462 /** 463 * List of the languages that the user is supposed to switch to no matter what input method 464 * subtype is currently used. This special "hint" can be used mainly for, but not limited to, 465 * multilingual users who want IMEs to switch language context automatically. 466 * 467 * <p>{@code null} means that no special language "hint" is needed.</p> 468 * 469 * <p><strong>Editor authors:</strong> Specify this only when you are confident that the user 470 * will switch to certain languages in this context no matter what input method subtype is 471 * currently selected. Otherwise, keep this {@code null}. Explicit user actions and/or 472 * preferences would be good signals to specify this special "hint", For example, a chat 473 * application may be able to put the last used language at the top of {@link #hintLocales} 474 * based on whom the user is going to talk, by remembering what language is used in the last 475 * conversation. Do not specify {@link android.widget.TextView#getTextLocales()} only because 476 * it is used for text rendering.</p> 477 * 478 * @see android.widget.TextView#setImeHintLocales(LocaleList) 479 * @see android.widget.TextView#getImeHintLocales() 480 */ 481 @Nullable 482 public LocaleList hintLocales = null; 483 484 485 /** 486 * List of acceptable MIME types for 487 * {@link InputConnection#commitContent(InputContentInfo, int, Bundle)}. 488 * 489 * <p>{@code null} or an empty array means that 490 * {@link InputConnection#commitContent(InputContentInfo, int, Bundle)} is not supported in this 491 * editor.</p> 492 */ 493 @Nullable 494 public String[] contentMimeTypes = null; 495 496 /** 497 * If not {@code null}, this editor needs to talk to IMEs that run for the specified user, no 498 * matter what user ID the calling process has. 499 * 500 * <p>Note: This field will be silently ignored when 501 * {@link com.android.server.inputmethod.InputMethodSystemProperty#MULTI_CLIENT_IME_ENABLED} is 502 * {@code true}.</p> 503 * 504 * <p>Note also that pseudo handles such as {@link UserHandle#ALL} are not supported.</p> 505 * 506 * @hide 507 */ 508 @RequiresPermission(INTERACT_ACROSS_USERS_FULL) 509 @Nullable 510 public UserHandle targetInputMethodUser = null; 511 512 @IntDef({TrimPolicy.HEAD, TrimPolicy.TAIL}) 513 @Retention(RetentionPolicy.SOURCE) 514 @interface TrimPolicy { 515 int HEAD = 0; 516 int TAIL = 1; 517 } 518 519 /** 520 * The maximum length of initialSurroundingText. When the input text from 521 * {@code setInitialSurroundingText(CharSequence)} is longer than this, trimming shall be 522 * performed to keep memory efficiency. 523 */ 524 @VisibleForTesting 525 static final int MEMORY_EFFICIENT_TEXT_LENGTH = 2048; 526 /** 527 * When the input text is longer than {@code #MEMORY_EFFICIENT_TEXT_LENGTH}, we start trimming 528 * the input text into three parts: BeforeCursor, Selection, and AfterCursor. We don't want to 529 * trim the Selection but we also don't want it consumes all available space. Therefore, the 530 * maximum acceptable Selection length is half of {@code #MEMORY_EFFICIENT_TEXT_LENGTH}. 531 */ 532 @VisibleForTesting 533 static final int MAX_INITIAL_SELECTION_LENGTH = MEMORY_EFFICIENT_TEXT_LENGTH / 2; 534 535 @NonNull 536 private InitialSurroundingText mInitialSurroundingText = new InitialSurroundingText(); 537 538 /** 539 * Editors may use this method to provide initial input text to IMEs. As the surrounding text 540 * could be used to provide various input assistance, we recommend editors to provide the 541 * complete initial input text in its {@link View#onCreateInputConnection(EditorInfo)} callback. 542 * The supplied text will then be processed to serve {@code #getInitialTextBeforeCursor}, 543 * {@code #getInitialSelectedText}, and {@code #getInitialTextBeforeCursor}. System is allowed 544 * to trim {@code sourceText} for various reasons while keeping the most valuable data to IMEs. 545 * 546 * <p><strong>Editor authors: </strong>Providing the initial input text helps reducing IPC calls 547 * for IMEs to provide many modern features right after the connection setup. We recommend 548 * calling this method in your implementation. 549 * 550 * @param sourceText The complete input text. 551 */ setInitialSurroundingText(@onNull CharSequence sourceText)552 public void setInitialSurroundingText(@NonNull CharSequence sourceText) { 553 setInitialSurroundingSubText(sourceText, /* subTextStart = */ 0); 554 } 555 556 /** 557 * Editors may use this method to provide initial input text to IMEs. As the surrounding text 558 * could be used to provide various input assistance, we recommend editors to provide the 559 * complete initial input text in its {@link View#onCreateInputConnection(EditorInfo)} callback. 560 * When trimming the input text is needed, call this method instead of 561 * {@code setInitialSurroundingText(CharSequence)} and provide the trimmed position info. Always 562 * try to include the selected text within {@code subText} to give the system best flexibility 563 * to choose where and how to trim {@code subText} when necessary. 564 * 565 * @param subText The input text. When it was trimmed, {@code subTextStart} must be provided 566 * correctly. 567 * @param subTextStart The position that the input text got trimmed. For example, when the 568 * editor wants to trim out the first 10 chars, subTextStart should be 10. 569 */ setInitialSurroundingSubText(@onNull CharSequence subText, int subTextStart)570 public void setInitialSurroundingSubText(@NonNull CharSequence subText, int subTextStart) { 571 CharSequence newSubText = Editable.Factory.getInstance().newEditable(subText); 572 Objects.requireNonNull(newSubText); 573 574 // Swap selection start and end if necessary. 575 final int subTextSelStart = initialSelStart > initialSelEnd 576 ? initialSelEnd - subTextStart : initialSelStart - subTextStart; 577 final int subTextSelEnd = initialSelStart > initialSelEnd 578 ? initialSelStart - subTextStart : initialSelEnd - subTextStart; 579 580 final int subTextLength = newSubText.length(); 581 // Unknown or invalid selection. 582 if (subTextStart < 0 || subTextSelStart < 0 || subTextSelEnd > subTextLength) { 583 mInitialSurroundingText = new InitialSurroundingText(); 584 return; 585 } 586 587 // For privacy protection reason, we don't carry password inputs to IMEs. 588 if (isPasswordInputType(inputType)) { 589 mInitialSurroundingText = new InitialSurroundingText(); 590 return; 591 } 592 593 if (subTextLength <= MEMORY_EFFICIENT_TEXT_LENGTH) { 594 mInitialSurroundingText = new InitialSurroundingText(newSubText, subTextSelStart, 595 subTextSelEnd); 596 return; 597 } 598 599 trimLongSurroundingText(newSubText, subTextSelStart, subTextSelEnd); 600 } 601 602 /** 603 * Trims the initial surrounding text when it is over sized. Fundamental trimming rules are: 604 * - The text before the cursor is the most important information to IMEs. 605 * - The text after the cursor is the second important information to IMEs. 606 * - The selected text is the least important information but it shall NEVER be truncated. When 607 * it is too long, just drop it. 608 *<p><pre> 609 * For example, the subText can be viewed as 610 * TextBeforeCursor + Selection + TextAfterCursor 611 * The result could be 612 * 1. (maybeTrimmedAtHead)TextBeforeCursor + Selection + TextAfterCursor(maybeTrimmedAtTail) 613 * 2. (maybeTrimmedAtHead)TextBeforeCursor + TextAfterCursor(maybeTrimmedAtTail)</pre> 614 * 615 * @param subText The long text that needs to be trimmed. 616 * @param selStart The text offset of the start of the selection. 617 * @param selEnd The text offset of the end of the selection 618 */ trimLongSurroundingText(CharSequence subText, int selStart, int selEnd)619 private void trimLongSurroundingText(CharSequence subText, int selStart, int selEnd) { 620 final int sourceSelLength = selEnd - selStart; 621 // When the selected text is too long, drop it. 622 final int newSelLength = (sourceSelLength > MAX_INITIAL_SELECTION_LENGTH) 623 ? 0 : sourceSelLength; 624 625 // Distribute rest of length quota to TextBeforeCursor and TextAfterCursor in 4:1 ratio. 626 final int subTextBeforeCursorLength = selStart; 627 final int subTextAfterCursorLength = subText.length() - selEnd; 628 final int maxLengthMinusSelection = MEMORY_EFFICIENT_TEXT_LENGTH - newSelLength; 629 final int possibleMaxBeforeCursorLength = 630 Math.min(subTextBeforeCursorLength, (int) (0.8 * maxLengthMinusSelection)); 631 int newAfterCursorLength = Math.min(subTextAfterCursorLength, 632 maxLengthMinusSelection - possibleMaxBeforeCursorLength); 633 int newBeforeCursorLength = Math.min(subTextBeforeCursorLength, 634 maxLengthMinusSelection - newAfterCursorLength); 635 636 // As trimming may happen at the head of TextBeforeCursor, calculate new starting position. 637 int newBeforeCursorHead = subTextBeforeCursorLength - newBeforeCursorLength; 638 639 // We don't want to cut surrogate pairs in the middle. Exam that at the new head and tail. 640 if (isCutOnSurrogate(subText, 641 selStart - newBeforeCursorLength, TrimPolicy.HEAD)) { 642 newBeforeCursorHead = newBeforeCursorHead + 1; 643 newBeforeCursorLength = newBeforeCursorLength - 1; 644 } 645 if (isCutOnSurrogate(subText, 646 selEnd + newAfterCursorLength - 1, TrimPolicy.TAIL)) { 647 newAfterCursorLength = newAfterCursorLength - 1; 648 } 649 650 // Now we know where to trim, compose the initialSurroundingText. 651 final int newTextLength = newBeforeCursorLength + newSelLength + newAfterCursorLength; 652 final CharSequence newInitialSurroundingText; 653 if (newSelLength != sourceSelLength) { 654 final CharSequence beforeCursor = subText.subSequence(newBeforeCursorHead, 655 newBeforeCursorHead + newBeforeCursorLength); 656 final CharSequence afterCursor = subText.subSequence(selEnd, 657 selEnd + newAfterCursorLength); 658 659 newInitialSurroundingText = TextUtils.concat(beforeCursor, afterCursor); 660 } else { 661 newInitialSurroundingText = subText 662 .subSequence(newBeforeCursorHead, newBeforeCursorHead + newTextLength); 663 } 664 665 // As trimming may happen at the head, adjust cursor position in the initialSurroundingText 666 // obj. 667 newBeforeCursorHead = 0; 668 final int newSelHead = newBeforeCursorHead + newBeforeCursorLength; 669 mInitialSurroundingText = new InitialSurroundingText( 670 newInitialSurroundingText, newSelHead, newSelHead + newSelLength); 671 } 672 673 /** 674 * Get <var>length</var> characters of text before the current cursor position. May be 675 * {@code null} when the protocol is not supported. 676 * 677 * @param length The expected length of the text. 678 * @param flags Supplies additional options controlling how the text is returned. May be 679 * either 0 or {@link InputConnection#GET_TEXT_WITH_STYLES}. 680 * @return the text before the cursor position; the length of the returned text might be less 681 * than <var>length</var>. When there is no text before the cursor, an empty string will be 682 * returned. It could also be {@code null} when the editor or system could not support this 683 * protocol. 684 */ 685 @Nullable getInitialTextBeforeCursor(int length, int flags)686 public CharSequence getInitialTextBeforeCursor(int length, int flags) { 687 return mInitialSurroundingText.getInitialTextBeforeCursor(length, flags); 688 } 689 690 /** 691 * Gets the selected text, if any. May be {@code null} when the protocol is not supported or the 692 * selected text is way too long. 693 * 694 * @param flags Supplies additional options controlling how the text is returned. May be 695 * either 0 or {@link InputConnection#GET_TEXT_WITH_STYLES}. 696 * @return the text that is currently selected, if any. It could be an empty string when there 697 * is no text selected. When {@code null} is returned, the selected text might be too long or 698 * this protocol is not supported. 699 */ 700 @Nullable getInitialSelectedText(int flags)701 public CharSequence getInitialSelectedText(int flags) { 702 // Swap selection start and end if necessary. 703 final int correctedTextSelStart = initialSelStart > initialSelEnd 704 ? initialSelEnd : initialSelStart; 705 final int correctedTextSelEnd = initialSelStart > initialSelEnd 706 ? initialSelStart : initialSelEnd; 707 708 final int sourceSelLength = correctedTextSelEnd - correctedTextSelStart; 709 if (initialSelStart < 0 || initialSelEnd < 0 710 || mInitialSurroundingText.getSelectionLength() != sourceSelLength) { 711 return null; 712 } 713 return mInitialSurroundingText.getInitialSelectedText(flags); 714 } 715 716 /** 717 * Get <var>length</var> characters of text after the current cursor position. May be 718 * {@code null} when the protocol is not supported. 719 * 720 * @param length The expected length of the text. 721 * @param flags Supplies additional options controlling how the text is returned. May be 722 * either 0 or {@link InputConnection#GET_TEXT_WITH_STYLES}. 723 * @return the text after the cursor position; the length of the returned text might be less 724 * than <var>length</var>. When there is no text after the cursor, an empty string will be 725 * returned. It could also be {@code null} when the editor or system could not support this 726 * protocol. 727 */ 728 @Nullable getInitialTextAfterCursor(int length, int flags)729 public CharSequence getInitialTextAfterCursor(int length, int flags) { 730 return mInitialSurroundingText.getInitialTextAfterCursor(length, flags); 731 } 732 isCutOnSurrogate(CharSequence sourceText, int cutPosition, @TrimPolicy int policy)733 private static boolean isCutOnSurrogate(CharSequence sourceText, int cutPosition, 734 @TrimPolicy int policy) { 735 switch (policy) { 736 case TrimPolicy.HEAD: 737 return Character.isLowSurrogate(sourceText.charAt(cutPosition)); 738 case TrimPolicy.TAIL: 739 return Character.isHighSurrogate(sourceText.charAt(cutPosition)); 740 default: 741 return false; 742 } 743 } 744 isPasswordInputType(int inputType)745 private static boolean isPasswordInputType(int inputType) { 746 final int variation = 747 inputType & (TYPE_MASK_CLASS | TYPE_MASK_VARIATION); 748 return variation 749 == (TYPE_CLASS_TEXT | TYPE_TEXT_VARIATION_PASSWORD) 750 || variation 751 == (TYPE_CLASS_TEXT | TYPE_TEXT_VARIATION_WEB_PASSWORD) 752 || variation 753 == (TYPE_CLASS_NUMBER | TYPE_NUMBER_VARIATION_PASSWORD); 754 } 755 756 /** 757 * Ensure that the data in this EditorInfo is compatible with an application 758 * that was developed against the given target API version. This can 759 * impact the following input types: 760 * {@link InputType#TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS}, 761 * {@link InputType#TYPE_TEXT_VARIATION_WEB_PASSWORD}, 762 * {@link InputType#TYPE_NUMBER_VARIATION_NORMAL}, 763 * {@link InputType#TYPE_NUMBER_VARIATION_PASSWORD}. 764 * 765 * <p>This is called by the framework for input method implementations; 766 * you should not generally need to call it yourself. 767 * 768 * @param targetSdkVersion The API version number that the compatible 769 * application was developed against. 770 */ makeCompatible(int targetSdkVersion)771 public final void makeCompatible(int targetSdkVersion) { 772 if (targetSdkVersion < android.os.Build.VERSION_CODES.HONEYCOMB) { 773 switch (inputType&(TYPE_MASK_CLASS|TYPE_MASK_VARIATION)) { 774 case TYPE_CLASS_TEXT|TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS: 775 inputType = TYPE_CLASS_TEXT|TYPE_TEXT_VARIATION_EMAIL_ADDRESS 776 | (inputType&TYPE_MASK_FLAGS); 777 break; 778 case TYPE_CLASS_TEXT|TYPE_TEXT_VARIATION_WEB_PASSWORD: 779 inputType = TYPE_CLASS_TEXT|TYPE_TEXT_VARIATION_PASSWORD 780 | (inputType&TYPE_MASK_FLAGS); 781 break; 782 case TYPE_CLASS_NUMBER|TYPE_NUMBER_VARIATION_NORMAL: 783 case TYPE_CLASS_NUMBER|TYPE_NUMBER_VARIATION_PASSWORD: 784 inputType = TYPE_CLASS_NUMBER 785 | (inputType&TYPE_MASK_FLAGS); 786 break; 787 } 788 } 789 } 790 791 /** 792 * Write debug output of this object. 793 */ dump(Printer pw, String prefix)794 public void dump(Printer pw, String prefix) { 795 pw.println(prefix + "inputType=0x" + Integer.toHexString(inputType) 796 + " imeOptions=0x" + Integer.toHexString(imeOptions) 797 + " privateImeOptions=" + privateImeOptions); 798 pw.println(prefix + "actionLabel=" + actionLabel 799 + " actionId=" + actionId); 800 pw.println(prefix + "initialSelStart=" + initialSelStart 801 + " initialSelEnd=" + initialSelEnd 802 + " initialCapsMode=0x" 803 + Integer.toHexString(initialCapsMode)); 804 pw.println(prefix + "hintText=" + hintText 805 + " label=" + label); 806 pw.println(prefix + "packageName=" + packageName 807 + " autofillId=" + autofillId 808 + " fieldId=" + fieldId 809 + " fieldName=" + fieldName); 810 pw.println(prefix + "extras=" + extras); 811 pw.println(prefix + "hintLocales=" + hintLocales); 812 pw.println(prefix + "contentMimeTypes=" + Arrays.toString(contentMimeTypes)); 813 if (targetInputMethodUser != null) { 814 pw.println(prefix + "targetInputMethodUserId=" + targetInputMethodUser.getIdentifier()); 815 } 816 } 817 818 /** 819 * Used to package this object into a {@link Parcel}. 820 * 821 * @param dest The {@link Parcel} to be written. 822 * @param flags The flags used for parceling. 823 */ writeToParcel(Parcel dest, int flags)824 public void writeToParcel(Parcel dest, int flags) { 825 dest.writeInt(inputType); 826 dest.writeInt(imeOptions); 827 dest.writeString(privateImeOptions); 828 TextUtils.writeToParcel(actionLabel, dest, flags); 829 dest.writeInt(actionId); 830 dest.writeInt(initialSelStart); 831 dest.writeInt(initialSelEnd); 832 dest.writeInt(initialCapsMode); 833 TextUtils.writeToParcel(hintText, dest, flags); 834 TextUtils.writeToParcel(label, dest, flags); 835 dest.writeString(packageName); 836 dest.writeParcelable(autofillId, flags); 837 dest.writeInt(fieldId); 838 dest.writeString(fieldName); 839 dest.writeBundle(extras); 840 mInitialSurroundingText.writeToParcel(dest, flags); 841 if (hintLocales != null) { 842 hintLocales.writeToParcel(dest, flags); 843 } else { 844 LocaleList.getEmptyLocaleList().writeToParcel(dest, flags); 845 } 846 dest.writeStringArray(contentMimeTypes); 847 UserHandle.writeToParcel(targetInputMethodUser, dest); 848 } 849 850 /** 851 * Used to make this class parcelable. 852 */ 853 public static final @android.annotation.NonNull Parcelable.Creator<EditorInfo> CREATOR = 854 new Parcelable.Creator<EditorInfo>() { 855 public EditorInfo createFromParcel(Parcel source) { 856 EditorInfo res = new EditorInfo(); 857 res.inputType = source.readInt(); 858 res.imeOptions = source.readInt(); 859 res.privateImeOptions = source.readString(); 860 res.actionLabel = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source); 861 res.actionId = source.readInt(); 862 res.initialSelStart = source.readInt(); 863 res.initialSelEnd = source.readInt(); 864 res.initialCapsMode = source.readInt(); 865 res.hintText = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source); 866 res.label = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source); 867 res.packageName = source.readString(); 868 res.autofillId = source.readParcelable(AutofillId.class.getClassLoader()); 869 res.fieldId = source.readInt(); 870 res.fieldName = source.readString(); 871 res.extras = source.readBundle(); 872 InitialSurroundingText initialSurroundingText = 873 InitialSurroundingText.CREATOR.createFromParcel(source); 874 res.mInitialSurroundingText = initialSurroundingText; 875 LocaleList hintLocales = LocaleList.CREATOR.createFromParcel(source); 876 res.hintLocales = hintLocales.isEmpty() ? null : hintLocales; 877 res.contentMimeTypes = source.readStringArray(); 878 res.targetInputMethodUser = UserHandle.readFromParcel(source); 879 return res; 880 } 881 882 public EditorInfo[] newArray(int size) { 883 return new EditorInfo[size]; 884 } 885 }; 886 describeContents()887 public int describeContents() { 888 return 0; 889 } 890 891 static final class InitialSurroundingText implements Parcelable { 892 @Nullable final CharSequence mSurroundingText; 893 final int mSelectionHead; 894 final int mSelectionEnd; 895 InitialSurroundingText()896 InitialSurroundingText() { 897 mSurroundingText = null; 898 mSelectionHead = 0; 899 mSelectionEnd = 0; 900 } 901 InitialSurroundingText(@ullable CharSequence surroundingText, int selectionHead, int selectionEnd)902 InitialSurroundingText(@Nullable CharSequence surroundingText, int selectionHead, 903 int selectionEnd) { 904 mSurroundingText = surroundingText; 905 mSelectionHead = selectionHead; 906 mSelectionEnd = selectionEnd; 907 } 908 909 @Nullable getInitialTextBeforeCursor(int n, int flags)910 private CharSequence getInitialTextBeforeCursor(int n, int flags) { 911 if (mSurroundingText == null) { 912 return null; 913 } 914 915 final int length = Math.min(n, mSelectionHead); 916 return ((flags & InputConnection.GET_TEXT_WITH_STYLES) != 0) 917 ? mSurroundingText.subSequence(mSelectionHead - length, mSelectionHead) 918 : TextUtils.substring(mSurroundingText, mSelectionHead - length, 919 mSelectionHead); 920 } 921 922 @Nullable getInitialSelectedText(int flags)923 private CharSequence getInitialSelectedText(int flags) { 924 if (mSurroundingText == null) { 925 return null; 926 } 927 928 return ((flags & InputConnection.GET_TEXT_WITH_STYLES) != 0) 929 ? mSurroundingText.subSequence(mSelectionHead, mSelectionEnd) 930 : TextUtils.substring(mSurroundingText, mSelectionHead, mSelectionEnd); 931 } 932 933 @Nullable getInitialTextAfterCursor(int n, int flags)934 private CharSequence getInitialTextAfterCursor(int n, int flags) { 935 if (mSurroundingText == null) { 936 return null; 937 } 938 939 final int length = Math.min(n, mSurroundingText.length() - mSelectionEnd); 940 return ((flags & InputConnection.GET_TEXT_WITH_STYLES) != 0) 941 ? mSurroundingText.subSequence(mSelectionEnd, mSelectionEnd + length) 942 : TextUtils.substring(mSurroundingText, mSelectionEnd, mSelectionEnd + length); 943 } 944 getSelectionLength()945 private int getSelectionLength() { 946 return mSelectionEnd - mSelectionHead; 947 } 948 949 @Override describeContents()950 public int describeContents() { 951 return 0; 952 } 953 954 @Override writeToParcel(Parcel dest, int flags)955 public void writeToParcel(Parcel dest, int flags) { 956 TextUtils.writeToParcel(mSurroundingText, dest, flags); 957 dest.writeInt(mSelectionHead); 958 dest.writeInt(mSelectionEnd); 959 } 960 961 public static final @android.annotation.NonNull Parcelable.Creator<InitialSurroundingText> 962 CREATOR = new Parcelable.Creator<InitialSurroundingText>() { 963 @Override 964 public InitialSurroundingText createFromParcel(Parcel source) { 965 final CharSequence initialText = 966 TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(source); 967 final int selectionHead = source.readInt(); 968 final int selectionEnd = source.readInt(); 969 970 return new InitialSurroundingText(initialText, selectionHead, selectionEnd); 971 } 972 973 @Override 974 public InitialSurroundingText[] newArray(int size) { 975 return new InitialSurroundingText[size]; 976 } 977 }; 978 } 979 } 980