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