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