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.NonNull;
20 import android.annotation.Nullable;
21 import android.inputmethodservice.InputMethodService;
22 import android.os.Bundle;
23 import android.os.Handler;
24 import android.view.KeyCharacterMap;
25 import android.view.KeyEvent;
26 
27 /**
28  * The InputConnection interface is the communication channel from an
29  * {@link InputMethod} back to the application that is receiving its
30  * input. It is used to perform such things as reading text around the
31  * cursor, committing text to the text box, and sending raw key events
32  * to the application.
33  *
34  * <p>Starting from API Level {@link android.os.Build.VERSION_CODES#N},
35  * the system can deal with the situation where the application directly
36  * implements this class but one or more of the following methods are
37  * not implemented.</p>
38  * <ul>
39  *     <li>{@link #getSelectedText(int)}, which was introduced in
40  *     {@link android.os.Build.VERSION_CODES#GINGERBREAD}.</li>
41  *     <li>{@link #setComposingRegion(int, int)}, which was introduced
42  *     in {@link android.os.Build.VERSION_CODES#GINGERBREAD}.</li>
43  *     <li>{@link #commitCorrection(CorrectionInfo)}, which was introduced
44  *     in {@link android.os.Build.VERSION_CODES#HONEYCOMB}.</li>
45  *     <li>{@link #requestCursorUpdates(int)}, which was introduced in
46  *     {@link android.os.Build.VERSION_CODES#LOLLIPOP}.</li>
47  *     <li>{@link #deleteSurroundingTextInCodePoints(int, int)}, which
48  *     was introduced in {@link android.os.Build.VERSION_CODES#N}.</li>
49  *     <li>{@link #getHandler()}, which was introduced in
50  *     {@link android.os.Build.VERSION_CODES#N}.</li>
51  *     <li>{@link #closeConnection()}, which was introduced in
52  *     {@link android.os.Build.VERSION_CODES#N}.</li>
53  *     <li>{@link #commitContent(InputContentInfo, int, Bundle)}, which was
54  *     introduced in {@link android.os.Build.VERSION_CODES#N_MR1}.</li>
55  * </ul>
56  *
57  * <h3>Implementing an IME or an editor</h3>
58  * <p>Text input is the result of the synergy of two essential components:
59  * an Input Method Engine (IME) and an editor. The IME can be a
60  * software keyboard, a handwriting interface, an emoji palette, a
61  * speech-to-text engine, and so on. There are typically several IMEs
62  * installed on any given Android device. In Android, IMEs extend
63  * {@link android.inputmethodservice.InputMethodService}.
64  * For more information about how to create an IME, see the
65  * <a href="{@docRoot}guide/topics/text/creating-input-method.html">
66  * Creating an input method</a> guide.
67  *
68  * The editor is the component that receives text and displays it.
69  * Typically, this is an {@link android.widget.EditText} instance, but
70  * some applications may choose to implement their own editor for
71  * various reasons. This is a large and complicated task, and an
72  * application that does this needs to make sure the behavior is
73  * consistent with standard EditText behavior in Android. An editor
74  * needs to interact with the IME, receiving commands through
75  * this InputConnection interface, and sending commands through
76  * {@link android.view.inputmethod.InputMethodManager}. An editor
77  * should start by implementing
78  * {@link android.view.View#onCreateInputConnection(EditorInfo)}
79  * to return its own input connection.</p>
80  *
81  * <p>If you are implementing your own IME, you will need to call the
82  * methods in this interface to interact with the application. Be sure
83  * to test your IME with a wide range of applications, including
84  * browsers and rich text editors, as some may have peculiarities you
85  * need to deal with. Remember your IME may not be the only source of
86  * changes on the text, and try to be as conservative as possible in
87  * the data you send and as liberal as possible in the data you
88  * receive.</p>
89  *
90  * <p>If you are implementing your own editor, you will probably need
91  * to provide your own subclass of {@link BaseInputConnection} to
92  * answer to the commands from IMEs. Please be sure to test your
93  * editor with as many IMEs as you can as their behavior can vary a
94  * lot. Also be sure to test with various languages, including CJK
95  * languages and right-to-left languages like Arabic, as these may
96  * have different input requirements. When in doubt about the
97  * behavior you should adopt for a particular call, please mimic the
98  * default TextView implementation in the latest Android version, and
99  * if you decide to drift from it, please consider carefully that
100  * inconsistencies in text editor behavior is almost universally felt
101  * as a bad thing by users.</p>
102  *
103  * <h3>Cursors, selections and compositions</h3>
104  * <p>In Android, the cursor and the selection are one and the same
105  * thing. A "cursor" is just the special case of a zero-sized
106  * selection. As such, this documentation uses them
107  * interchangeably. Any method acting "before the cursor" would act
108  * before the start of the selection if there is one, and any method
109  * acting "after the cursor" would act after the end of the
110  * selection.</p>
111  *
112  * <p>An editor needs to be able to keep track of a currently
113  * "composing" region, like the standard edition widgets do. The
114  * composition is marked in a specific style: see
115  * {@link android.text.Spanned#SPAN_COMPOSING}. IMEs use this to help
116  * the user keep track of what part of the text they are currently
117  * focusing on, and interact with the editor using
118  * {@link InputConnection#setComposingText(CharSequence, int)},
119  * {@link InputConnection#setComposingRegion(int, int)} and
120  * {@link InputConnection#finishComposingText()}.
121  * The composing region and the selection are completely independent
122  * of each other, and the IME may use them however they see fit.</p>
123  */
124 public interface InputConnection {
125     /**
126      * Flag for use with {@link #getTextAfterCursor} and
127      * {@link #getTextBeforeCursor} to have style information returned
128      * along with the text. If not set, {@link #getTextAfterCursor}
129      * sends only the raw text, without style or other spans. If set,
130      * it may return a complex CharSequence of both text and style
131      * spans. <strong>Editor authors</strong>: you should strive to
132      * send text with styles if possible, but it is not required.
133      */
134     int GET_TEXT_WITH_STYLES = 0x0001;
135 
136     /**
137      * Flag for use with {@link #getExtractedText} to indicate you
138      * would like to receive updates when the extracted text changes.
139      */
140     int GET_EXTRACTED_TEXT_MONITOR = 0x0001;
141 
142     /**
143      * Get <var>n</var> characters of text before the current cursor
144      * position.
145      *
146      * <p>This method may fail either if the input connection has
147      * become invalid (such as its process crashing) or the editor is
148      * taking too long to respond with the text (it is given a couple
149      * seconds to return). In either case, null is returned. This
150      * method does not affect the text in the editor in any way, nor
151      * does it affect the selection or composing spans.</p>
152      *
153      * <p>If {@link #GET_TEXT_WITH_STYLES} is supplied as flags, the
154      * editor should return a {@link android.text.SpannableString}
155      * with all the spans set on the text.</p>
156      *
157      * <p><strong>IME authors:</strong> please consider this will
158      * trigger an IPC round-trip that will take some time. Assume this
159      * method consumes a lot of time. Also, please keep in mind the
160      * Editor may choose to return less characters than requested even
161      * if they are available for performance reasons.</p>
162      *
163      * <p><strong>Editor authors:</strong> please be careful of race
164      * conditions in implementing this call. An IME can make a change
165      * to the text and use this method right away; you need to make
166      * sure the returned value is consistent with the result of the
167      * latest edits. Also, you may return less than n characters if performance
168      * dictates so, but keep in mind IMEs are relying on this for many
169      * functions: you should not, for example, limit the returned value to
170      * the current line, and specifically do not return 0 characters unless
171      * the cursor is really at the start of the text.</p>
172      *
173      * @param n The expected length of the text.
174      * @param flags Supplies additional options controlling how the text is
175      * returned. May be either 0 or {@link #GET_TEXT_WITH_STYLES}.
176      * @return the text before the cursor position; the length of the
177      * returned text might be less than <var>n</var>.
178      */
getTextBeforeCursor(int n, int flags)179     CharSequence getTextBeforeCursor(int n, int flags);
180 
181     /**
182      * Get <var>n</var> characters of text after the current cursor
183      * position.
184      *
185      * <p>This method may fail either if the input connection has
186      * become invalid (such as its process crashing) or the client is
187      * taking too long to respond with the text (it is given a couple
188      * seconds to return). In either case, null is returned.
189      *
190      * <p>This method does not affect the text in the editor in any
191      * way, nor does it affect the selection or composing spans.</p>
192      *
193      * <p>If {@link #GET_TEXT_WITH_STYLES} is supplied as flags, the
194      * editor should return a {@link android.text.SpannableString}
195      * with all the spans set on the text.</p>
196      *
197      * <p><strong>IME authors:</strong> please consider this will
198      * trigger an IPC round-trip that will take some time. Assume this
199      * method consumes a lot of time.</p>
200      *
201      * <p><strong>Editor authors:</strong> please be careful of race
202      * conditions in implementing this call. An IME can make a change
203      * to the text and use this method right away; you need to make
204      * sure the returned value is consistent with the result of the
205      * latest edits. Also, you may return less than n characters if performance
206      * dictates so, but keep in mind IMEs are relying on this for many
207      * functions: you should not, for example, limit the returned value to
208      * the current line, and specifically do not return 0 characters unless
209      * the cursor is really at the end of the text.</p>
210      *
211      * @param n The expected length of the text.
212      * @param flags Supplies additional options controlling how the text is
213      * returned. May be either 0 or {@link #GET_TEXT_WITH_STYLES}.
214      *
215      * @return the text after the cursor position; the length of the
216      * returned text might be less than <var>n</var>.
217      */
getTextAfterCursor(int n, int flags)218     CharSequence getTextAfterCursor(int n, int flags);
219 
220     /**
221      * Gets the selected text, if any.
222      *
223      * <p>This method may fail if either the input connection has
224      * become invalid (such as its process crashing) or the client is
225      * taking too long to respond with the text (it is given a couple
226      * of seconds to return). In either case, null is returned.</p>
227      *
228      * <p>This method must not cause any changes in the editor's
229      * state.</p>
230      *
231      * <p>If {@link #GET_TEXT_WITH_STYLES} is supplied as flags, the
232      * editor should return a {@link android.text.SpannableString}
233      * with all the spans set on the text.</p>
234      *
235      * <p><strong>IME authors:</strong> please consider this will
236      * trigger an IPC round-trip that will take some time. Assume this
237      * method consumes a lot of time.</p>
238      *
239      * <p><strong>Editor authors:</strong> please be careful of race
240      * conditions in implementing this call. An IME can make a change
241      * to the text or change the selection position and use this
242      * method right away; you need to make sure the returned value is
243      * consistent with the results of the latest edits.</p>
244      *
245      * @param flags Supplies additional options controlling how the text is
246      * returned. May be either 0 or {@link #GET_TEXT_WITH_STYLES}.
247      * @return the text that is currently selected, if any, or null if
248      * no text is selected. In {@link android.os.Build.VERSION_CODES#N} and
249      * later, returns false when the target application does not implement
250      * this method.
251      */
getSelectedText(int flags)252     CharSequence getSelectedText(int flags);
253 
254     /**
255      * Retrieve the current capitalization mode in effect at the
256      * current cursor position in the text. See
257      * {@link android.text.TextUtils#getCapsMode TextUtils.getCapsMode}
258      * for more information.
259      *
260      * <p>This method may fail either if the input connection has
261      * become invalid (such as its process crashing) or the client is
262      * taking too long to respond with the text (it is given a couple
263      * seconds to return). In either case, 0 is returned.</p>
264      *
265      * <p>This method does not affect the text in the editor in any
266      * way, nor does it affect the selection or composing spans.</p>
267      *
268      * <p><strong>Editor authors:</strong> please be careful of race
269      * conditions in implementing this call. An IME can change the
270      * cursor position and use this method right away; you need to make
271      * sure the returned value is consistent with the results of the
272      * latest edits and changes to the cursor position.</p>
273      *
274      * @param reqModes The desired modes to retrieve, as defined by
275      * {@link android.text.TextUtils#getCapsMode TextUtils.getCapsMode}. These
276      * constants are defined so that you can simply pass the current
277      * {@link EditorInfo#inputType TextBoxAttribute.contentType} value
278      * directly in to here.
279      * @return the caps mode flags that are in effect at the current
280      * cursor position. See TYPE_TEXT_FLAG_CAPS_* in {@link android.text.InputType}.
281      */
getCursorCapsMode(int reqModes)282     int getCursorCapsMode(int reqModes);
283 
284     /**
285      * Retrieve the current text in the input connection's editor, and
286      * monitor for any changes to it. This function returns with the
287      * current text, and optionally the input connection can send
288      * updates to the input method when its text changes.
289      *
290      * <p>This method may fail either if the input connection has
291      * become invalid (such as its process crashing) or the client is
292      * taking too long to respond with the text (it is given a couple
293      * seconds to return). In either case, null is returned.</p>
294      *
295      * <p>Editor authors: as a general rule, try to comply with the
296      * fields in <code>request</code> for how many chars to return,
297      * but if performance or convenience dictates otherwise, please
298      * feel free to do what is most appropriate for your case. Also,
299      * if the
300      * {@link #GET_EXTRACTED_TEXT_MONITOR} flag is set, you should be
301      * calling
302      * {@link InputMethodManager#updateExtractedText(View, int, ExtractedText)}
303      * whenever you call
304      * {@link InputMethodManager#updateSelection(View, int, int, int, int)}.</p>
305      *
306      * @param request Description of how the text should be returned.
307      * {@link android.view.inputmethod.ExtractedTextRequest}
308      * @param flags Additional options to control the client, either 0 or
309      * {@link #GET_EXTRACTED_TEXT_MONITOR}.
310 
311      * @return an {@link android.view.inputmethod.ExtractedText}
312      * object describing the state of the text view and containing the
313      * extracted text itself, or null if the input connection is no
314      * longer valid of the editor can't comply with the request for
315      * some reason.
316      */
getExtractedText(ExtractedTextRequest request, int flags)317     ExtractedText getExtractedText(ExtractedTextRequest request, int flags);
318 
319     /**
320      * Delete <var>beforeLength</var> characters of text before the
321      * current cursor position, and delete <var>afterLength</var>
322      * characters of text after the current cursor position, excluding
323      * the selection. Before and after refer to the order of the
324      * characters in the string, not to their visual representation:
325      * this means you don't have to figure out the direction of the
326      * text and can just use the indices as-is.
327      *
328      * <p>The lengths are supplied in Java chars, not in code points
329      * or in glyphs.</p>
330      *
331      * <p>Since this method only operates on text before and after the
332      * selection, it can't affect the contents of the selection. This
333      * may affect the composing span if the span includes characters
334      * that are to be deleted, but otherwise will not change it. If
335      * some characters in the composing span are deleted, the
336      * composing span will persist but get shortened by however many
337      * chars inside it have been removed.</p>
338      *
339      * <p><strong>IME authors:</strong> please be careful not to
340      * delete only half of a surrogate pair. Also take care not to
341      * delete more characters than are in the editor, as that may have
342      * ill effects on the application. Calling this method will cause
343      * the editor to call
344      * {@link android.inputmethodservice.InputMethodService#onUpdateSelection(int, int, int, int,
345      * int, int)} on your service after the batch input is over.</p>
346      *
347      * <p><strong>Editor authors:</strong> please be careful of race
348      * conditions in implementing this call. An IME can make a change
349      * to the text or change the selection position and use this
350      * method right away; you need to make sure the effects are
351      * consistent with the results of the latest edits. Also, although
352      * the IME should not send lengths bigger than the contents of the
353      * string, you should check the values for overflows and trim the
354      * indices to the size of the contents to avoid crashes. Since
355      * this changes the contents of the editor, you need to make the
356      * changes known to the input method by calling
357      * {@link InputMethodManager#updateSelection(View, int, int, int, int)},
358      * but be careful to wait until the batch edit is over if one is
359      * in progress.</p>
360      *
361      * @param beforeLength The number of characters before the cursor to be deleted, in code unit.
362      *        If this is greater than the number of existing characters between the beginning of the
363      *        text and the cursor, then this method does not fail but deletes all the characters in
364      *        that range.
365      * @param afterLength The number of characters after the cursor to be deleted, in code unit.
366      *        If this is greater than the number of existing characters between the cursor and
367      *        the end of the text, then this method does not fail but deletes all the characters in
368      *        that range.
369      * @return true on success, false if the input connection is no longer valid.
370      */
deleteSurroundingText(int beforeLength, int afterLength)371     boolean deleteSurroundingText(int beforeLength, int afterLength);
372 
373     /**
374      * A variant of {@link #deleteSurroundingText(int, int)}. Major differences are:
375      *
376      * <ul>
377      *     <li>The lengths are supplied in code points, not in Java chars or in glyphs.</>
378      *     <li>This method does nothing if there are one or more invalid surrogate pairs in the
379      *     requested range.</li>
380      * </ul>
381      *
382      * <p><strong>Editor authors:</strong> In addition to the requirement in
383      * {@link #deleteSurroundingText(int, int)}, make sure to do nothing when one ore more invalid
384      * surrogate pairs are found in the requested range.</p>
385      *
386      * @see #deleteSurroundingText(int, int)
387      *
388      * @param beforeLength The number of characters before the cursor to be deleted, in code points.
389      *        If this is greater than the number of existing characters between the beginning of the
390      *        text and the cursor, then this method does not fail but deletes all the characters in
391      *        that range.
392      * @param afterLength The number of characters after the cursor to be deleted, in code points.
393      *        If this is greater than the number of existing characters between the cursor and
394      *        the end of the text, then this method does not fail but deletes all the characters in
395      *        that range.
396      * @return true on success, false if the input connection is no longer valid.  Returns
397      * {@code false} when the target application does not implement this method.
398      */
deleteSurroundingTextInCodePoints(int beforeLength, int afterLength)399     boolean deleteSurroundingTextInCodePoints(int beforeLength, int afterLength);
400 
401     /**
402      * Replace the currently composing text with the given text, and
403      * set the new cursor position. Any composing text set previously
404      * will be removed automatically.
405      *
406      * <p>If there is any composing span currently active, all
407      * characters that it comprises are removed. The passed text is
408      * added in its place, and a composing span is added to this
409      * text. If there is no composing span active, the passed text is
410      * added at the cursor position (removing selected characters
411      * first if any), and a composing span is added on the new text.
412      * Finally, the cursor is moved to the location specified by
413      * <code>newCursorPosition</code>.</p>
414      *
415      * <p>This is usually called by IMEs to add or remove or change
416      * characters in the composing span. Calling this method will
417      * cause the editor to call
418      * {@link android.inputmethodservice.InputMethodService#onUpdateSelection(int, int, int, int,
419      * int, int)} on the current IME after the batch input is over.</p>
420      *
421      * <p><strong>Editor authors:</strong> please keep in mind the
422      * text may be very similar or completely different than what was
423      * in the composing span at call time, or there may not be a
424      * composing span at all. Please note that although it's not
425      * typical use, the string may be empty. Treat this normally,
426      * replacing the currently composing text with an empty string.
427      * Also, be careful with the cursor position. IMEs rely on this
428      * working exactly as described above. Since this changes the
429      * contents of the editor, you need to make the changes known to
430      * the input method by calling
431      * {@link InputMethodManager#updateSelection(View, int, int, int, int)},
432      * but be careful to wait until the batch edit is over if one is
433      * in progress. Note that this method can set the cursor position
434      * on either edge of the composing text or entirely outside it,
435      * but the IME may also go on to move the cursor position to
436      * within the composing text in a subsequent call so you should
437      * make no assumption at all: the composing text and the selection
438      * are entirely independent.</p>
439      *
440      * @param text The composing text with styles if necessary. If no style
441      *        object attached to the text, the default style for composing text
442      *        is used. See {@link android.text.Spanned} for how to attach style
443      *        object to the text. {@link android.text.SpannableString} and
444      *        {@link android.text.SpannableStringBuilder} are two
445      *        implementations of the interface {@link android.text.Spanned}.
446      * @param newCursorPosition The new cursor position around the text. If
447      *        > 0, this is relative to the end of the text - 1; if <= 0, this
448      *        is relative to the start of the text. So a value of 1 will
449      *        always advance you to the position after the full text being
450      *        inserted. Note that this means you can't position the cursor
451      *        within the text, because the editor can make modifications to
452      *        the text you are providing so it is not possible to correctly
453      *        specify locations there.
454      * @return true on success, false if the input connection is no longer
455      * valid.
456      */
setComposingText(CharSequence text, int newCursorPosition)457     boolean setComposingText(CharSequence text, int newCursorPosition);
458 
459     /**
460      * Mark a certain region of text as composing text. If there was a
461      * composing region, the characters are left as they were and the
462      * composing span removed, as if {@link #finishComposingText()}
463      * has been called. The default style for composing text is used.
464      *
465      * <p>The passed indices are clipped to the contents bounds. If
466      * the resulting region is zero-sized, no region is marked and the
467      * effect is the same as that of calling {@link #finishComposingText()}.
468      * The order of start and end is not important. In effect, the
469      * region from start to end and the region from end to start is
470      * the same. Editor authors, be ready to accept a start that is
471      * greater than end.</p>
472      *
473      * <p>Since this does not change the contents of the text, editors should not call
474      * {@link InputMethodManager#updateSelection(View, int, int, int, int)} and
475      * IMEs should not receive
476      * {@link android.inputmethodservice.InputMethodService#onUpdateSelection(int, int, int, int,
477      * int, int)}.</p>
478      *
479      * <p>This has no impact on the cursor/selection position. It may
480      * result in the cursor being anywhere inside or outside the
481      * composing region, including cases where the selection and the
482      * composing region overlap partially or entirely.</p>
483      *
484      * @param start the position in the text at which the composing region begins
485      * @param end the position in the text at which the composing region ends
486      * @return true on success, false if the input connection is no longer
487      * valid. In {@link android.os.Build.VERSION_CODES#N} and later, false is returned when the
488      * target application does not implement this method.
489      */
setComposingRegion(int start, int end)490     boolean setComposingRegion(int start, int end);
491 
492     /**
493      * Have the text editor finish whatever composing text is
494      * currently active. This simply leaves the text as-is, removing
495      * any special composing styling or other state that was around
496      * it. The cursor position remains unchanged.
497      *
498      * <p><strong>IME authors:</strong> be aware that this call may be
499      * expensive with some editors.</p>
500      *
501      * <p><strong>Editor authors:</strong> please note that the cursor
502      * may be anywhere in the contents when this is called, including
503      * in the middle of the composing span or in a completely
504      * unrelated place. It must not move.</p>
505      *
506      * @return true on success, false if the input connection
507      * is no longer valid.
508      */
finishComposingText()509     boolean finishComposingText();
510 
511     /**
512      * Commit text to the text box and set the new cursor position.
513      *
514      * <p>This method removes the contents of the currently composing
515      * text and replaces it with the passed CharSequence, and then
516      * moves the cursor according to {@code newCursorPosition}. If there
517      * is no composing text when this method is called, the new text is
518      * inserted at the cursor position, removing text inside the selection
519      * if any. This behaves like calling
520      * {@link #setComposingText(CharSequence, int) setComposingText(text, newCursorPosition)}
521      * then {@link #finishComposingText()}.</p>
522      *
523      * <p>Calling this method will cause the editor to call
524      * {@link android.inputmethodservice.InputMethodService#onUpdateSelection(int, int, int, int,
525      * int, int)} on the current IME after the batch input is over.
526      * <strong>Editor authors</strong>, for this to happen you need to
527      * make the changes known to the input method by calling
528      * {@link InputMethodManager#updateSelection(View, int, int, int, int)},
529      * but be careful to wait until the batch edit is over if one is
530      * in progress.</p>
531      *
532      * @param text The text to commit. This may include styles.
533      * @param newCursorPosition The new cursor position around the text,
534      *        in Java characters. If > 0, this is relative to the end
535      *        of the text - 1; if <= 0, this is relative to the start
536      *        of the text. So a value of 1 will always advance the cursor
537      *        to the position after the full text being inserted. Note that
538      *        this means you can't position the cursor within the text,
539      *        because the editor can make modifications to the text
540      *        you are providing so it is not possible to correctly specify
541      *        locations there.
542      * @return true on success, false if the input connection is no longer
543      * valid.
544      */
commitText(CharSequence text, int newCursorPosition)545     boolean commitText(CharSequence text, int newCursorPosition);
546 
547     /**
548      * Commit a completion the user has selected from the possible ones
549      * previously reported to {@link InputMethodSession#displayCompletions
550      * InputMethodSession#displayCompletions(CompletionInfo[])} or
551      * {@link InputMethodManager#displayCompletions
552      * InputMethodManager#displayCompletions(View, CompletionInfo[])}.
553      * This will result in the same behavior as if the user had
554      * selected the completion from the actual UI. In all other
555      * respects, this behaves like {@link #commitText(CharSequence, int)}.
556      *
557      * <p><strong>IME authors:</strong> please take care to send the
558      * same object that you received through
559      * {@link android.inputmethodservice.InputMethodService#onDisplayCompletions(CompletionInfo[])}.
560      * </p>
561      *
562      * <p><strong>Editor authors:</strong> if you never call
563      * {@link InputMethodSession#displayCompletions(CompletionInfo[])} or
564      * {@link InputMethodManager#displayCompletions(View, CompletionInfo[])} then
565      * a well-behaved IME should never call this on your input
566      * connection, but be ready to deal with misbehaving IMEs without
567      * crashing.</p>
568      *
569      * <p>Calling this method (with a valid {@link CompletionInfo} object)
570      * will cause the editor to call
571      * {@link android.inputmethodservice.InputMethodService#onUpdateSelection(int, int, int, int,
572      * int, int)} on the current IME after the batch input is over.
573      * <strong>Editor authors</strong>, for this to happen you need to
574      * make the changes known to the input method by calling
575      * {@link InputMethodManager#updateSelection(View, int, int, int, int)},
576      * but be careful to wait until the batch edit is over if one is
577      * in progress.</p>
578      *
579      * @param text The committed completion.
580      * @return true on success, false if the input connection is no longer
581      * valid.
582      */
commitCompletion(CompletionInfo text)583     boolean commitCompletion(CompletionInfo text);
584 
585     /**
586      * Commit a correction automatically performed on the raw user's input. A
587      * typical example would be to correct typos using a dictionary.
588      *
589      * <p>Calling this method will cause the editor to call
590      * {@link android.inputmethodservice.InputMethodService#onUpdateSelection(int, int, int, int,
591      * int, int)} on the current IME after the batch input is over.
592      * <strong>Editor authors</strong>, for this to happen you need to
593      * make the changes known to the input method by calling
594      * {@link InputMethodManager#updateSelection(View, int, int, int, int)},
595      * but be careful to wait until the batch edit is over if one is
596      * in progress.</p>
597      *
598      * @param correctionInfo Detailed information about the correction.
599      * @return true on success, false if the input connection is no longer valid.
600      * In {@link android.os.Build.VERSION_CODES#N} and later, returns false
601      * when the target application does not implement this method.
602      */
commitCorrection(CorrectionInfo correctionInfo)603     boolean commitCorrection(CorrectionInfo correctionInfo);
604 
605     /**
606      * Set the selection of the text editor. To set the cursor
607      * position, start and end should have the same value.
608      *
609      * <p>Since this moves the cursor, calling this method will cause
610      * the editor to call
611      * {@link android.inputmethodservice.InputMethodService#onUpdateSelection(int, int, int, int,
612      * int, int)} on the current IME after the batch input is over.
613      * <strong>Editor authors</strong>, for this to happen you need to
614      * make the changes known to the input method by calling
615      * {@link InputMethodManager#updateSelection(View, int, int, int, int)},
616      * but be careful to wait until the batch edit is over if one is
617      * in progress.</p>
618      *
619      * <p>This has no effect on the composing region which must stay
620      * unchanged. The order of start and end is not important. In
621      * effect, the region from start to end and the region from end to
622      * start is the same. Editor authors, be ready to accept a start
623      * that is greater than end.</p>
624      *
625      * @param start the character index where the selection should start.
626      * @param end the character index where the selection should end.
627      * @return true on success, false if the input connection is no longer
628      * valid.
629      */
setSelection(int start, int end)630     boolean setSelection(int start, int end);
631 
632     /**
633      * Have the editor perform an action it has said it can do.
634      *
635      * <p>This is typically used by IMEs when the user presses the key
636      * associated with the action.</p>
637      *
638      * @param editorAction This must be one of the action constants for
639      * {@link EditorInfo#imeOptions EditorInfo.editorType}, such as
640      * {@link EditorInfo#IME_ACTION_GO EditorInfo.EDITOR_ACTION_GO}.
641      * @return true on success, false if the input connection is no longer
642      * valid.
643      */
performEditorAction(int editorAction)644     boolean performEditorAction(int editorAction);
645 
646     /**
647      * Perform a context menu action on the field. The given id may be one of:
648      * {@link android.R.id#selectAll},
649      * {@link android.R.id#startSelectingText}, {@link android.R.id#stopSelectingText},
650      * {@link android.R.id#cut}, {@link android.R.id#copy},
651      * {@link android.R.id#paste}, {@link android.R.id#copyUrl},
652      * or {@link android.R.id#switchInputMethod}
653      */
performContextMenuAction(int id)654     boolean performContextMenuAction(int id);
655 
656     /**
657      * Tell the editor that you are starting a batch of editor
658      * operations. The editor will try to avoid sending you updates
659      * about its state until {@link #endBatchEdit} is called. Batch
660      * edits nest.
661      *
662      * <p><strong>IME authors:</strong> use this to avoid getting
663      * calls to
664      * {@link android.inputmethodservice.InputMethodService#onUpdateSelection(int, int, int, int,
665      * int, int)} corresponding to intermediate state. Also, use this to avoid
666      * flickers that may arise from displaying intermediate state. Be
667      * sure to call {@link #endBatchEdit} for each call to this, or
668      * you may block updates in the editor.</p>
669      *
670      * <p><strong>Editor authors:</strong> while a batch edit is in
671      * progress, take care not to send updates to the input method and
672      * not to update the display. IMEs use this intensively to this
673      * effect. Also please note that batch edits need to nest
674      * correctly.</p>
675      *
676      * @return true if a batch edit is now in progress, false otherwise. Since
677      * this method starts a batch edit, that means it will always return true
678      * unless the input connection is no longer valid.
679      */
beginBatchEdit()680     boolean beginBatchEdit();
681 
682     /**
683      * Tell the editor that you are done with a batch edit previously
684      * initiated with {@link #beginBatchEdit}. This ends the latest
685      * batch only.
686      *
687      * <p><strong>IME authors:</strong> make sure you call this
688      * exactly once for each call to {@link #beginBatchEdit}.</p>
689      *
690      * <p><strong>Editor authors:</strong> please be careful about
691      * batch edit nesting. Updates still to be held back until the end
692      * of the last batch edit.</p>
693      *
694      * @return true if there is still a batch edit in progress after closing
695      * the latest one (in other words, if the nesting count is > 0), false
696      * otherwise or if the input connection is no longer valid.
697      */
endBatchEdit()698     boolean endBatchEdit();
699 
700     /**
701      * Send a key event to the process that is currently attached
702      * through this input connection. The event will be dispatched
703      * like a normal key event, to the currently focused view; this
704      * generally is the view that is providing this InputConnection,
705      * but due to the asynchronous nature of this protocol that can
706      * not be guaranteed and the focus may have changed by the time
707      * the event is received.
708      *
709      * <p>This method can be used to send key events to the
710      * application. For example, an on-screen keyboard may use this
711      * method to simulate a hardware keyboard. There are three types
712      * of standard keyboards, numeric (12-key), predictive (20-key)
713      * and ALPHA (QWERTY). You can specify the keyboard type by
714      * specify the device id of the key event.</p>
715      *
716      * <p>You will usually want to set the flag
717      * {@link KeyEvent#FLAG_SOFT_KEYBOARD KeyEvent.FLAG_SOFT_KEYBOARD}
718      * on all key event objects you give to this API; the flag will
719      * not be set for you.</p>
720      *
721      * <p>Note that it's discouraged to send such key events in normal
722      * operation; this is mainly for use with
723      * {@link android.text.InputType#TYPE_NULL} type text fields. Use
724      * the {@link #commitText} family of methods to send text to the
725      * application instead.</p>
726      *
727      * @param event The key event.
728      * @return true on success, false if the input connection is no longer
729      * valid.
730      *
731      * @see KeyEvent
732      * @see KeyCharacterMap#NUMERIC
733      * @see KeyCharacterMap#PREDICTIVE
734      * @see KeyCharacterMap#ALPHA
735      */
sendKeyEvent(KeyEvent event)736     boolean sendKeyEvent(KeyEvent event);
737 
738     /**
739      * Clear the given meta key pressed states in the given input
740      * connection.
741      *
742      * <p>This can be used by the IME to clear the meta key states set
743      * by a hardware keyboard with latched meta keys, if the editor
744      * keeps track of these.</p>
745      *
746      * @param states The states to be cleared, may be one or more bits as
747      * per {@link KeyEvent#getMetaState() KeyEvent.getMetaState()}.
748      * @return true on success, false if the input connection is no longer
749      * valid.
750      */
clearMetaKeyStates(int states)751     boolean clearMetaKeyStates(int states);
752 
753     /**
754      * Called back when the connected IME switches between fullscreen and normal modes.
755      *
756      * <p>Note: On {@link android.os.Build.VERSION_CODES#O} and later devices, input methods are no
757      * longer allowed to directly call this method at any time. To signal this event in the target
758      * application, input methods should always call
759      * {@link InputMethodService#updateFullscreenMode()} instead. This approach should work on API
760      * {@link android.os.Build.VERSION_CODES#N_MR1} and prior devices.</p>
761      *
762      * @return For editor authors, the return value will always be ignored. For IME authors, this
763      *         always returns {@code true} on {@link android.os.Build.VERSION_CODES#N_MR1} and prior
764      *         devices and {@code false} on {@link android.os.Build.VERSION_CODES#O} and later
765      *         devices.
766      * @see InputMethodManager#isFullscreenMode()
767      */
reportFullscreenMode(boolean enabled)768     boolean reportFullscreenMode(boolean enabled);
769 
770     /**
771      * API to send private commands from an input method to its
772      * connected editor. This can be used to provide domain-specific
773      * features that are only known between certain input methods and
774      * their clients. Note that because the InputConnection protocol
775      * is asynchronous, you have no way to get a result back or know
776      * if the client understood the command; you can use the
777      * information in {@link EditorInfo} to determine if a client
778      * supports a particular command.
779      *
780      * @param action Name of the command to be performed. This <em>must</em>
781      * be a scoped name, i.e. prefixed with a package name you own, so that
782      * different developers will not create conflicting commands.
783      * @param data Any data to include with the command.
784      * @return true if the command was sent (whether or not the
785      * associated editor understood it), false if the input connection is no longer
786      * valid.
787      */
performPrivateCommand(String action, Bundle data)788     boolean performPrivateCommand(String action, Bundle data);
789 
790     /**
791      * The editor is requested to call
792      * {@link InputMethodManager#updateCursorAnchorInfo(android.view.View, CursorAnchorInfo)} at
793      * once, as soon as possible, regardless of cursor/anchor position changes. This flag can be
794      * used together with {@link #CURSOR_UPDATE_MONITOR}.
795      */
796     int CURSOR_UPDATE_IMMEDIATE = 1 << 0;
797 
798     /**
799      * The editor is requested to call
800      * {@link InputMethodManager#updateCursorAnchorInfo(android.view.View, CursorAnchorInfo)}
801      * whenever cursor/anchor position is changed. To disable monitoring, call
802      * {@link InputConnection#requestCursorUpdates(int)} again with this flag off.
803      * <p>
804      * This flag can be used together with {@link #CURSOR_UPDATE_IMMEDIATE}.
805      * </p>
806      */
807     int CURSOR_UPDATE_MONITOR = 1 << 1;
808 
809     /**
810      * Called by the input method to ask the editor for calling back
811      * {@link InputMethodManager#updateCursorAnchorInfo(android.view.View, CursorAnchorInfo)} to
812      * notify cursor/anchor locations.
813      *
814      * @param cursorUpdateMode {@link #CURSOR_UPDATE_IMMEDIATE} and/or
815      * {@link #CURSOR_UPDATE_MONITOR}. Pass {@code 0} to disable the effect of
816      * {@link #CURSOR_UPDATE_MONITOR}.
817      * @return {@code true} if the request is scheduled. {@code false} to indicate that when the
818      * application will not call
819      * {@link InputMethodManager#updateCursorAnchorInfo(android.view.View, CursorAnchorInfo)}.
820      * In {@link android.os.Build.VERSION_CODES#N} and later, returns {@code false} also when the
821      * target application does not implement this method.
822      */
requestCursorUpdates(int cursorUpdateMode)823     boolean requestCursorUpdates(int cursorUpdateMode);
824 
825     /**
826      * Called by the {@link InputMethodManager} to enable application developers to specify a
827      * dedicated {@link Handler} on which incoming IPC method calls from input methods will be
828      * dispatched.
829      *
830      * <p>Note: This does nothing when called from input methods.</p>
831      *
832      * @return {@code null} to use the default {@link Handler}.
833      */
getHandler()834     Handler getHandler();
835 
836     /**
837      * Called by the system up to only once to notify that the system is about to invalidate
838      * connection between the input method and the application.
839      *
840      * <p><strong>Editor authors</strong>: You can clear all the nested batch edit right now and
841      * you no longer need to handle subsequent callbacks on this connection, including
842      * {@link #beginBatchEdit()}}.  Note that although the system tries to call this method whenever
843      * possible, there may be a chance that this method is not called in some exceptional
844      * situations.</p>
845      *
846      * <p>Note: This does nothing when called from input methods.</p>
847      */
closeConnection()848     void closeConnection();
849 
850     /**
851      * When this flag is used, the editor will be able to request read access to the content URI
852      * contained in the {@link InputContentInfo} object.
853      *
854      * <p>Make sure that the content provider owning the Uri sets the
855      * {@link android.R.styleable#AndroidManifestProvider_grantUriPermissions
856      * grantUriPermissions} attribute in its manifest or included the
857      * {@link android.R.styleable#AndroidManifestGrantUriPermission
858      * &lt;grant-uri-permissions&gt;} tag. Otherwise {@link InputContentInfo#requestPermission()}
859      * can fail.</p>
860      *
861      * <p>Although calling this API is allowed only for the IME that is currently selected, the
862      * client is able to request a temporary read-only access even after the current IME is switched
863      * to any other IME as long as the client keeps {@link InputContentInfo} object.</p>
864      **/
865     int INPUT_CONTENT_GRANT_READ_URI_PERMISSION =
866             android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION;  // 0x00000001
867 
868     /**
869      * Called by the input method to commit content such as a PNG image to the editor.
870      *
871      * <p>In order to avoid a variety of compatibility issues, this focuses on a simple use case,
872      * where editors and IMEs are expected to work cooperatively as follows:</p>
873      * <ul>
874      *     <li>Editor must keep {@link EditorInfo#contentMimeTypes} equal to {@code null} if it does
875      *     not support this method at all.</li>
876      *     <li>Editor can ignore this request when the MIME type specified in
877      *     {@code inputContentInfo} does not match any of {@link EditorInfo#contentMimeTypes}.
878      *     </li>
879      *     <li>Editor can ignore the cursor position when inserting the provided content.</li>
880      *     <li>Editor can return {@code true} asynchronously, even before it starts loading the
881      *     content.</li>
882      *     <li>Editor should provide a way to delete the content inserted by this method or to
883      *     revert the effect caused by this method.</li>
884      *     <li>IME should not call this method when there is any composing text, in case calling
885      *     this method causes a focus change.</li>
886      *     <li>IME should grant a permission for the editor to read the content. See
887      *     {@link EditorInfo#packageName} about how to obtain the package name of the editor.</li>
888      * </ul>
889      *
890      * @param inputContentInfo Content to be inserted.
891      * @param flags {@link #INPUT_CONTENT_GRANT_READ_URI_PERMISSION} if the content provider
892      * allows {@link android.R.styleable#AndroidManifestProvider_grantUriPermissions
893      * grantUriPermissions} or {@code 0} if the application does not need to call
894      * {@link InputContentInfo#requestPermission()}.
895      * @param opts optional bundle data. This can be {@code null}.
896      * @return {@code true} if this request is accepted by the application, whether the request
897      * is already handled or still being handled in background, {@code false} otherwise.
898      */
commitContent(@onNull InputContentInfo inputContentInfo, int flags, @Nullable Bundle opts)899     boolean commitContent(@NonNull InputContentInfo inputContentInfo, int flags,
900             @Nullable Bundle opts);
901 }
902