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