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