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