• 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 null if
278      * no text is selected. In {@link android.os.Build.VERSION_CODES#N} and
279      * later, returns false when the target application does not implement
280      * this method.
281      */
getSelectedText(int flags)282     CharSequence getSelectedText(int flags);
283 
284     /**
285      * Gets the surrounding text around the current cursor, with <var>beforeLength</var> characters
286      * of text before the cursor (start of the selection), <var>afterLength</var> characters of text
287      * after the cursor (end of the selection), and all of the selected text. The range are for java
288      * characters, not glyphs that can be multiple characters.
289      *
290      * <p>This method may fail either if the input connection has become invalid (such as its
291      * process crashing), or the client is taking too long to respond with the text (it is given a
292      * couple seconds to return), or the protocol is not supported. In any of these cases, null is
293      * returned.
294      *
295      * <p>This method does not affect the text in the editor in any way, nor does it affect the
296      * selection or composing spans.</p>
297      *
298      * <p>If {@link #GET_TEXT_WITH_STYLES} is supplied as flags, the editor should return a
299      * {@link android.text.Spanned} with all the spans set on the text.</p>
300      *
301      * <p><strong>IME authors:</strong> please consider this will trigger an IPC round-trip that
302      * will take some time. Assume this method consumes a lot of time. If you are using this to get
303      * the initial surrounding text around the cursor, you may consider using
304      * {@link EditorInfo#getInitialTextBeforeCursor(int, int)},
305      * {@link EditorInfo#getInitialSelectedText(int)}, and
306      * {@link EditorInfo#getInitialTextAfterCursor(int, int)} to prevent IPC costs.</p>
307      *
308      * @param beforeLength The expected length of the text before the cursor.
309      * @param afterLength The expected length of the text after the cursor.
310      * @param flags Supplies additional options controlling how the text is returned. May be either
311      *              {@code 0} or {@link #GET_TEXT_WITH_STYLES}.
312      * @return an {@link android.view.inputmethod.SurroundingText} object describing the surrounding
313      * text and state of selection, or null if the input connection is no longer valid, or the
314      * editor can't comply with the request for some reason, or the application does not implement
315      * this method. The length of the returned text might be less than the sum of
316      * <var>beforeLength</var> and <var>afterLength</var> .
317      * @throws IllegalArgumentException if {@code beforeLength} or {@code afterLength} is negative.
318      */
319     @Nullable
getSurroundingText( @ntRangefrom = 0) int beforeLength, @IntRange(from = 0) int afterLength, @GetTextType int flags)320     default SurroundingText getSurroundingText(
321             @IntRange(from = 0) int beforeLength, @IntRange(from = 0) int afterLength,
322             @GetTextType int flags) {
323         Preconditions.checkArgumentNonnegative(beforeLength);
324         Preconditions.checkArgumentNonnegative(afterLength);
325 
326         CharSequence textBeforeCursor = getTextBeforeCursor(beforeLength, flags);
327         if (textBeforeCursor == null) {
328             return null;
329         }
330         CharSequence textAfterCursor = getTextAfterCursor(afterLength, flags);
331         if (textAfterCursor == null) {
332             return null;
333         }
334         CharSequence selectedText = getSelectedText(flags);
335         if (selectedText == null) {
336             selectedText = "";
337         }
338         CharSequence surroundingText =
339                 TextUtils.concat(textBeforeCursor, selectedText, textAfterCursor);
340         return new SurroundingText(surroundingText, textBeforeCursor.length(),
341                 textBeforeCursor.length() + selectedText.length(), -1);
342     }
343 
344     /**
345      * Retrieve the current capitalization mode in effect at the
346      * current cursor position in the text. See
347      * {@link android.text.TextUtils#getCapsMode TextUtils.getCapsMode}
348      * for more information.
349      *
350      * <p>This method may fail either if the input connection has
351      * become invalid (such as its process crashing) or the client is
352      * taking too long to respond with the text (it is given a couple
353      * seconds to return). In either case, 0 is returned.</p>
354      *
355      * <p>This method does not affect the text in the editor in any
356      * way, nor does it affect the selection or composing spans.</p>
357      *
358      * <p><strong>Editor authors:</strong> please be careful of race
359      * conditions in implementing this call. An IME can change the
360      * cursor position and use this method right away; you need to make
361      * sure the returned value is consistent with the results of the
362      * latest edits and changes to the cursor position.</p>
363      *
364      * @param reqModes The desired modes to retrieve, as defined by
365      * {@link android.text.TextUtils#getCapsMode TextUtils.getCapsMode}. These
366      * constants are defined so that you can simply pass the current
367      * {@link EditorInfo#inputType TextBoxAttribute.contentType} value
368      * directly in to here.
369      * @return the caps mode flags that are in effect at the current
370      * cursor position. See TYPE_TEXT_FLAG_CAPS_* in {@link android.text.InputType}.
371      */
getCursorCapsMode(int reqModes)372     int getCursorCapsMode(int reqModes);
373 
374     /**
375      * Retrieve the current text in the input connection's editor, and
376      * monitor for any changes to it. This function returns with the
377      * current text, and optionally the input connection can send
378      * updates to the input method when its text changes.
379      *
380      * <p>This method may fail either if the input connection has
381      * become invalid (such as its process crashing) or the client is
382      * taking too long to respond with the text (it is given a couple
383      * seconds to return). In either case, null is returned.</p>
384      *
385      * <p>Editor authors: as a general rule, try to comply with the
386      * fields in <code>request</code> for how many chars to return,
387      * but if performance or convenience dictates otherwise, please
388      * feel free to do what is most appropriate for your case. Also,
389      * if the
390      * {@link #GET_EXTRACTED_TEXT_MONITOR} flag is set, you should be
391      * calling
392      * {@link InputMethodManager#updateExtractedText(View, int, ExtractedText)}
393      * whenever you call
394      * {@link InputMethodManager#updateSelection(View, int, int, int, int)}.</p>
395      *
396      * @param request Description of how the text should be returned.
397      * {@link android.view.inputmethod.ExtractedTextRequest}
398      * @param flags Additional options to control the client, either {@code 0} or
399      * {@link #GET_EXTRACTED_TEXT_MONITOR}.
400 
401      * @return an {@link android.view.inputmethod.ExtractedText}
402      * object describing the state of the text view and containing the
403      * extracted text itself, or null if the input connection is no
404      * longer valid of the editor can't comply with the request for
405      * some reason.
406      */
getExtractedText(ExtractedTextRequest request, int flags)407     ExtractedText getExtractedText(ExtractedTextRequest request, int flags);
408 
409     /**
410      * Delete <var>beforeLength</var> characters of text before the
411      * current cursor position, and delete <var>afterLength</var>
412      * characters of text after the current cursor position, excluding
413      * the selection. Before and after refer to the order of the
414      * characters in the string, not to their visual representation:
415      * this means you don't have to figure out the direction of the
416      * text and can just use the indices as-is.
417      *
418      * <p>The lengths are supplied in Java chars, not in code points
419      * or in glyphs.</p>
420      *
421      * <p>Since this method only operates on text before and after the
422      * selection, it can't affect the contents of the selection. This
423      * may affect the composing span if the span includes characters
424      * that are to be deleted, but otherwise will not change it. If
425      * some characters in the composing span are deleted, the
426      * composing span will persist but get shortened by however many
427      * chars inside it have been removed.</p>
428      *
429      * <p><strong>IME authors:</strong> please be careful not to
430      * delete only half of a surrogate pair. Also take care not to
431      * delete more characters than are in the editor, as that may have
432      * ill effects on the application. Calling this method will cause
433      * the editor to call
434      * {@link android.inputmethodservice.InputMethodService#onUpdateSelection(int, int, int, int,
435      * int, int)} on your service after the batch input is over.</p>
436      *
437      * <p><strong>Editor authors:</strong> please be careful of race
438      * conditions in implementing this call. An IME can make a change
439      * to the text or change the selection position and use this
440      * method right away; you need to make sure the effects are
441      * consistent with the results of the latest edits. Also, although
442      * the IME should not send lengths bigger than the contents of the
443      * string, you should check the values for overflows and trim the
444      * indices to the size of the contents to avoid crashes. Since
445      * this changes the contents of the editor, you need to make the
446      * changes known to the input method by calling
447      * {@link InputMethodManager#updateSelection(View, int, int, int, int)},
448      * but be careful to wait until the batch edit is over if one is
449      * in progress.</p>
450      *
451      * @param beforeLength The number of characters before the cursor to be deleted, in code unit.
452      *        If this is greater than the number of existing characters between the beginning of the
453      *        text and the cursor, then this method does not fail but deletes all the characters in
454      *        that range.
455      * @param afterLength The number of characters after the cursor to be deleted, in code unit.
456      *        If this is greater than the number of existing characters between the cursor and
457      *        the end of the text, then this method does not fail but deletes all the characters in
458      *        that range.
459      * @return true on success, false if the input connection is no longer valid.
460      */
deleteSurroundingText(int beforeLength, int afterLength)461     boolean deleteSurroundingText(int beforeLength, int afterLength);
462 
463     /**
464      * A variant of {@link #deleteSurroundingText(int, int)}. Major differences are:
465      *
466      * <ul>
467      *     <li>The lengths are supplied in code points, not in Java chars or in glyphs.</>
468      *     <li>This method does nothing if there are one or more invalid surrogate pairs in the
469      *     requested range.</li>
470      * </ul>
471      *
472      * <p><strong>Editor authors:</strong> In addition to the requirement in
473      * {@link #deleteSurroundingText(int, int)}, make sure to do nothing when one ore more invalid
474      * surrogate pairs are found in the requested range.</p>
475      *
476      * @see #deleteSurroundingText(int, int)
477      *
478      * @param beforeLength The number of characters before the cursor to be deleted, in code points.
479      *        If this is greater than the number of existing characters between the beginning of the
480      *        text and the cursor, then this method does not fail but deletes all the characters in
481      *        that range.
482      * @param afterLength The number of characters after the cursor to be deleted, in code points.
483      *        If this is greater than the number of existing characters between the cursor and
484      *        the end of the text, then this method does not fail but deletes all the characters in
485      *        that range.
486      * @return true on success, false if the input connection is no longer valid.  Returns
487      * {@code false} when the target application does not implement this method.
488      */
deleteSurroundingTextInCodePoints(int beforeLength, int afterLength)489     boolean deleteSurroundingTextInCodePoints(int beforeLength, int afterLength);
490 
491     /**
492      * Replace the currently composing text with the given text, and
493      * set the new cursor position. Any composing text set previously
494      * will be removed automatically.
495      *
496      * <p>If there is any composing span currently active, all
497      * characters that it comprises are removed. The passed text is
498      * added in its place, and a composing span is added to this
499      * text. If there is no composing span active, the passed text is
500      * added at the cursor position (removing selected characters
501      * first if any), and a composing span is added on the new text.
502      * Finally, the cursor is moved to the location specified by
503      * <code>newCursorPosition</code>.</p>
504      *
505      * <p>This is usually called by IMEs to add or remove or change
506      * characters in the composing span. Calling this method will
507      * cause the editor to call
508      * {@link android.inputmethodservice.InputMethodService#onUpdateSelection(int, int, int, int,
509      * int, int)} on the current IME after the batch input is over.</p>
510      *
511      * <p><strong>Editor authors:</strong> please keep in mind the
512      * text may be very similar or completely different than what was
513      * in the composing span at call time, or there may not be a
514      * composing span at all. Please note that although it's not
515      * typical use, the string may be empty. Treat this normally,
516      * replacing the currently composing text with an empty string.
517      * Also, be careful with the cursor position. IMEs rely on this
518      * working exactly as described above. Since this changes the
519      * contents of the editor, you need to make the changes known to
520      * the input method by calling
521      * {@link InputMethodManager#updateSelection(View, int, int, int, int)},
522      * but be careful to wait until the batch edit is over if one is
523      * in progress. Note that this method can set the cursor position
524      * on either edge of the composing text or entirely outside it,
525      * but the IME may also go on to move the cursor position to
526      * within the composing text in a subsequent call so you should
527      * make no assumption at all: the composing text and the selection
528      * are entirely independent.</p>
529      *
530      * @param text The composing text with styles if necessary. If no style
531      *        object attached to the text, the default style for composing text
532      *        is used. See {@link android.text.Spanned} for how to attach style
533      *        object to the text. {@link android.text.SpannableString} and
534      *        {@link android.text.SpannableStringBuilder} are two
535      *        implementations of the interface {@link android.text.Spanned}.
536      * @param newCursorPosition The new cursor position around the text. If
537      *        > 0, this is relative to the end of the text - 1; if <= 0, this
538      *        is relative to the start of the text. So a value of 1 will
539      *        always advance you to the position after the full text being
540      *        inserted. Note that this means you can't position the cursor
541      *        within the text, because the editor can make modifications to
542      *        the text you are providing so it is not possible to correctly
543      *        specify locations there.
544      * @return true on success, false if the input connection is no longer
545      * valid.
546      */
setComposingText(CharSequence text, int newCursorPosition)547     boolean setComposingText(CharSequence text, int newCursorPosition);
548 
549     /**
550      * Mark a certain region of text as composing text. If there was a
551      * composing region, the characters are left as they were and the
552      * composing span removed, as if {@link #finishComposingText()}
553      * has been called. The default style for composing text is used.
554      *
555      * <p>The passed indices are clipped to the contents bounds. If
556      * the resulting region is zero-sized, no region is marked and the
557      * effect is the same as that of calling {@link #finishComposingText()}.
558      * The order of start and end is not important. In effect, the
559      * region from start to end and the region from end to start is
560      * the same. Editor authors, be ready to accept a start that is
561      * greater than end.</p>
562      *
563      * <p>Since this does not change the contents of the text, editors should not call
564      * {@link InputMethodManager#updateSelection(View, int, int, int, int)} and
565      * IMEs should not receive
566      * {@link android.inputmethodservice.InputMethodService#onUpdateSelection(int, int, int, int,
567      * int, int)}.</p>
568      *
569      * <p>This has no impact on the cursor/selection position. It may
570      * result in the cursor being anywhere inside or outside the
571      * composing region, including cases where the selection and the
572      * composing region overlap partially or entirely.</p>
573      *
574      * @param start the position in the text at which the composing region begins
575      * @param end the position in the text at which the composing region ends
576      * @return true on success, false if the input connection is no longer
577      * valid. In {@link android.os.Build.VERSION_CODES#N} and later, false is returned when the
578      * target application does not implement this method.
579      */
setComposingRegion(int start, int end)580     boolean setComposingRegion(int start, int end);
581 
582     /**
583      * Have the text editor finish whatever composing text is
584      * currently active. This simply leaves the text as-is, removing
585      * any special composing styling or other state that was around
586      * it. The cursor position remains unchanged.
587      *
588      * <p><strong>IME authors:</strong> be aware that this call may be
589      * expensive with some editors.</p>
590      *
591      * <p><strong>Editor authors:</strong> please note that the cursor
592      * may be anywhere in the contents when this is called, including
593      * in the middle of the composing span or in a completely
594      * unrelated place. It must not move.</p>
595      *
596      * @return true on success, false if the input connection
597      * is no longer valid.
598      */
finishComposingText()599     boolean finishComposingText();
600 
601     /**
602      * Commit text to the text box and set the new cursor position.
603      *
604      * <p>This method removes the contents of the currently composing
605      * text and replaces it with the passed CharSequence, and then
606      * moves the cursor according to {@code newCursorPosition}. If there
607      * is no composing text when this method is called, the new text is
608      * inserted at the cursor position, removing text inside the selection
609      * if any. This behaves like calling
610      * {@link #setComposingText(CharSequence, int) setComposingText(text, newCursorPosition)}
611      * then {@link #finishComposingText()}.</p>
612      *
613      * <p>Calling this method will cause the editor to call
614      * {@link android.inputmethodservice.InputMethodService#onUpdateSelection(int, int, int, int,
615      * int, int)} on the current IME after the batch input is over.
616      * <strong>Editor authors</strong>, for this to happen you need to
617      * make the changes known to the input method by calling
618      * {@link InputMethodManager#updateSelection(View, int, int, int, int)},
619      * but be careful to wait until the batch edit is over if one is
620      * in progress.</p>
621      *
622      * @param text The text to commit. This may include styles.
623      * @param newCursorPosition The new cursor position around the text,
624      *        in Java characters. If > 0, this is relative to the end
625      *        of the text - 1; if <= 0, this is relative to the start
626      *        of the text. So a value of 1 will always advance the cursor
627      *        to the position after the full text being inserted. Note that
628      *        this means you can't position the cursor within the text,
629      *        because the editor can make modifications to the text
630      *        you are providing so it is not possible to correctly specify
631      *        locations there.
632      * @return true on success, false if the input connection is no longer
633      * valid.
634      */
commitText(CharSequence text, int newCursorPosition)635     boolean commitText(CharSequence text, int newCursorPosition);
636 
637     /**
638      * Commit a completion the user has selected from the possible ones
639      * previously reported to {@link InputMethodSession#displayCompletions
640      * InputMethodSession#displayCompletions(CompletionInfo[])} or
641      * {@link InputMethodManager#displayCompletions
642      * InputMethodManager#displayCompletions(View, CompletionInfo[])}.
643      * This will result in the same behavior as if the user had
644      * selected the completion from the actual UI. In all other
645      * respects, this behaves like {@link #commitText(CharSequence, int)}.
646      *
647      * <p><strong>IME authors:</strong> please take care to send the
648      * same object that you received through
649      * {@link android.inputmethodservice.InputMethodService#onDisplayCompletions(CompletionInfo[])}.
650      * </p>
651      *
652      * <p><strong>Editor authors:</strong> if you never call
653      * {@link InputMethodSession#displayCompletions(CompletionInfo[])} or
654      * {@link InputMethodManager#displayCompletions(View, CompletionInfo[])} then
655      * a well-behaved IME should never call this on your input
656      * connection, but be ready to deal with misbehaving IMEs without
657      * crashing.</p>
658      *
659      * <p>Calling this method (with a valid {@link CompletionInfo} object)
660      * will cause the editor to call
661      * {@link android.inputmethodservice.InputMethodService#onUpdateSelection(int, int, int, int,
662      * int, int)} on the current IME after the batch input is over.
663      * <strong>Editor authors</strong>, for this to happen you need to
664      * make the changes known to the input method by calling
665      * {@link InputMethodManager#updateSelection(View, int, int, int, int)},
666      * but be careful to wait until the batch edit is over if one is
667      * in progress.</p>
668      *
669      * @param text The committed completion.
670      * @return true on success, false if the input connection is no longer
671      * valid.
672      */
commitCompletion(CompletionInfo text)673     boolean commitCompletion(CompletionInfo text);
674 
675     /**
676      * Commit a correction automatically performed on the raw user's input. A
677      * typical example would be to correct typos using a dictionary.
678      *
679      * <p>Calling this method will cause the editor to call
680      * {@link android.inputmethodservice.InputMethodService#onUpdateSelection(int, int, int, int,
681      * int, int)} on the current IME after the batch input is over.
682      * <strong>Editor authors</strong>, for this to happen you need to
683      * make the changes known to the input method by calling
684      * {@link InputMethodManager#updateSelection(View, int, int, int, int)},
685      * but be careful to wait until the batch edit is over if one is
686      * in progress.</p>
687      *
688      * @param correctionInfo Detailed information about the correction.
689      * @return true on success, false if the input connection is no longer valid.
690      * In {@link android.os.Build.VERSION_CODES#N} and later, returns false
691      * when the target application does not implement this method.
692      */
commitCorrection(CorrectionInfo correctionInfo)693     boolean commitCorrection(CorrectionInfo correctionInfo);
694 
695     /**
696      * Set the selection of the text editor. To set the cursor
697      * position, start and end should have the same value.
698      *
699      * <p>Since this moves the cursor, calling this method will cause
700      * the editor to call
701      * {@link android.inputmethodservice.InputMethodService#onUpdateSelection(int, int, int, int,
702      * int, int)} on the current IME after the batch input is over.
703      * <strong>Editor authors</strong>, for this to happen you need to
704      * make the changes known to the input method by calling
705      * {@link InputMethodManager#updateSelection(View, int, int, int, int)},
706      * but be careful to wait until the batch edit is over if one is
707      * in progress.</p>
708      *
709      * <p>This has no effect on the composing region which must stay
710      * unchanged. The order of start and end is not important. In
711      * effect, the region from start to end and the region from end to
712      * start is the same. Editor authors, be ready to accept a start
713      * that is greater than end.</p>
714      *
715      * @param start the character index where the selection should start.
716      * @param end the character index where the selection should end.
717      * @return true on success, false if the input connection is no longer
718      * valid.
719      */
setSelection(int start, int end)720     boolean setSelection(int start, int end);
721 
722     /**
723      * Have the editor perform an action it has said it can do.
724      *
725      * <p>This is typically used by IMEs when the user presses the key
726      * associated with the action.</p>
727      *
728      * @param editorAction This must be one of the action constants for
729      * {@link EditorInfo#imeOptions EditorInfo.editorType}, such as
730      * {@link EditorInfo#IME_ACTION_GO EditorInfo.EDITOR_ACTION_GO}.
731      * @return true on success, false if the input connection is no longer
732      * valid.
733      */
performEditorAction(int editorAction)734     boolean performEditorAction(int editorAction);
735 
736     /**
737      * Perform a context menu action on the field. The given id may be one of:
738      * {@link android.R.id#selectAll},
739      * {@link android.R.id#startSelectingText}, {@link android.R.id#stopSelectingText},
740      * {@link android.R.id#cut}, {@link android.R.id#copy},
741      * {@link android.R.id#paste}, {@link android.R.id#copyUrl},
742      * or {@link android.R.id#switchInputMethod}
743      */
performContextMenuAction(int id)744     boolean performContextMenuAction(int id);
745 
746     /**
747      * Tell the editor that you are starting a batch of editor
748      * operations. The editor will try to avoid sending you updates
749      * about its state until {@link #endBatchEdit} is called. Batch
750      * edits nest.
751      *
752      * <p><strong>IME authors:</strong> use this to avoid getting
753      * calls to
754      * {@link android.inputmethodservice.InputMethodService#onUpdateSelection(int, int, int, int,
755      * int, int)} corresponding to intermediate state. Also, use this to avoid
756      * flickers that may arise from displaying intermediate state. Be
757      * sure to call {@link #endBatchEdit} for each call to this, or
758      * you may block updates in the editor.</p>
759      *
760      * <p><strong>Editor authors:</strong> while a batch edit is in
761      * progress, take care not to send updates to the input method and
762      * not to update the display. IMEs use this intensively to this
763      * effect. Also please note that batch edits need to nest
764      * correctly.</p>
765      *
766      * @return true if a batch edit is now in progress, false otherwise. Since
767      * this method starts a batch edit, that means it will always return true
768      * unless the input connection is no longer valid.
769      */
beginBatchEdit()770     boolean beginBatchEdit();
771 
772     /**
773      * Tell the editor that you are done with a batch edit previously
774      * initiated with {@link #beginBatchEdit}. This ends the latest
775      * batch only.
776      *
777      * <p><strong>IME authors:</strong> make sure you call this
778      * exactly once for each call to {@link #beginBatchEdit}.</p>
779      *
780      * <p><strong>Editor authors:</strong> please be careful about
781      * batch edit nesting. Updates still to be held back until the end
782      * of the last batch edit.</p>
783      *
784      * @return true if there is still a batch edit in progress after closing
785      * the latest one (in other words, if the nesting count is > 0), false
786      * otherwise or if the input connection is no longer valid.
787      */
endBatchEdit()788     boolean endBatchEdit();
789 
790     /**
791      * Send a key event to the process that is currently attached
792      * through this input connection. The event will be dispatched
793      * like a normal key event, to the currently focused view; this
794      * generally is the view that is providing this InputConnection,
795      * but due to the asynchronous nature of this protocol that can
796      * not be guaranteed and the focus may have changed by the time
797      * the event is received.
798      *
799      * <p>This method can be used to send key events to the
800      * application. For example, an on-screen keyboard may use this
801      * method to simulate a hardware keyboard. There are three types
802      * of standard keyboards, numeric (12-key), predictive (20-key)
803      * and ALPHA (QWERTY). You can specify the keyboard type by
804      * specify the device id of the key event.</p>
805      *
806      * <p>You will usually want to set the flag
807      * {@link KeyEvent#FLAG_SOFT_KEYBOARD KeyEvent.FLAG_SOFT_KEYBOARD}
808      * on all key event objects you give to this API; the flag will
809      * not be set for you.</p>
810      *
811      * <p>Note that it's discouraged to send such key events in normal
812      * operation; this is mainly for use with
813      * {@link android.text.InputType#TYPE_NULL} type text fields. Use
814      * the {@link #commitText} family of methods to send text to the
815      * application instead.</p>
816      *
817      * @param event The key event.
818      * @return true on success, false if the input connection is no longer
819      * valid.
820      *
821      * @see KeyEvent
822      * @see KeyCharacterMap#NUMERIC
823      * @see KeyCharacterMap#PREDICTIVE
824      * @see KeyCharacterMap#ALPHA
825      */
sendKeyEvent(KeyEvent event)826     boolean sendKeyEvent(KeyEvent event);
827 
828     /**
829      * Clear the given meta key pressed states in the given input
830      * connection.
831      *
832      * <p>This can be used by the IME to clear the meta key states set
833      * by a hardware keyboard with latched meta keys, if the editor
834      * keeps track of these.</p>
835      *
836      * @param states The states to be cleared, may be one or more bits as
837      * per {@link KeyEvent#getMetaState() KeyEvent.getMetaState()}.
838      * @return true on success, false if the input connection is no longer
839      * valid.
840      */
clearMetaKeyStates(int states)841     boolean clearMetaKeyStates(int states);
842 
843     /**
844      * Called back when the connected IME switches between fullscreen and normal modes.
845      *
846      * <p>Note: On {@link android.os.Build.VERSION_CODES#O} and later devices, input methods are no
847      * longer allowed to directly call this method at any time. To signal this event in the target
848      * application, input methods should always call
849      * {@link InputMethodService#updateFullscreenMode()} instead. This approach should work on API
850      * {@link android.os.Build.VERSION_CODES#N_MR1} and prior devices.</p>
851      *
852      * @return For editor authors, the return value will always be ignored. For IME authors, this
853      *         always returns {@code true} on {@link android.os.Build.VERSION_CODES#N_MR1} and prior
854      *         devices and {@code false} on {@link android.os.Build.VERSION_CODES#O} and later
855      *         devices.
856      * @see InputMethodManager#isFullscreenMode()
857      */
reportFullscreenMode(boolean enabled)858     boolean reportFullscreenMode(boolean enabled);
859 
860     /**
861      * Have the editor perform spell checking for the full content.
862      *
863      * <p>The editor can ignore this method call if it does not support spell checking.
864      *
865      * @return For editor authors, the return value will always be ignored. For IME authors, this
866      *         method returns true if the spell check request was sent (whether or not the
867      *         associated editor supports spell checking), false if the input connection is no
868      *         longer valid.
869      */
performSpellCheck()870     default boolean performSpellCheck() {
871         return false;
872     }
873 
874     /**
875      * API to send private commands from an input method to its
876      * connected editor. This can be used to provide domain-specific
877      * features that are only known between certain input methods and
878      * their clients. Note that because the InputConnection protocol
879      * is asynchronous, you have no way to get a result back or know
880      * if the client understood the command; you can use the
881      * information in {@link EditorInfo} to determine if a client
882      * supports a particular command.
883      *
884      * @param action Name of the command to be performed. This <em>must</em>
885      * be a scoped name, i.e. prefixed with a package name you own, so that
886      * different developers will not create conflicting commands.
887      * @param data Any data to include with the command.
888      * @return true if the command was sent (whether or not the
889      * associated editor understood it), false if the input connection is no longer
890      * valid.
891      */
performPrivateCommand(String action, Bundle data)892     boolean performPrivateCommand(String action, Bundle data);
893 
894     /**
895      * The editor is requested to call
896      * {@link InputMethodManager#updateCursorAnchorInfo(android.view.View, CursorAnchorInfo)} at
897      * once, as soon as possible, regardless of cursor/anchor position changes. This flag can be
898      * used together with {@link #CURSOR_UPDATE_MONITOR}.
899      */
900     int CURSOR_UPDATE_IMMEDIATE = 1 << 0;
901 
902     /**
903      * The editor is requested to call
904      * {@link InputMethodManager#updateCursorAnchorInfo(android.view.View, CursorAnchorInfo)}
905      * whenever cursor/anchor position is changed. To disable monitoring, call
906      * {@link InputConnection#requestCursorUpdates(int)} again with this flag off.
907      * <p>
908      * This flag can be used together with {@link #CURSOR_UPDATE_IMMEDIATE}.
909      * </p>
910      */
911     int CURSOR_UPDATE_MONITOR = 1 << 1;
912 
913     /**
914      * Called by the input method to ask the editor for calling back
915      * {@link InputMethodManager#updateCursorAnchorInfo(android.view.View, CursorAnchorInfo)} to
916      * notify cursor/anchor locations.
917      *
918      * @param cursorUpdateMode {@link #CURSOR_UPDATE_IMMEDIATE} and/or
919      * {@link #CURSOR_UPDATE_MONITOR}. Pass {@code 0} to disable the effect of
920      * {@link #CURSOR_UPDATE_MONITOR}.
921      * @return {@code true} if the request is scheduled. {@code false} to indicate that when the
922      * application will not call
923      * {@link InputMethodManager#updateCursorAnchorInfo(android.view.View, CursorAnchorInfo)}.
924      * In {@link android.os.Build.VERSION_CODES#N} and later, returns {@code false} also when the
925      * target application does not implement this method.
926      */
requestCursorUpdates(int cursorUpdateMode)927     boolean requestCursorUpdates(int cursorUpdateMode);
928 
929     /**
930      * Called by the {@link InputMethodManager} to enable application developers to specify a
931      * dedicated {@link Handler} on which incoming IPC method calls from input methods will be
932      * dispatched.
933      *
934      * <p>Note: This does nothing when called from input methods.</p>
935      *
936      * @return {@code null} to use the default {@link Handler}.
937      */
getHandler()938     Handler getHandler();
939 
940     /**
941      * Called by the system up to only once to notify that the system is about to invalidate
942      * connection between the input method and the application.
943      *
944      * <p><strong>Editor authors</strong>: You can clear all the nested batch edit right now and
945      * you no longer need to handle subsequent callbacks on this connection, including
946      * {@link #beginBatchEdit()}}.  Note that although the system tries to call this method whenever
947      * possible, there may be a chance that this method is not called in some exceptional
948      * situations.</p>
949      *
950      * <p>Note: This does nothing when called from input methods.</p>
951      */
closeConnection()952     void closeConnection();
953 
954     /**
955      * When this flag is used, the editor will be able to request read access to the content URI
956      * contained in the {@link InputContentInfo} object.
957      *
958      * <p>Make sure that the content provider owning the Uri sets the
959      * {@link android.R.styleable#AndroidManifestProvider_grantUriPermissions
960      * grantUriPermissions} attribute in its manifest or included the
961      * {@link android.R.styleable#AndroidManifestGrantUriPermission
962      * &lt;grant-uri-permissions&gt;} tag. Otherwise {@link InputContentInfo#requestPermission()}
963      * can fail.</p>
964      *
965      * <p>Although calling this API is allowed only for the IME that is currently selected, the
966      * client is able to request a temporary read-only access even after the current IME is switched
967      * to any other IME as long as the client keeps {@link InputContentInfo} object.</p>
968      **/
969     int INPUT_CONTENT_GRANT_READ_URI_PERMISSION =
970             android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION;  // 0x00000001
971 
972     /**
973      * Called by the input method to commit content such as a PNG image to the editor.
974      *
975      * <p>In order to avoid a variety of compatibility issues, this focuses on a simple use case,
976      * where editors and IMEs are expected to work cooperatively as follows:</p>
977      * <ul>
978      *     <li>Editor must keep {@link EditorInfo#contentMimeTypes} equal to {@code null} if it does
979      *     not support this method at all.</li>
980      *     <li>Editor can ignore this request when the MIME type specified in
981      *     {@code inputContentInfo} does not match any of {@link EditorInfo#contentMimeTypes}.
982      *     </li>
983      *     <li>Editor can ignore the cursor position when inserting the provided content.</li>
984      *     <li>Editor can return {@code true} asynchronously, even before it starts loading the
985      *     content.</li>
986      *     <li>Editor should provide a way to delete the content inserted by this method or to
987      *     revert the effect caused by this method.</li>
988      *     <li>IME should not call this method when there is any composing text, in case calling
989      *     this method causes a focus change.</li>
990      *     <li>IME should grant a permission for the editor to read the content. See
991      *     {@link EditorInfo#packageName} about how to obtain the package name of the editor.</li>
992      * </ul>
993      *
994      * @param inputContentInfo Content to be inserted.
995      * @param flags {@link #INPUT_CONTENT_GRANT_READ_URI_PERMISSION} if the content provider
996      * allows {@link android.R.styleable#AndroidManifestProvider_grantUriPermissions
997      * grantUriPermissions} or {@code 0} if the application does not need to call
998      * {@link InputContentInfo#requestPermission()}.
999      * @param opts optional bundle data. This can be {@code null}.
1000      * @return {@code true} if this request is accepted by the application, whether the request
1001      * is already handled or still being handled in background, {@code false} otherwise.
1002      */
commitContent(@onNull InputContentInfo inputContentInfo, int flags, @Nullable Bundle opts)1003     boolean commitContent(@NonNull InputContentInfo inputContentInfo, int flags,
1004             @Nullable Bundle opts);
1005 
1006     /**
1007      * Called by the input method to indicate that it consumes all input for itself, or no longer
1008      * does so.
1009      *
1010      * <p>Editors should reflect that they are not receiving input by hiding the cursor if
1011      * {@code imeConsumesInput} is {@code true}, and resume showing the cursor if it is
1012      * {@code false}.
1013      *
1014      * @param imeConsumesInput {@code true} when the IME is consuming input and the cursor should be
1015      * hidden, {@code false} when input to the editor resumes and the cursor should be shown again.
1016      * @return For editor authors, the return value will always be ignored. For IME authors, this
1017      *         method returns {@code true} if the request was sent (whether or not the associated
1018      *         editor does something based on this request), {@code false} if the input connection
1019      *         is no longer valid.
1020      */
setImeConsumesInput(boolean imeConsumesInput)1021     default boolean setImeConsumesInput(boolean imeConsumesInput) {
1022         return false;
1023     }
1024 }
1025