• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2007 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 android.annotation.IntDef;
20 import android.annotation.IntRange;
21 import android.annotation.NonNull;
22 import android.annotation.Nullable;
23 import android.inputmethodservice.InputMethodService;
24 import android.os.Bundle;
25 import android.os.Handler;
26 import android.text.TextUtils;
27 import android.view.KeyCharacterMap;
28 import android.view.KeyEvent;
29 
30 import com.android.internal.util.Preconditions;
31 
32 import java.lang.annotation.Retention;
33 import java.lang.annotation.RetentionPolicy;
34 
35 /**
36  * The InputConnection interface is the communication channel from an
37  * {@link InputMethod} back to the application that is receiving its
38  * input. It is used to perform such things as reading text around the
39  * cursor, committing text to the text box, and sending raw key events
40  * to the application.
41  *
42  * <p>Starting from API Level {@link android.os.Build.VERSION_CODES#N},
43  * the system can deal with the situation where the application directly
44  * implements this class but one or more of the following methods are
45  * not implemented.</p>
46  * <ul>
47  *     <li>{@link #getSelectedText(int)}, which was introduced in
48  *     {@link android.os.Build.VERSION_CODES#GINGERBREAD}.</li>
49  *     <li>{@link #setComposingRegion(int, int)}, which was introduced
50  *     in {@link android.os.Build.VERSION_CODES#GINGERBREAD}.</li>
51  *     <li>{@link #commitCorrection(CorrectionInfo)}, which was introduced
52  *     in {@link android.os.Build.VERSION_CODES#HONEYCOMB}.</li>
53  *     <li>{@link #requestCursorUpdates(int)}, which was introduced in
54  *     {@link android.os.Build.VERSION_CODES#LOLLIPOP}.</li>
55  *     <li>{@link #deleteSurroundingTextInCodePoints(int, int)}, which
56  *     was introduced in {@link android.os.Build.VERSION_CODES#N}.</li>
57  *     <li>{@link #getHandler()}, which was introduced in
58  *     {@link android.os.Build.VERSION_CODES#N}.</li>
59  *     <li>{@link #closeConnection()}, which was introduced in
60  *     {@link android.os.Build.VERSION_CODES#N}.</li>
61  *     <li>{@link #commitContent(InputContentInfo, int, Bundle)}, which was
62  *     introduced in {@link android.os.Build.VERSION_CODES#N_MR1}.</li>
63  * </ul>
64  *
65  * <h3>Implementing an IME or an editor</h3>
66  * <p>Text input is the result of the synergy of two essential components:
67  * an Input Method Engine (IME) and an editor. The IME can be a
68  * software keyboard, a handwriting interface, an emoji palette, a
69  * speech-to-text engine, and so on. There are typically several IMEs
70  * installed on any given Android device. In Android, IMEs extend
71  * {@link android.inputmethodservice.InputMethodService}.
72  * For more information about how to create an IME, see the
73  * <a href="{@docRoot}guide/topics/text/creating-input-method.html">
74  * Creating an input method</a> guide.
75  *
76  * The editor is the component that receives text and displays it.
77  * Typically, this is an {@link android.widget.EditText} instance, but
78  * some applications may choose to implement their own editor for
79  * various reasons. This is a large and complicated task, and an
80  * application that does this needs to make sure the behavior is
81  * consistent with standard EditText behavior in Android. An editor
82  * needs to interact with the IME, receiving commands through
83  * this InputConnection interface, and sending commands through
84  * {@link android.view.inputmethod.InputMethodManager}. An editor
85  * should start by implementing
86  * {@link android.view.View#onCreateInputConnection(EditorInfo)}
87  * to return its own input connection.</p>
88  *
89  * <p>If you are implementing your own IME, you will need to call the
90  * methods in this interface to interact with the application. Be sure
91  * to test your IME with a wide range of applications, including
92  * browsers and rich text editors, as some may have peculiarities you
93  * need to deal with. Remember your IME may not be the only source of
94  * changes on the text, and try to be as conservative as possible in
95  * the data you send and as liberal as possible in the data you
96  * receive.</p>
97  *
98  * <p>If you are implementing your own editor, you will probably need
99  * to provide your own subclass of {@link BaseInputConnection} to
100  * answer to the commands from IMEs. Please be sure to test your
101  * editor with as many IMEs as you can as their behavior can vary a
102  * lot. Also be sure to test with various languages, including CJK
103  * languages and right-to-left languages like Arabic, as these may
104  * have different input requirements. When in doubt about the
105  * behavior you should adopt for a particular call, please mimic the
106  * default TextView implementation in the latest Android version, and
107  * if you decide to drift from it, please consider carefully that
108  * inconsistencies in text editor behavior is almost universally felt
109  * as a bad thing by users.</p>
110  *
111  * <h3>Cursors, selections and compositions</h3>
112  * <p>In Android, the cursor and the selection are one and the same
113  * thing. A "cursor" is just the special case of a zero-sized
114  * selection. As such, this documentation uses them
115  * interchangeably. Any method acting "before the cursor" would act
116  * before the start of the selection if there is one, and any method
117  * acting "after the cursor" would act after the end of the
118  * selection.</p>
119  *
120  * <p>An editor needs to be able to keep track of a currently
121  * "composing" region, like the standard edition widgets do. The
122  * composition is marked in a specific style: see
123  * {@link android.text.Spanned#SPAN_COMPOSING}. IMEs use this to help
124  * the user keep track of what part of the text they are currently
125  * focusing on, and interact with the editor using
126  * {@link InputConnection#setComposingText(CharSequence, int)},
127  * {@link InputConnection#setComposingRegion(int, int)} and
128  * {@link InputConnection#finishComposingText()}.
129  * The composing region and the selection are completely independent
130  * of each other, and the IME may use them however they see fit.</p>
131  */
132 public interface InputConnection {
133     /** @hide */
134     @IntDef(flag = true, prefix = { "GET_TEXT_" }, value = {
135             GET_TEXT_WITH_STYLES,
136     })
137     @Retention(RetentionPolicy.SOURCE)
138     @interface GetTextType {}
139 
140     /**
141      * Flag for use with {@link #getTextAfterCursor}, {@link #getTextBeforeCursor} and
142      * {@link #getSurroundingText} to have style information returned along with the text. If not
143      * set, {@link #getTextAfterCursor} sends only the raw text, without style or other spans. If
144      * set, it may return a complex CharSequence of both text and style spans.
145      * <strong>Editor authors</strong>: you should strive to send text with styles if possible, but
146      * it is not required.
147      */
148     int GET_TEXT_WITH_STYLES = 0x0001;
149 
150     /**
151      * Flag for use with {@link #getExtractedText} to indicate you
152      * would like to receive updates when the extracted text changes.
153      */
154     int GET_EXTRACTED_TEXT_MONITOR = 0x0001;
155 
156     /**
157      * Get <var>n</var> characters of text before the current cursor
158      * position.
159      *
160      * <p>This method may fail either if the input connection has
161      * become invalid (such as its process crashing) or the editor is
162      * taking too long to respond with the text (it is given a couple
163      * seconds to return). In either case, null is returned. This
164      * method does not affect the text in the editor in any way, nor
165      * does it affect the selection or composing spans.</p>
166      *
167      * <p>If {@link #GET_TEXT_WITH_STYLES} is supplied as flags, the
168      * editor should return a {@link android.text.SpannableString}
169      * with all the spans set on the text.</p>
170      *
171      * <p><strong>IME authors:</strong> please consider this will
172      * trigger an IPC round-trip that will take some time. Assume this
173      * method consumes a lot of time. Also, please keep in mind the
174      * Editor may choose to return less characters than requested even
175      * if they are available for performance reasons. If you are using
176      * this to get the initial text around the cursor, you may consider
177      * using {@link EditorInfo#getInitialTextBeforeCursor(int, int)},
178      * {@link EditorInfo#getInitialSelectedText(int)}, and
179      * {@link EditorInfo#getInitialTextAfterCursor(int, int)} to prevent IPC costs.</p>
180      *
181      * <p><strong>Editor authors:</strong> please be careful of race
182      * conditions in implementing this call. An IME can make a change
183      * to the text and use this method right away; you need to make
184      * sure the returned value is consistent with the result of the
185      * latest edits. Also, you may return less than n characters if performance
186      * dictates so, but keep in mind IMEs are relying on this for many
187      * functions: you should not, for example, limit the returned value to
188      * the current line, and specifically do not return 0 characters unless
189      * the cursor is really at the start of the text.</p>
190      *
191      * @param n The expected length of the text. This must be non-negative.
192      * @param flags Supplies additional options controlling how the text is
193      * returned. May be either {@code 0} or {@link #GET_TEXT_WITH_STYLES}.
194      * @return the text before the cursor position; the length of the
195      * returned text might be less than <var>n</var>.
196      * @throws IllegalArgumentException if {@code n} is negative.
197      */
198     @Nullable
getTextBeforeCursor(@ntRangefrom = 0) int n, int flags)199     CharSequence getTextBeforeCursor(@IntRange(from = 0) int n, int flags);
200 
201     /**
202      * Get <var>n</var> characters of text after the current cursor
203      * position.
204      *
205      * <p>This method may fail either if the input connection has
206      * become invalid (such as its process crashing) or the client is
207      * taking too long to respond with the text (it is given a couple
208      * seconds to return). In either case, null is returned.
209      *
210      * <p>This method does not affect the text in the editor in any
211      * way, nor does it affect the selection or composing spans.</p>
212      *
213      * <p>If {@link #GET_TEXT_WITH_STYLES} is supplied as flags, the
214      * editor should return a {@link android.text.SpannableString}
215      * with all the spans set on the text.</p>
216      *
217      * <p><strong>IME authors:</strong> please consider this will
218      * trigger an IPC round-trip that will take some time. Assume this
219      * method consumes a lot of time. If you are using this to get the
220      * initial text around the cursor, you may consider using
221      * {@link EditorInfo#getInitialTextBeforeCursor(int, int)},
222      * {@link EditorInfo#getInitialSelectedText(int)}, and
223      * {@link EditorInfo#getInitialTextAfterCursor(int, int)} to prevent IPC costs.</p>
224      *
225      * <p><strong>Editor authors:</strong> please be careful of race
226      * conditions in implementing this call. An IME can make a change
227      * to the text and use this method right away; you need to make
228      * sure the returned value is consistent with the result of the
229      * latest edits. Also, you may return less than n characters if performance
230      * dictates so, but keep in mind IMEs are relying on this for many
231      * functions: you should not, for example, limit the returned value to
232      * the current line, and specifically do not return 0 characters unless
233      * the cursor is really at the end of the text.</p>
234      *
235      * @param n The expected length of the text. This must be non-negative.
236      * @param flags Supplies additional options controlling how the text is
237      * returned. May be either {@code 0} or {@link #GET_TEXT_WITH_STYLES}.
238      *
239      * @return the text after the cursor position; the length of the
240      * returned text might be less than <var>n</var>.
241      * @throws IllegalArgumentException if {@code n} is negative.
242      */
243     @Nullable
getTextAfterCursor(@ntRangefrom = 0) int n, int flags)244     CharSequence getTextAfterCursor(@IntRange(from = 0) int n, int flags);
245 
246     /**
247      * Gets the selected text, if any.
248      *
249      * <p>This method may fail if either the input connection has
250      * become invalid (such as its process crashing) or the client is
251      * taking too long to respond with the text (it is given a couple
252      * of seconds to return). In either case, null is returned.</p>
253      *
254      * <p>This method must not cause any changes in the editor's
255      * state.</p>
256      *
257      * <p>If {@link #GET_TEXT_WITH_STYLES} is supplied as flags, the
258      * editor should return a {@link android.text.SpannableString}
259      * with all the spans set on the text.</p>
260      *
261      * <p><strong>IME authors:</strong> please consider this will
262      * trigger an IPC round-trip that will take some time. Assume this
263      * method consumes a lot of time. If you are using this to get the
264      * initial text around the cursor, you may consider using
265      * {@link EditorInfo#getInitialTextBeforeCursor(int, int)},
266      * {@link EditorInfo#getInitialSelectedText(int)}, and
267      * {@link EditorInfo#getInitialTextAfterCursor(int, int)} to prevent IPC costs.</p>
268      *
269      * <p><strong>Editor authors:</strong> please be careful of race
270      * conditions in implementing this call. An IME can make a change
271      * to the text or change the selection position and use this
272      * method right away; you need to make sure the returned value is
273      * consistent with the results of the latest edits.</p>
274      *
275      * @param flags Supplies additional options controlling how the text is
276      * returned. May be either {@code 0} or {@link #GET_TEXT_WITH_STYLES}.
277      * @return the text that is currently selected, if any, or {@code null} if no text is selected.
278      */
getSelectedText(int flags)279     CharSequence getSelectedText(int flags);
280 
281     /**
282      * Gets the surrounding text around the current cursor, with <var>beforeLength</var> characters
283      * of text before the cursor (start of the selection), <var>afterLength</var> characters of text
284      * after the cursor (end of the selection), and all of the selected text. The range are for java
285      * characters, not glyphs that can be multiple characters.
286      *
287      * <p>This method may fail either if the input connection has become invalid (such as its
288      * process crashing), or the client is taking too long to respond with the text (it is given a
289      * couple seconds to return), or the protocol is not supported. In any of these cases, null is
290      * returned.
291      *
292      * <p>This method does not affect the text in the editor in any way, nor does it affect the
293      * selection or composing spans.</p>
294      *
295      * <p>If {@link #GET_TEXT_WITH_STYLES} is supplied as flags, the editor should return a
296      * {@link android.text.Spanned} with all the spans set on the text.</p>
297      *
298      * <p><strong>IME authors:</strong> please consider this will trigger an IPC round-trip that
299      * will take some time. Assume this method consumes a lot of time. If you are using this to get
300      * the initial surrounding text around the cursor, you may consider using
301      * {@link EditorInfo#getInitialTextBeforeCursor(int, int)},
302      * {@link EditorInfo#getInitialSelectedText(int)}, and
303      * {@link EditorInfo#getInitialTextAfterCursor(int, int)} to prevent IPC costs.</p>
304      *
305      * @param beforeLength The expected length of the text before the cursor.
306      * @param afterLength The expected length of the text after the cursor.
307      * @param flags Supplies additional options controlling how the text is returned. May be either
308      *              {@code 0} or {@link #GET_TEXT_WITH_STYLES}.
309      * @return an {@link android.view.inputmethod.SurroundingText} object describing the surrounding
310      * text and state of selection, or null if the input connection is no longer valid, or the
311      * editor can't comply with the request for some reason, or the application does not implement
312      * this method. The length of the returned text might be less than the sum of
313      * <var>beforeLength</var> and <var>afterLength</var> .
314      * @throws IllegalArgumentException if {@code beforeLength} or {@code afterLength} is negative.
315      */
316     @Nullable
getSurroundingText( @ntRangefrom = 0) int beforeLength, @IntRange(from = 0) int afterLength, @GetTextType int flags)317     default SurroundingText getSurroundingText(
318             @IntRange(from = 0) int beforeLength, @IntRange(from = 0) int afterLength,
319             @GetTextType int flags) {
320         Preconditions.checkArgumentNonnegative(beforeLength);
321         Preconditions.checkArgumentNonnegative(afterLength);
322 
323         CharSequence textBeforeCursor = getTextBeforeCursor(beforeLength, flags);
324         if (textBeforeCursor == null) {
325             return null;
326         }
327         CharSequence textAfterCursor = getTextAfterCursor(afterLength, flags);
328         if (textAfterCursor == null) {
329             return null;
330         }
331         CharSequence selectedText = getSelectedText(flags);
332         if (selectedText == null) {
333             selectedText = "";
334         }
335         CharSequence surroundingText =
336                 TextUtils.concat(textBeforeCursor, selectedText, textAfterCursor);
337         return new SurroundingText(surroundingText, textBeforeCursor.length(),
338                 textBeforeCursor.length() + selectedText.length(), -1);
339     }
340 
341     /**
342      * Retrieve the current capitalization mode in effect at the
343      * current cursor position in the text. See
344      * {@link android.text.TextUtils#getCapsMode TextUtils.getCapsMode}
345      * for more information.
346      *
347      * <p>This method may fail either if the input connection has
348      * become invalid (such as its process crashing) or the client is
349      * taking too long to respond with the text (it is given a couple
350      * seconds to return). In either case, 0 is returned.</p>
351      *
352      * <p>This method does not affect the text in the editor in any
353      * way, nor does it affect the selection or composing spans.</p>
354      *
355      * <p><strong>Editor authors:</strong> please be careful of race
356      * conditions in implementing this call. An IME can change the
357      * cursor position and use this method right away; you need to make
358      * sure the returned value is consistent with the results of the
359      * latest edits and changes to the cursor position.</p>
360      *
361      * @param reqModes The desired modes to retrieve, as defined by
362      * {@link android.text.TextUtils#getCapsMode TextUtils.getCapsMode}. These
363      * constants are defined so that you can simply pass the current
364      * {@link EditorInfo#inputType TextBoxAttribute.contentType} value
365      * directly in to here.
366      * @return the caps mode flags that are in effect at the current
367      * cursor position. See TYPE_TEXT_FLAG_CAPS_* in {@link android.text.InputType}.
368      */
getCursorCapsMode(int reqModes)369     int getCursorCapsMode(int reqModes);
370 
371     /**
372      * Retrieve the current text in the input connection's editor, and
373      * monitor for any changes to it. This function returns with the
374      * current text, and optionally the input connection can send
375      * updates to the input method when its text changes.
376      *
377      * <p>This method may fail either if the input connection has
378      * become invalid (such as its process crashing) or the client is
379      * taking too long to respond with the text (it is given a couple
380      * seconds to return). In either case, null is returned.</p>
381      *
382      * <p>Editor authors: as a general rule, try to comply with the
383      * fields in <code>request</code> for how many chars to return,
384      * but if performance or convenience dictates otherwise, please
385      * feel free to do what is most appropriate for your case. Also,
386      * if the
387      * {@link #GET_EXTRACTED_TEXT_MONITOR} flag is set, you should be
388      * calling
389      * {@link InputMethodManager#updateExtractedText(View, int, ExtractedText)}
390      * whenever you call
391      * {@link InputMethodManager#updateSelection(View, int, int, int, int)}.</p>
392      *
393      * @param request Description of how the text should be returned.
394      * {@link android.view.inputmethod.ExtractedTextRequest}
395      * @param flags Additional options to control the client, either {@code 0} or
396      * {@link #GET_EXTRACTED_TEXT_MONITOR}.
397 
398      * @return an {@link android.view.inputmethod.ExtractedText}
399      * object describing the state of the text view and containing the
400      * extracted text itself, or null if the input connection is no
401      * longer valid of the editor can't comply with the request for
402      * some reason.
403      */
getExtractedText(ExtractedTextRequest request, int flags)404     ExtractedText getExtractedText(ExtractedTextRequest request, int flags);
405 
406     /**
407      * Delete <var>beforeLength</var> characters of text before the
408      * current cursor position, and delete <var>afterLength</var>
409      * characters of text after the current cursor position, excluding
410      * the selection. Before and after refer to the order of the
411      * characters in the string, not to their visual representation:
412      * this means you don't have to figure out the direction of the
413      * text and can just use the indices as-is.
414      *
415      * <p>The lengths are supplied in Java chars, not in code points
416      * or in glyphs.</p>
417      *
418      * <p>Since this method only operates on text before and after the
419      * selection, it can't affect the contents of the selection. This
420      * may affect the composing span if the span includes characters
421      * that are to be deleted, but otherwise will not change it. If
422      * some characters in the composing span are deleted, the
423      * composing span will persist but get shortened by however many
424      * chars inside it have been removed.</p>
425      *
426      * <p><strong>IME authors:</strong> please be careful not to
427      * delete only half of a surrogate pair. Also take care not to
428      * delete more characters than are in the editor, as that may have
429      * ill effects on the application. Calling this method will cause
430      * the editor to call
431      * {@link android.inputmethodservice.InputMethodService#onUpdateSelection(int, int, int, int,
432      * int, int)} on your service after the batch input is over.</p>
433      *
434      * <p><strong>Editor authors:</strong> please be careful of race
435      * conditions in implementing this call. An IME can make a change
436      * to the text or change the selection position and use this
437      * method right away; you need to make sure the effects are
438      * consistent with the results of the latest edits. Also, although
439      * the IME should not send lengths bigger than the contents of the
440      * string, you should check the values for overflows and trim the
441      * indices to the size of the contents to avoid crashes. Since
442      * this changes the contents of the editor, you need to make the
443      * changes known to the input method by calling
444      * {@link InputMethodManager#updateSelection(View, int, int, int, int)},
445      * but be careful to wait until the batch edit is over if one is
446      * in progress.</p>
447      *
448      * @param beforeLength The number of characters before the cursor to be deleted, in code unit.
449      *        If this is greater than the number of existing characters between the beginning of the
450      *        text and the cursor, then this method does not fail but deletes all the characters in
451      *        that range.
452      * @param afterLength The number of characters after the cursor to be deleted, in code unit.
453      *        If this is greater than the number of existing characters between the cursor and
454      *        the end of the text, then this method does not fail but deletes all the characters in
455      *        that range.
456      * @return true on success, false if the input connection is no longer valid.
457      */
deleteSurroundingText(int beforeLength, int afterLength)458     boolean deleteSurroundingText(int beforeLength, int afterLength);
459 
460     /**
461      * A variant of {@link #deleteSurroundingText(int, int)}. Major differences are:
462      *
463      * <ul>
464      *     <li>The lengths are supplied in code points, not in Java chars or in glyphs.</>
465      *     <li>This method does nothing if there are one or more invalid surrogate pairs in the
466      *     requested range.</li>
467      * </ul>
468      *
469      * <p><strong>Editor authors:</strong> In addition to the requirement in
470      * {@link #deleteSurroundingText(int, int)}, make sure to do nothing when one ore more invalid
471      * surrogate pairs are found in the requested range.</p>
472      *
473      * @see #deleteSurroundingText(int, int)
474      *
475      * @param beforeLength The number of characters before the cursor to be deleted, in code points.
476      *        If this is greater than the number of existing characters between the beginning of the
477      *        text and the cursor, then this method does not fail but deletes all the characters in
478      *        that range.
479      * @param afterLength The number of characters after the cursor to be deleted, in code points.
480      *        If this is greater than the number of existing characters between the cursor and
481      *        the end of the text, then this method does not fail but deletes all the characters in
482      *        that range.
483      * @return {@code true} on success, {@code false} if the input connection is no longer valid.
484      *         Before Android {@link android.os.Build.VERSION_CODES#TIRAMISU}, this API returned
485      *         {@code false} when the target application does not implement this method.
486      */
deleteSurroundingTextInCodePoints(int beforeLength, int afterLength)487     boolean deleteSurroundingTextInCodePoints(int beforeLength, int afterLength);
488 
489     /**
490      * Replace the currently composing text with the given text, and
491      * set the new cursor position. Any composing text set previously
492      * will be removed automatically.
493      *
494      * <p>If there is any composing span currently active, all
495      * characters that it comprises are removed. The passed text is
496      * added in its place, and a composing span is added to this
497      * text. If there is no composing span active, the passed text is
498      * added at the cursor position (removing selected characters
499      * first if any), and a composing span is added on the new text.
500      * Finally, the cursor is moved to the location specified by
501      * <code>newCursorPosition</code>.</p>
502      *
503      * <p>This is usually called by IMEs to add or remove or change
504      * characters in the composing span. Calling this method will
505      * cause the editor to call
506      * {@link android.inputmethodservice.InputMethodService#onUpdateSelection(int, int, int, int,
507      * int, int)} on the current IME after the batch input is over.</p>
508      *
509      * <p><strong>Editor authors:</strong> please keep in mind the
510      * text may be very similar or completely different than what was
511      * in the composing span at call time, or there may not be a
512      * composing span at all. Please note that although it's not
513      * typical use, the string may be empty. Treat this normally,
514      * replacing the currently composing text with an empty string.
515      * Also, be careful with the cursor position. IMEs rely on this
516      * working exactly as described above. Since this changes the
517      * contents of the editor, you need to make the changes known to
518      * the input method by calling
519      * {@link InputMethodManager#updateSelection(View, int, int, int, int)},
520      * but be careful to wait until the batch edit is over if one is
521      * in progress. Note that this method can set the cursor position
522      * on either edge of the composing text or entirely outside it,
523      * but the IME may also go on to move the cursor position to
524      * within the composing text in a subsequent call so you should
525      * make no assumption at all: the composing text and the selection
526      * are entirely independent.</p>
527      *
528      * @param text The composing text with styles if necessary. If no style
529      *        object attached to the text, the default style for composing text
530      *        is used. See {@link android.text.Spanned} for how to attach style
531      *        object to the text. {@link android.text.SpannableString} and
532      *        {@link android.text.SpannableStringBuilder} are two
533      *        implementations of the interface {@link android.text.Spanned}.
534      * @param newCursorPosition The new cursor position around the text. If
535      *        > 0, this is relative to the end of the text - 1; if <= 0, this
536      *        is relative to the start of the text. So a value of 1 will
537      *        always advance you to the position after the full text being
538      *        inserted. Note that this means you can't position the cursor
539      *        within the text, because the editor can make modifications to
540      *        the text you are providing so it is not possible to correctly
541      *        specify locations there.
542      * @return true on success, false if the input connection is no longer
543      * valid.
544      */
setComposingText(CharSequence text, int newCursorPosition)545     boolean setComposingText(CharSequence text, int newCursorPosition);
546 
547     /**
548      * The variant of {@link #setComposingText(CharSequence, int)}. This method is
549      * used to allow the IME to provide extra information while setting up composing text.
550      *
551      * @param text The composing text with styles if necessary. If no style
552      *        object attached to the text, the default style for composing text
553      *        is used. See {@link android.text.Spanned} for how to attach style
554      *        object to the text. {@link android.text.SpannableString} and
555      *        {@link android.text.SpannableStringBuilder} are two
556      *        implementations of the interface {@link android.text.Spanned}.
557      * @param newCursorPosition The new cursor position around the text. If
558      *        > 0, this is relative to the end of the text - 1; if <= 0, this
559      *        is relative to the start of the text. So a value of 1 will
560      *        always advance you to the position after the full text being
561      *        inserted. Note that this means you can't position the cursor
562      *        within the text, because the editor can make modifications to
563      *        the text you are providing so it is not possible to correctly
564      *        specify locations there.
565      * @param textAttribute The extra information about the text.
566      * @return true on success, false if the input connection is no longer
567      *
568      */
setComposingText(@onNull CharSequence text, int newCursorPosition, @Nullable TextAttribute textAttribute)569     default boolean setComposingText(@NonNull CharSequence text, int newCursorPosition,
570             @Nullable TextAttribute textAttribute) {
571         return setComposingText(text, newCursorPosition);
572     }
573 
574     /**
575      * Mark a certain region of text as composing text. If there was a
576      * composing region, the characters are left as they were and the
577      * composing span removed, as if {@link #finishComposingText()}
578      * has been called. The default style for composing text is used.
579      *
580      * <p>The passed indices are clipped to the contents bounds. If
581      * the resulting region is zero-sized, no region is marked and the
582      * effect is the same as that of calling {@link #finishComposingText()}.
583      * The order of start and end is not important. In effect, the
584      * region from start to end and the region from end to start is
585      * the same. Editor authors, be ready to accept a start that is
586      * greater than end.</p>
587      *
588      * <p>Since this does not change the contents of the text, editors should not call
589      * {@link InputMethodManager#updateSelection(View, int, int, int, int)} and
590      * IMEs should not receive
591      * {@link android.inputmethodservice.InputMethodService#onUpdateSelection(int, int, int, int,
592      * int, int)}.</p>
593      *
594      * <p>This has no impact on the cursor/selection position. It may
595      * result in the cursor being anywhere inside or outside the
596      * composing region, including cases where the selection and the
597      * composing region overlap partially or entirely.</p>
598      *
599      * @param start the position in the text at which the composing region begins
600      * @param end the position in the text at which the composing region ends
601      * @return {@code true} on success, {@code false} if the input connection is no longer valid.
602      *         Since Android {@link android.os.Build.VERSION_CODES#N} until
603      *         {@link android.os.Build.VERSION_CODES#TIRAMISU}, this API returned {@code false} when
604      *         the target application does not implement this method.
605      */
setComposingRegion(int start, int end)606     boolean setComposingRegion(int start, int end);
607 
608     /**
609      * The variant of {@link InputConnection#setComposingRegion(int, int)}. This method is
610      * used to allow the IME to provide extra information while setting up text.
611      *
612      * @param start the position in the text at which the composing region begins
613      * @param end the position in the text at which the composing region ends
614      * @param textAttribute The extra information about the text.
615      * @return {@code true} on success, {@code false} if the input connection is no longer valid.
616      *         Since Android {@link android.os.Build.VERSION_CODES#N} until
617      *         {@link android.os.Build.VERSION_CODES#TIRAMISU}, this API returned {@code false} when
618      *         the target application does not implement this method.
619      */
setComposingRegion(int start, int end, @Nullable TextAttribute textAttribute)620     default boolean setComposingRegion(int start, int end, @Nullable TextAttribute textAttribute) {
621         return setComposingRegion(start, end);
622     }
623 
624     /**
625      * Have the text editor finish whatever composing text is
626      * currently active. This simply leaves the text as-is, removing
627      * any special composing styling or other state that was around
628      * it. The cursor position remains unchanged.
629      *
630      * <p><strong>IME authors:</strong> be aware that this call may be
631      * expensive with some editors.</p>
632      *
633      * <p><strong>Editor authors:</strong> please note that the cursor
634      * may be anywhere in the contents when this is called, including
635      * in the middle of the composing span or in a completely
636      * unrelated place. It must not move.</p>
637      *
638      * @return true on success, false if the input connection
639      * is no longer valid.
640      */
finishComposingText()641     boolean finishComposingText();
642 
643     /**
644      * Commit text to the text box and set the new cursor position.
645      *
646      * <p>This method removes the contents of the currently composing
647      * text and replaces it with the passed CharSequence, and then
648      * moves the cursor according to {@code newCursorPosition}. If there
649      * is no composing text when this method is called, the new text is
650      * inserted at the cursor position, removing text inside the selection
651      * if any. This behaves like calling
652      * {@link #setComposingText(CharSequence, int) setComposingText(text, newCursorPosition)}
653      * then {@link #finishComposingText()}.</p>
654      *
655      * <p>Calling this method will cause the editor to call
656      * {@link android.inputmethodservice.InputMethodService#onUpdateSelection(int, int, int, int,
657      * int, int)} on the current IME after the batch input is over.
658      * <strong>Editor authors</strong>, for this to happen you need to
659      * make the changes known to the input method by calling
660      * {@link InputMethodManager#updateSelection(View, int, int, int, int)},
661      * but be careful to wait until the batch edit is over if one is
662      * in progress.</p>
663      *
664      * @param text The text to commit. This may include styles.
665      * @param newCursorPosition The new cursor position around the text,
666      *        in Java characters. If > 0, this is relative to the end
667      *        of the text - 1; if <= 0, this is relative to the start
668      *        of the text. So a value of 1 will always advance the cursor
669      *        to the position after the full text being inserted. Note that
670      *        this means you can't position the cursor within the text,
671      *        because the editor can make modifications to the text
672      *        you are providing so it is not possible to correctly specify
673      *        locations there.
674      * @return true on success, false if the input connection is no longer
675      * valid.
676      */
commitText(CharSequence text, int newCursorPosition)677     boolean commitText(CharSequence text, int newCursorPosition);
678 
679     /**
680      * The variant of {@link InputConnection#commitText(CharSequence, int)}. This method is
681      * used to allow the IME to provide extra information while setting up text.
682      *
683      * @param text The text to commit. This may include styles.
684      * @param newCursorPosition The new cursor position around the text,
685      *        in Java characters. If > 0, this is relative to the end
686      *        of the text - 1; if <= 0, this is relative to the start
687      *        of the text. So a value of 1 will always advance the cursor
688      *        to the position after the full text being inserted. Note that
689      *        this means you can't position the cursor within the text,
690      *        because the editor can make modifications to the text
691      *        you are providing so it is not possible to correctly specify
692      *        locations there.
693      * @param textAttribute The extra information about the text.
694      * @return true on success, false if the input connection is no longer
695      */
commitText(@onNull CharSequence text, int newCursorPosition, @Nullable TextAttribute textAttribute)696     default boolean commitText(@NonNull CharSequence text, int newCursorPosition,
697             @Nullable TextAttribute textAttribute) {
698         return commitText(text, newCursorPosition);
699     }
700 
701     /**
702      * Commit a completion the user has selected from the possible ones
703      * previously reported to {@link InputMethodSession#displayCompletions
704      * InputMethodSession#displayCompletions(CompletionInfo[])} or
705      * {@link InputMethodManager#displayCompletions
706      * InputMethodManager#displayCompletions(View, CompletionInfo[])}.
707      * This will result in the same behavior as if the user had
708      * selected the completion from the actual UI. In all other
709      * respects, this behaves like {@link #commitText(CharSequence, int)}.
710      *
711      * <p><strong>IME authors:</strong> please take care to send the
712      * same object that you received through
713      * {@link android.inputmethodservice.InputMethodService#onDisplayCompletions(CompletionInfo[])}.
714      * </p>
715      *
716      * <p><strong>Editor authors:</strong> if you never call
717      * {@link InputMethodSession#displayCompletions(CompletionInfo[])} or
718      * {@link InputMethodManager#displayCompletions(View, CompletionInfo[])} then
719      * a well-behaved IME should never call this on your input
720      * connection, but be ready to deal with misbehaving IMEs without
721      * crashing.</p>
722      *
723      * <p>Calling this method (with a valid {@link CompletionInfo} object)
724      * will cause the editor to call
725      * {@link android.inputmethodservice.InputMethodService#onUpdateSelection(int, int, int, int,
726      * int, int)} on the current IME after the batch input is over.
727      * <strong>Editor authors</strong>, for this to happen you need to
728      * make the changes known to the input method by calling
729      * {@link InputMethodManager#updateSelection(View, int, int, int, int)},
730      * but be careful to wait until the batch edit is over if one is
731      * in progress.</p>
732      *
733      * @param text The committed completion.
734      * @return true on success, false if the input connection is no longer
735      * valid.
736      */
commitCompletion(CompletionInfo text)737     boolean commitCompletion(CompletionInfo text);
738 
739     /**
740      * Commit a correction automatically performed on the raw user's input. A
741      * typical example would be to correct typos using a dictionary.
742      *
743      * <p>Calling this method will cause the editor to call
744      * {@link android.inputmethodservice.InputMethodService#onUpdateSelection(int, int, int, int,
745      * int, int)} on the current IME after the batch input is over.
746      * <strong>Editor authors</strong>, for this to happen you need to
747      * make the changes known to the input method by calling
748      * {@link InputMethodManager#updateSelection(View, int, int, int, int)},
749      * but be careful to wait until the batch edit is over if one is
750      * in progress.</p>
751      *
752      * @param correctionInfo Detailed information about the correction.
753      * @return {@code true} on success, {@code false} if the input connection is no longer valid.
754      *         Since Android {@link android.os.Build.VERSION_CODES#N} until
755      *         {@link android.os.Build.VERSION_CODES#TIRAMISU}, this API returned {@code false} when
756      *         the target application does not implement this method.
757      */
commitCorrection(CorrectionInfo correctionInfo)758     boolean commitCorrection(CorrectionInfo correctionInfo);
759 
760     /**
761      * Set the selection of the text editor. To set the cursor
762      * position, start and end should have the same value.
763      *
764      * <p>Since this moves the cursor, calling this method will cause
765      * the editor to call
766      * {@link android.inputmethodservice.InputMethodService#onUpdateSelection(int, int, int, int,
767      * int, int)} on the current IME after the batch input is over.
768      * <strong>Editor authors</strong>, for this to happen you need to
769      * make the changes known to the input method by calling
770      * {@link InputMethodManager#updateSelection(View, int, int, int, int)},
771      * but be careful to wait until the batch edit is over if one is
772      * in progress.</p>
773      *
774      * <p>This has no effect on the composing region which must stay
775      * unchanged. The order of start and end is not important. In
776      * effect, the region from start to end and the region from end to
777      * start is the same. Editor authors, be ready to accept a start
778      * that is greater than end.</p>
779      *
780      * @param start the character index where the selection should start.
781      * @param end the character index where the selection should end.
782      * @return true on success, false if the input connection is no longer
783      * valid.
784      */
setSelection(int start, int end)785     boolean setSelection(int start, int end);
786 
787     /**
788      * Have the editor perform an action it has said it can do.
789      *
790      * <p>This is typically used by IMEs when the user presses the key
791      * associated with the action.</p>
792      *
793      * @param editorAction This must be one of the action constants for
794      * {@link EditorInfo#imeOptions EditorInfo.imeOptions}, such as
795      * {@link EditorInfo#IME_ACTION_GO EditorInfo.EDITOR_ACTION_GO}, or the value of
796      * {@link EditorInfo#actionId EditorInfo.actionId} if a custom action is available.
797      * @return true on success, false if the input connection is no longer
798      * valid.
799      */
performEditorAction(int editorAction)800     boolean performEditorAction(int editorAction);
801 
802     /**
803      * Perform a context menu action on the field. The given id may be one of:
804      * {@link android.R.id#selectAll},
805      * {@link android.R.id#startSelectingText}, {@link android.R.id#stopSelectingText},
806      * {@link android.R.id#cut}, {@link android.R.id#copy},
807      * {@link android.R.id#paste}, {@link android.R.id#copyUrl},
808      * or {@link android.R.id#switchInputMethod}
809      */
performContextMenuAction(int id)810     boolean performContextMenuAction(int id);
811 
812     /**
813      * Tell the editor that you are starting a batch of editor
814      * operations. The editor will try to avoid sending you updates
815      * about its state until {@link #endBatchEdit} is called. Batch
816      * edits nest.
817      *
818      * <p><strong>IME authors:</strong> use this to avoid getting
819      * calls to
820      * {@link android.inputmethodservice.InputMethodService#onUpdateSelection(int, int, int, int,
821      * int, int)} corresponding to intermediate state. Also, use this to avoid
822      * flickers that may arise from displaying intermediate state. Be
823      * sure to call {@link #endBatchEdit} for each call to this, or
824      * you may block updates in the editor.</p>
825      *
826      * <p><strong>Editor authors:</strong> while a batch edit is in
827      * progress, take care not to send updates to the input method and
828      * not to update the display. IMEs use this intensively to this
829      * effect. Also please note that batch edits need to nest
830      * correctly.</p>
831      *
832      * @return true if a batch edit is now in progress, false otherwise. Since
833      * this method starts a batch edit, that means it will always return true
834      * unless the input connection is no longer valid.
835      */
beginBatchEdit()836     boolean beginBatchEdit();
837 
838     /**
839      * Tell the editor that you are done with a batch edit previously initiated with
840      * {@link #beginBatchEdit()}. This ends the latest batch only.
841      *
842      * <p><strong>IME authors:</strong> make sure you call this exactly once for each call to
843      * {@link #beginBatchEdit()}.</p>
844      *
845      * <p><strong>Editor authors:</strong> please be careful about batch edit nesting. Updates still
846      * to be held back until the end of the last batch edit.  In case you are delegating this API
847      * call to the one obtained from
848      * {@link android.widget.EditText#onCreateInputConnection(EditorInfo)}, there was an off-by-one
849      * that had returned {@code true} when its nested batch edit count becomes {@code 0} as a result
850      * of invoking this API.  This bug is fixed in {@link android.os.Build.VERSION_CODES#TIRAMISU}.
851      * </p>
852      *
853      * @return For editor authors, you must return {@code true} if a batch edit is still in progress
854      *         after closing the latest one (in other words, if the nesting count is still a
855      *         positive number). Return {@code false} otherwise.  For IME authors, you will
856      *         always receive {@code true} as long as the request was sent to the editor, and
857      *         receive {@code false} only if the input connection is no longer valid.
858      */
endBatchEdit()859     boolean endBatchEdit();
860 
861     /**
862      * Send a key event to the process that is currently attached
863      * through this input connection. The event will be dispatched
864      * like a normal key event, to the currently focused view; this
865      * generally is the view that is providing this InputConnection,
866      * but due to the asynchronous nature of this protocol that can
867      * not be guaranteed and the focus may have changed by the time
868      * the event is received.
869      *
870      * <p>This method can be used to send key events to the
871      * application. For example, an on-screen keyboard may use this
872      * method to simulate a hardware keyboard. There are three types
873      * of standard keyboards, numeric (12-key), predictive (20-key)
874      * and ALPHA (QWERTY). You can specify the keyboard type by
875      * specify the device id of the key event.</p>
876      *
877      * <p>You will usually want to set the flag
878      * {@link KeyEvent#FLAG_SOFT_KEYBOARD KeyEvent.FLAG_SOFT_KEYBOARD}
879      * on all key event objects you give to this API; the flag will
880      * not be set for you.</p>
881      *
882      * <p>Note that it's discouraged to send such key events in normal
883      * operation; this is mainly for use with
884      * {@link android.text.InputType#TYPE_NULL} type text fields. Use
885      * the {@link #commitText} family of methods to send text to the
886      * application instead.</p>
887      *
888      * @param event The key event.
889      * @return true on success, false if the input connection is no longer
890      * valid.
891      *
892      * @see KeyEvent
893      * @see KeyCharacterMap#NUMERIC
894      * @see KeyCharacterMap#PREDICTIVE
895      * @see KeyCharacterMap#ALPHA
896      */
sendKeyEvent(KeyEvent event)897     boolean sendKeyEvent(KeyEvent event);
898 
899     /**
900      * Clear the given meta key pressed states in the given input
901      * connection.
902      *
903      * <p>This can be used by the IME to clear the meta key states set
904      * by a hardware keyboard with latched meta keys, if the editor
905      * keeps track of these.</p>
906      *
907      * @param states The states to be cleared, may be one or more bits as
908      * per {@link KeyEvent#getMetaState() KeyEvent.getMetaState()}.
909      * @return true on success, false if the input connection is no longer
910      * valid.
911      */
clearMetaKeyStates(int states)912     boolean clearMetaKeyStates(int states);
913 
914     /**
915      * Called back when the connected IME switches between fullscreen and normal modes.
916      *
917      * <p><p><strong>Editor authors:</strong> There is a bug on
918      * {@link android.os.Build.VERSION_CODES#O} and later devices that this method is called back
919      * on the main thread even when {@link #getHandler()} is overridden.  This bug is fixed in
920      * {@link android.os.Build.VERSION_CODES#TIRAMISU}.</p>
921      *
922      * <p><p><strong>IME authors:</strong> On {@link android.os.Build.VERSION_CODES#O} and later
923      * devices, input methods are no longer allowed to directly call this method at any time.
924      * To signal this event in the target application, input methods should always call
925      * {@link InputMethodService#updateFullscreenMode()} instead. This approach should work on API
926      * {@link android.os.Build.VERSION_CODES#N_MR1} and prior devices.</p>
927      *
928      * @return For editor authors, the return value will always be ignored. For IME authors, this
929      *         always returns {@code true} on {@link android.os.Build.VERSION_CODES#N_MR1} and prior
930      *         devices and {@code false} on {@link android.os.Build.VERSION_CODES#O} and later
931      *         devices.
932      * @see InputMethodManager#isFullscreenMode()
933      */
reportFullscreenMode(boolean enabled)934     boolean reportFullscreenMode(boolean enabled);
935 
936     /**
937      * Have the editor perform spell checking for the full content.
938      *
939      * <p>The editor can ignore this method call if it does not support spell checking.
940      *
941      * @return For editor authors, the return value will always be ignored. For IME authors, this
942      *         method returns true if the spell check request was sent (whether or not the
943      *         associated editor supports spell checking), false if the input connection is no
944      *         longer valid.
945      */
performSpellCheck()946     default boolean performSpellCheck() {
947         return false;
948     }
949 
950     /**
951      * API to send private commands from an input method to its
952      * connected editor. This can be used to provide domain-specific
953      * features that are only known between certain input methods and
954      * their clients. Note that because the InputConnection protocol
955      * is asynchronous, you have no way to get a result back or know
956      * if the client understood the command; you can use the
957      * information in {@link EditorInfo} to determine if a client
958      * supports a particular command.
959      *
960      * @param action Name of the command to be performed. This <em>must</em>
961      * be a scoped name, i.e. prefixed with a package name you own, so that
962      * different developers will not create conflicting commands.
963      * @param data Any data to include with the command.
964      * @return true if the command was sent (whether or not the
965      * associated editor understood it), false if the input connection is no longer
966      * valid.
967      */
performPrivateCommand(String action, Bundle data)968     boolean performPrivateCommand(String action, Bundle data);
969 
970     /**
971      * The editor is requested to call
972      * {@link InputMethodManager#updateCursorAnchorInfo(android.view.View, CursorAnchorInfo)} at
973      * once, as soon as possible, regardless of cursor/anchor position changes. This flag can be
974      * used together with {@link #CURSOR_UPDATE_MONITOR}.
975      * <p>
976      * Note by default all of {@link #CURSOR_UPDATE_FILTER_EDITOR_BOUNDS},
977      * {@link #CURSOR_UPDATE_FILTER_CHARACTER_BOUNDS} and
978      * {@link #CURSOR_UPDATE_FILTER_INSERTION_MARKER} are included but specifying them can
979      * filter-out others.
980      * It can be CPU intensive to include all, filtering specific info is recommended.
981      * </p>
982      */
983     int CURSOR_UPDATE_IMMEDIATE = 1 << 0;
984 
985     /**
986      * The editor is requested to call
987      * {@link InputMethodManager#updateCursorAnchorInfo(android.view.View, CursorAnchorInfo)}
988      * whenever cursor/anchor position is changed. To disable monitoring, call
989      * {@link InputConnection#requestCursorUpdates(int)} again with this flag off.
990      * <p>
991      * This flag can be used together with {@link #CURSOR_UPDATE_IMMEDIATE}.
992      * </p>
993      * <p>
994      * Note by default all of {@link #CURSOR_UPDATE_FILTER_EDITOR_BOUNDS},
995      * {@link #CURSOR_UPDATE_FILTER_CHARACTER_BOUNDS} and
996      * {@link #CURSOR_UPDATE_FILTER_INSERTION_MARKER} are included but specifying them can
997      * filter-out others.
998      * It can be CPU intensive to include all, filtering specific info is recommended.
999      * </p>
1000      */
1001     int CURSOR_UPDATE_MONITOR = 1 << 1;
1002 
1003     /**
1004      * The editor is requested to call
1005      * {@link InputMethodManager#updateCursorAnchorInfo(android.view.View, CursorAnchorInfo)}
1006      * with new {@link EditorBoundsInfo} whenever cursor/anchor position is changed. To disable
1007      * monitoring, call {@link InputConnection#requestCursorUpdates(int)} again with this flag off.
1008      * <p>
1009      * This flag can be used together with filters: {@link #CURSOR_UPDATE_FILTER_CHARACTER_BOUNDS},
1010      * {@link #CURSOR_UPDATE_FILTER_INSERTION_MARKER} and update flags
1011      * {@link #CURSOR_UPDATE_IMMEDIATE} and {@link #CURSOR_UPDATE_MONITOR}.
1012      * </p>
1013      */
1014     int CURSOR_UPDATE_FILTER_EDITOR_BOUNDS = 1 << 2;
1015 
1016     /**
1017      * The editor is requested to call
1018      * {@link InputMethodManager#updateCursorAnchorInfo(android.view.View, CursorAnchorInfo)}
1019      * with new character bounds {@link CursorAnchorInfo#getCharacterBounds(int)} whenever
1020      * cursor/anchor position is changed. To disable
1021      * monitoring, call {@link InputConnection#requestCursorUpdates(int)} again with this flag off.
1022      * <p>
1023      * This flag can be combined with other filters: {@link #CURSOR_UPDATE_FILTER_EDITOR_BOUNDS},
1024      * {@link #CURSOR_UPDATE_FILTER_INSERTION_MARKER} and update flags
1025      * {@link #CURSOR_UPDATE_IMMEDIATE} and {@link #CURSOR_UPDATE_MONITOR}.
1026      * </p>
1027      */
1028     int CURSOR_UPDATE_FILTER_CHARACTER_BOUNDS = 1 << 3;
1029 
1030     /**
1031      * The editor is requested to call
1032      * {@link InputMethodManager#updateCursorAnchorInfo(android.view.View, CursorAnchorInfo)}
1033      * with new Insertion marker info {@link CursorAnchorInfo#getInsertionMarkerFlags()},
1034      * {@link CursorAnchorInfo#getInsertionMarkerBaseline()}, etc whenever cursor/anchor position is
1035      * changed. To disable monitoring, call {@link InputConnection#requestCursorUpdates(int)} again
1036      * with this flag off.
1037      * <p>
1038      * This flag can be combined with other filters: {@link #CURSOR_UPDATE_FILTER_CHARACTER_BOUNDS},
1039      * {@link #CURSOR_UPDATE_FILTER_EDITOR_BOUNDS} and update flags {@link #CURSOR_UPDATE_IMMEDIATE}
1040      * and {@link #CURSOR_UPDATE_MONITOR}.
1041      * </p>
1042      */
1043     int CURSOR_UPDATE_FILTER_INSERTION_MARKER = 1 << 4;
1044 
1045     /**
1046      * @hide
1047      */
1048     @Retention(RetentionPolicy.SOURCE)
1049     @IntDef(value = {CURSOR_UPDATE_IMMEDIATE, CURSOR_UPDATE_MONITOR}, flag = true,
1050             prefix = { "CURSOR_UPDATE_" })
1051     @interface CursorUpdateMode{}
1052 
1053     /**
1054      * @hide
1055      */
1056     @Retention(RetentionPolicy.SOURCE)
1057     @IntDef(value = {CURSOR_UPDATE_FILTER_EDITOR_BOUNDS, CURSOR_UPDATE_FILTER_CHARACTER_BOUNDS,
1058             CURSOR_UPDATE_FILTER_INSERTION_MARKER}, flag = true,
1059             prefix = { "CURSOR_UPDATE_FILTER_" })
1060     @interface CursorUpdateFilter{}
1061 
1062     /**
1063      * Called by the input method to ask the editor for calling back
1064      * {@link InputMethodManager#updateCursorAnchorInfo(android.view.View, CursorAnchorInfo)} to
1065      * notify cursor/anchor locations.
1066      *
1067      * @param cursorUpdateMode any combination of update modes and filters:
1068      * {@link #CURSOR_UPDATE_IMMEDIATE}, {@link #CURSOR_UPDATE_MONITOR}, and date filters:
1069      * {@link #CURSOR_UPDATE_FILTER_CHARACTER_BOUNDS}, {@link #CURSOR_UPDATE_FILTER_EDITOR_BOUNDS},
1070      * {@link #CURSOR_UPDATE_FILTER_INSERTION_MARKER}.
1071      * Pass {@code 0} to disable them. However, if an unknown flag is provided, request will be
1072      * rejected and method will return {@code false}.
1073      * @return {@code true} if the request is scheduled. {@code false} to indicate that when the
1074      *         application will not call {@link InputMethodManager#updateCursorAnchorInfo(
1075      *         android.view.View, CursorAnchorInfo)}.
1076      *         Since Android {@link android.os.Build.VERSION_CODES#N} until
1077      *         {@link android.os.Build.VERSION_CODES#TIRAMISU}, this API returned {@code false} when
1078      *         the target application does not implement this method.
1079      */
requestCursorUpdates(int cursorUpdateMode)1080     boolean requestCursorUpdates(int cursorUpdateMode);
1081 
1082     /**
1083      * Called by the input method to ask the editor for calling back
1084      * {@link InputMethodManager#updateCursorAnchorInfo(android.view.View, CursorAnchorInfo)} to
1085      * notify cursor/anchor locations.
1086      *
1087      * @param cursorUpdateMode combination of update modes:
1088      * {@link #CURSOR_UPDATE_IMMEDIATE}, {@link #CURSOR_UPDATE_MONITOR}
1089      * @param cursorUpdateFilter any combination of data filters:
1090      * {@link #CURSOR_UPDATE_FILTER_CHARACTER_BOUNDS}, {@link #CURSOR_UPDATE_FILTER_EDITOR_BOUNDS},
1091      * {@link #CURSOR_UPDATE_FILTER_INSERTION_MARKER}.
1092      *
1093      * <p>Pass {@code 0} to disable them. However, if an unknown flag is provided, request will be
1094      * rejected and method will return {@code false}.</p>
1095      * @return {@code true} if the request is scheduled. {@code false} to indicate that when the
1096      *         application will not call {@link InputMethodManager#updateCursorAnchorInfo(
1097      *         android.view.View, CursorAnchorInfo)}.
1098      *         Since Android {@link android.os.Build.VERSION_CODES#N} until
1099      *         {@link android.os.Build.VERSION_CODES#TIRAMISU}, this API returned {@code false} when
1100      *         the target application does not implement this method.
1101      */
requestCursorUpdates(@ursorUpdateMode int cursorUpdateMode, @CursorUpdateFilter int cursorUpdateFilter)1102     default boolean requestCursorUpdates(@CursorUpdateMode int cursorUpdateMode,
1103             @CursorUpdateFilter int cursorUpdateFilter) {
1104         if (cursorUpdateFilter == 0) {
1105             return requestCursorUpdates(cursorUpdateMode);
1106         }
1107         return false;
1108     }
1109 
1110     /**
1111      * Called by the system to enable application developers to specify a dedicated thread on which
1112      * {@link InputConnection} methods are called back.
1113      *
1114      * <p><strong>Editor authors</strong>: although you can return your custom subclasses of
1115      * {@link Handler}, the system only uses {@link android.os.Looper} returned from
1116      * {@link Handler#getLooper()}.  You cannot intercept or cancel {@link InputConnection}
1117      * callbacks by implementing this method.</p>
1118      *
1119      * <p><strong>IME authors</strong>: This method is not intended to be called from the IME.  You
1120      * will always receive {@code null}.</p>
1121      *
1122      * @return {@code null} to use the default {@link Handler}.
1123      */
1124     @Nullable
getHandler()1125     Handler getHandler();
1126 
1127     /**
1128      * Called by the system up to only once to notify that the system is about to invalidate
1129      * connection between the input method and the application.
1130      *
1131      * <p><strong>Editor authors</strong>: You can clear all the nested batch edit right now and
1132      * you no longer need to handle subsequent callbacks on this connection, including
1133      * {@link #beginBatchEdit()}}.  Note that although the system tries to call this method whenever
1134      * possible, there may be a chance that this method is not called in some exceptional
1135      * situations.</p>
1136      *
1137      * <p>Note: This does nothing when called from input methods.</p>
1138      */
closeConnection()1139     void closeConnection();
1140 
1141     /**
1142      * When this flag is used, the editor will be able to request read access to the content URI
1143      * contained in the {@link InputContentInfo} object.
1144      *
1145      * <p>Make sure that the content provider owning the Uri sets the
1146      * {@link android.R.styleable#AndroidManifestProvider_grantUriPermissions
1147      * grantUriPermissions} attribute in its manifest or included the
1148      * {@link android.R.styleable#AndroidManifestGrantUriPermission
1149      * &lt;grant-uri-permissions&gt;} tag. Otherwise {@link InputContentInfo#requestPermission()}
1150      * can fail.</p>
1151      *
1152      * <p>Although calling this API is allowed only for the IME that is currently selected, the
1153      * client is able to request a temporary read-only access even after the current IME is switched
1154      * to any other IME as long as the client keeps {@link InputContentInfo} object.</p>
1155      **/
1156     int INPUT_CONTENT_GRANT_READ_URI_PERMISSION =
1157             android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION;  // 0x00000001
1158 
1159     /**
1160      * Called by the input method to commit content such as a PNG image to the editor.
1161      *
1162      * <p>In order to avoid a variety of compatibility issues, this focuses on a simple use case,
1163      * where editors and IMEs are expected to work cooperatively as follows:</p>
1164      * <ul>
1165      *     <li>Editor must keep {@link EditorInfo#contentMimeTypes} equal to {@code null} if it does
1166      *     not support this method at all.</li>
1167      *     <li>Editor can ignore this request when the MIME type specified in
1168      *     {@code inputContentInfo} does not match any of {@link EditorInfo#contentMimeTypes}.
1169      *     </li>
1170      *     <li>Editor can ignore the cursor position when inserting the provided content.</li>
1171      *     <li>Editor can return {@code true} asynchronously, even before it starts loading the
1172      *     content.</li>
1173      *     <li>Editor should provide a way to delete the content inserted by this method or to
1174      *     revert the effect caused by this method.</li>
1175      *     <li>IME should not call this method when there is any composing text, in case calling
1176      *     this method causes a focus change.</li>
1177      *     <li>IME should grant a permission for the editor to read the content. See
1178      *     {@link EditorInfo#packageName} about how to obtain the package name of the editor.</li>
1179      * </ul>
1180      *
1181      * @param inputContentInfo Content to be inserted.
1182      * @param flags {@link #INPUT_CONTENT_GRANT_READ_URI_PERMISSION} if the content provider
1183      * allows {@link android.R.styleable#AndroidManifestProvider_grantUriPermissions
1184      * grantUriPermissions} or {@code 0} if the application does not need to call
1185      * {@link InputContentInfo#requestPermission()}.
1186      * @param opts optional bundle data. This can be {@code null}.
1187      * @return {@code true} if this request is accepted by the application, whether the request
1188      * is already handled or still being handled in background, {@code false} otherwise.
1189      */
commitContent(@onNull InputContentInfo inputContentInfo, int flags, @Nullable Bundle opts)1190     boolean commitContent(@NonNull InputContentInfo inputContentInfo, int flags,
1191             @Nullable Bundle opts);
1192 
1193     /**
1194      * Called by the input method to indicate that it consumes all input for itself, or no longer
1195      * does so.
1196      *
1197      * <p>Editors should reflect that they are not receiving input by hiding the cursor if
1198      * {@code imeConsumesInput} is {@code true}, and resume showing the cursor if it is
1199      * {@code false}.
1200      *
1201      * @param imeConsumesInput {@code true} when the IME is consuming input and the cursor should be
1202      * hidden, {@code false} when input to the editor resumes and the cursor should be shown again.
1203      * @return For editor authors, the return value will always be ignored. For IME authors, this
1204      *         method returns {@code true} if the request was sent (whether or not the associated
1205      *         editor does something based on this request), {@code false} if the input connection
1206      *         is no longer valid.
1207      */
setImeConsumesInput(boolean imeConsumesInput)1208     default boolean setImeConsumesInput(boolean imeConsumesInput) {
1209         return false;
1210     }
1211 
1212     /**
1213      * Called by the system when it needs to take a snapshot of multiple text-related data in an
1214      * atomic manner.
1215      *
1216      * <p><strong>Editor authors</strong>: Supporting this method is strongly encouraged. Atomically
1217      * taken {@link TextSnapshot} is going to be really helpful for the system when optimizing IPCs
1218      * in a safe and deterministic manner.  Return {@code null} if an atomically taken
1219      * {@link TextSnapshot} is unavailable.  The system continues supporting such a scenario
1220      * gracefully.</p>
1221      *
1222      * <p><strong>IME authors</strong>: Currently IMEs cannot call this method directly and always
1223      * receive {@code null} as the result.</p>
1224      *
1225      * @return {@code null} if {@link TextSnapshot} is unavailable and/or this API is called from
1226      *         IMEs.
1227      */
1228     @Nullable
takeSnapshot()1229     default TextSnapshot takeSnapshot() {
1230         // Returning null by default because the composing text range cannot be retrieved from
1231         // existing APIs.
1232         return null;
1233     }
1234 }
1235