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