BaseInputConnection.java revision 39dd1510ea2bfb79709075f352384730862fd4c4
1/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 * use this file except in compliance with the License. You may obtain a copy of
6 * 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, WITHOUT
12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 * License for the specific language governing permissions and limitations under
14 * the License.
15 */
16
17package android.view.inputmethod;
18
19import android.content.Context;
20import android.content.res.TypedArray;
21import android.os.Bundle;
22import android.os.SystemClock;
23import android.text.Editable;
24import android.text.NoCopySpan;
25import android.text.Selection;
26import android.text.Spannable;
27import android.text.SpannableStringBuilder;
28import android.text.Spanned;
29import android.text.TextUtils;
30import android.text.method.MetaKeyKeyListener;
31import android.util.Log;
32import android.util.LogPrinter;
33import android.view.KeyCharacterMap;
34import android.view.KeyEvent;
35import android.view.View;
36import android.view.ViewRootImpl;
37
38class ComposingText implements NoCopySpan {
39}
40
41/**
42 * Base class for implementors of the InputConnection interface, taking care
43 * of most of the common behavior for providing a connection to an Editable.
44 * Implementors of this class will want to be sure to implement
45 * {@link #getEditable} to provide access to their own editable object, and
46 * to refer to the documentation in {@link InputConnection}.
47 */
48public class BaseInputConnection implements InputConnection {
49    private static final boolean DEBUG = false;
50    private static final String TAG = "BaseInputConnection";
51    static final Object COMPOSING = new ComposingText();
52
53    /** @hide */
54    protected final InputMethodManager mIMM;
55    final View mTargetView;
56    final boolean mDummyMode;
57
58    private Object[] mDefaultComposingSpans;
59
60    Editable mEditable;
61    KeyCharacterMap mKeyCharacterMap;
62
63    BaseInputConnection(InputMethodManager mgr, boolean fullEditor) {
64        mIMM = mgr;
65        mTargetView = null;
66        mDummyMode = !fullEditor;
67    }
68
69    public BaseInputConnection(View targetView, boolean fullEditor) {
70        mIMM = (InputMethodManager)targetView.getContext().getSystemService(
71                Context.INPUT_METHOD_SERVICE);
72        mTargetView = targetView;
73        mDummyMode = !fullEditor;
74    }
75
76    public static final void removeComposingSpans(Spannable text) {
77        text.removeSpan(COMPOSING);
78        Object[] sps = text.getSpans(0, text.length(), Object.class);
79        if (sps != null) {
80            for (int i=sps.length-1; i>=0; i--) {
81                Object o = sps[i];
82                if ((text.getSpanFlags(o)&Spanned.SPAN_COMPOSING) != 0) {
83                    text.removeSpan(o);
84                }
85            }
86        }
87    }
88
89    public static void setComposingSpans(Spannable text) {
90        setComposingSpans(text, 0, text.length());
91    }
92
93    /** @hide */
94    public static void setComposingSpans(Spannable text, int start, int end) {
95        final Object[] sps = text.getSpans(start, end, Object.class);
96        if (sps != null) {
97            for (int i=sps.length-1; i>=0; i--) {
98                final Object o = sps[i];
99                if (o == COMPOSING) {
100                    text.removeSpan(o);
101                    continue;
102                }
103
104                final int fl = text.getSpanFlags(o);
105                if ((fl&(Spanned.SPAN_COMPOSING|Spanned.SPAN_POINT_MARK_MASK))
106                        != (Spanned.SPAN_COMPOSING|Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)) {
107                    text.setSpan(o, text.getSpanStart(o), text.getSpanEnd(o),
108                            (fl & ~Spanned.SPAN_POINT_MARK_MASK)
109                                    | Spanned.SPAN_COMPOSING
110                                    | Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
111                }
112            }
113        }
114
115        text.setSpan(COMPOSING, start, end,
116                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE | Spanned.SPAN_COMPOSING);
117    }
118
119    public static int getComposingSpanStart(Spannable text) {
120        return text.getSpanStart(COMPOSING);
121    }
122
123    public static int getComposingSpanEnd(Spannable text) {
124        return text.getSpanEnd(COMPOSING);
125    }
126
127    /**
128     * Return the target of edit operations.  The default implementation
129     * returns its own fake editable that is just used for composing text;
130     * subclasses that are real text editors should override this and
131     * supply their own.
132     */
133    public Editable getEditable() {
134        if (mEditable == null) {
135            mEditable = Editable.Factory.getInstance().newEditable("");
136            Selection.setSelection(mEditable, 0);
137        }
138        return mEditable;
139    }
140
141    /**
142     * Default implementation does nothing.
143     */
144    public boolean beginBatchEdit() {
145        return false;
146    }
147
148    /**
149     * Default implementation does nothing.
150     */
151    public boolean endBatchEdit() {
152        return false;
153    }
154
155    /**
156     * Called when this InputConnection is no longer used by the InputMethodManager.
157     *
158     * @hide
159     */
160    protected void reportFinish() {
161        // Intentionaly empty
162    }
163
164    /**
165     * Default implementation uses
166     * {@link MetaKeyKeyListener#clearMetaKeyState(long, int)
167     * MetaKeyKeyListener.clearMetaKeyState(long, int)} to clear the state.
168     */
169    public boolean clearMetaKeyStates(int states) {
170        final Editable content = getEditable();
171        if (content == null) return false;
172        MetaKeyKeyListener.clearMetaKeyState(content, states);
173        return true;
174    }
175
176    /**
177     * Default implementation does nothing and returns false.
178     */
179    public boolean commitCompletion(CompletionInfo text) {
180        return false;
181    }
182
183    /**
184     * Default implementation does nothing and returns false.
185     */
186    public boolean commitCorrection(CorrectionInfo correctionInfo) {
187        return false;
188    }
189
190    /**
191     * Default implementation replaces any existing composing text with
192     * the given text.  In addition, only if dummy mode, a key event is
193     * sent for the new text and the current editable buffer cleared.
194     */
195    public boolean commitText(CharSequence text, int newCursorPosition) {
196        if (DEBUG) Log.v(TAG, "commitText " + text);
197        replaceText(text, newCursorPosition, false);
198        mIMM.notifyUserAction();
199        sendCurrentText();
200        return true;
201    }
202
203    /**
204     * The default implementation performs the deletion around the current
205     * selection position of the editable text.
206     * @param beforeLength
207     * @param afterLength
208     */
209    public boolean deleteSurroundingText(int beforeLength, int afterLength) {
210        if (DEBUG) Log.v(TAG, "deleteSurroundingText " + beforeLength
211                + " / " + afterLength);
212        final Editable content = getEditable();
213        if (content == null) return false;
214
215        beginBatchEdit();
216
217        int a = Selection.getSelectionStart(content);
218        int b = Selection.getSelectionEnd(content);
219
220        if (a > b) {
221            int tmp = a;
222            a = b;
223            b = tmp;
224        }
225
226        // ignore the composing text.
227        int ca = getComposingSpanStart(content);
228        int cb = getComposingSpanEnd(content);
229        if (cb < ca) {
230            int tmp = ca;
231            ca = cb;
232            cb = tmp;
233        }
234        if (ca != -1 && cb != -1) {
235            if (ca < a) a = ca;
236            if (cb > b) b = cb;
237        }
238
239        int deleted = 0;
240
241        if (beforeLength > 0) {
242            int start = a - beforeLength;
243            if (start < 0) start = 0;
244            content.delete(start, a);
245            deleted = a - start;
246        }
247
248        if (afterLength > 0) {
249            b = b - deleted;
250
251            int end = b + afterLength;
252            if (end > content.length()) end = content.length();
253
254            content.delete(b, end);
255        }
256
257        endBatchEdit();
258
259        return true;
260    }
261
262    /**
263     * The default implementation removes the composing state from the
264     * current editable text.  In addition, only if dummy mode, a key event is
265     * sent for the new text and the current editable buffer cleared.
266     */
267    public boolean finishComposingText() {
268        if (DEBUG) Log.v(TAG, "finishComposingText");
269        final Editable content = getEditable();
270        if (content != null) {
271            beginBatchEdit();
272            removeComposingSpans(content);
273            // Note: sendCurrentText does nothing unless mDummyMode is set
274            sendCurrentText();
275            endBatchEdit();
276        }
277        return true;
278    }
279
280    /**
281     * The default implementation uses TextUtils.getCapsMode to get the
282     * cursor caps mode for the current selection position in the editable
283     * text, unless in dummy mode in which case 0 is always returned.
284     */
285    public int getCursorCapsMode(int reqModes) {
286        if (mDummyMode) return 0;
287
288        final Editable content = getEditable();
289        if (content == null) return 0;
290
291        int a = Selection.getSelectionStart(content);
292        int b = Selection.getSelectionEnd(content);
293
294        if (a > b) {
295            int tmp = a;
296            a = b;
297            b = tmp;
298        }
299
300        return TextUtils.getCapsMode(content, a, reqModes);
301    }
302
303    /**
304     * The default implementation always returns null.
305     */
306    public ExtractedText getExtractedText(ExtractedTextRequest request, int flags) {
307        return null;
308    }
309
310    /**
311     * The default implementation returns the given amount of text from the
312     * current cursor position in the buffer.
313     */
314    public CharSequence getTextBeforeCursor(int length, int flags) {
315        final Editable content = getEditable();
316        if (content == null) return null;
317
318        int a = Selection.getSelectionStart(content);
319        int b = Selection.getSelectionEnd(content);
320
321        if (a > b) {
322            int tmp = a;
323            a = b;
324            b = tmp;
325        }
326
327        if (a <= 0) {
328            return "";
329        }
330
331        if (length > a) {
332            length = a;
333        }
334
335        if ((flags&GET_TEXT_WITH_STYLES) != 0) {
336            return content.subSequence(a - length, a);
337        }
338        return TextUtils.substring(content, a - length, a);
339    }
340
341    /**
342     * The default implementation returns the text currently selected, or null if none is
343     * selected.
344     */
345    public CharSequence getSelectedText(int flags) {
346        final Editable content = getEditable();
347        if (content == null) return null;
348
349        int a = Selection.getSelectionStart(content);
350        int b = Selection.getSelectionEnd(content);
351
352        if (a > b) {
353            int tmp = a;
354            a = b;
355            b = tmp;
356        }
357
358        if (a == b) return null;
359
360        if ((flags&GET_TEXT_WITH_STYLES) != 0) {
361            return content.subSequence(a, b);
362        }
363        return TextUtils.substring(content, a, b);
364    }
365
366    /**
367     * The default implementation returns the given amount of text from the
368     * current cursor position in the buffer.
369     */
370    public CharSequence getTextAfterCursor(int length, int flags) {
371        final Editable content = getEditable();
372        if (content == null) return null;
373
374        int a = Selection.getSelectionStart(content);
375        int b = Selection.getSelectionEnd(content);
376
377        if (a > b) {
378            int tmp = a;
379            a = b;
380            b = tmp;
381        }
382
383        // Guard against the case where the cursor has not been positioned yet.
384        if (b < 0) {
385            b = 0;
386        }
387
388        if (b + length > content.length()) {
389            length = content.length() - b;
390        }
391
392
393        if ((flags&GET_TEXT_WITH_STYLES) != 0) {
394            return content.subSequence(b, b + length);
395        }
396        return TextUtils.substring(content, b, b + length);
397    }
398
399    /**
400     * The default implementation turns this into the enter key.
401     */
402    public boolean performEditorAction(int actionCode) {
403        long eventTime = SystemClock.uptimeMillis();
404        sendKeyEvent(new KeyEvent(eventTime, eventTime,
405                KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER, 0, 0,
406                KeyCharacterMap.VIRTUAL_KEYBOARD, 0,
407                KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE
408                | KeyEvent.FLAG_EDITOR_ACTION));
409        sendKeyEvent(new KeyEvent(SystemClock.uptimeMillis(), eventTime,
410                KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER, 0, 0,
411                KeyCharacterMap.VIRTUAL_KEYBOARD, 0,
412                KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE
413                | KeyEvent.FLAG_EDITOR_ACTION));
414        return true;
415    }
416
417    /**
418     * The default implementation does nothing.
419     */
420    public boolean performContextMenuAction(int id) {
421        return false;
422    }
423
424    /**
425     * The default implementation does nothing.
426     */
427    public boolean performPrivateCommand(String action, Bundle data) {
428        return false;
429    }
430
431    /**
432     * The default implementation places the given text into the editable,
433     * replacing any existing composing text.  The new text is marked as
434     * in a composing state with the composing style.
435     */
436    public boolean setComposingText(CharSequence text, int newCursorPosition) {
437        if (DEBUG) Log.v(TAG, "setComposingText " + text);
438        replaceText(text, newCursorPosition, true);
439        mIMM.notifyUserAction();
440        return true;
441    }
442
443    public boolean setComposingRegion(int start, int end) {
444        final Editable content = getEditable();
445        if (content != null) {
446            beginBatchEdit();
447            removeComposingSpans(content);
448            int a = start;
449            int b = end;
450            if (a > b) {
451                int tmp = a;
452                a = b;
453                b = tmp;
454            }
455            // Clip the end points to be within the content bounds.
456            final int length = content.length();
457            if (a < 0) a = 0;
458            if (b < 0) b = 0;
459            if (a > length) a = length;
460            if (b > length) b = length;
461
462            ensureDefaultComposingSpans();
463            if (mDefaultComposingSpans != null) {
464                for (int i = 0; i < mDefaultComposingSpans.length; ++i) {
465                    content.setSpan(mDefaultComposingSpans[i], a, b,
466                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE | Spanned.SPAN_COMPOSING);
467                }
468            }
469
470            content.setSpan(COMPOSING, a, b,
471                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE | Spanned.SPAN_COMPOSING);
472
473            // Note: sendCurrentText does nothing unless mDummyMode is set
474            sendCurrentText();
475            endBatchEdit();
476        }
477        return true;
478    }
479
480    /**
481     * The default implementation changes the selection position in the
482     * current editable text.
483     */
484    public boolean setSelection(int start, int end) {
485        if (DEBUG) Log.v(TAG, "setSelection " + start + ", " + end);
486        final Editable content = getEditable();
487        if (content == null) return false;
488        int len = content.length();
489        if (start > len || end > len || start < 0 || end < 0) {
490            // If the given selection is out of bounds, just ignore it.
491            // Most likely the text was changed out from under the IME,
492            // and the IME is going to have to update all of its state
493            // anyway.
494            return true;
495        }
496        if (start == end && MetaKeyKeyListener.getMetaState(content,
497                MetaKeyKeyListener.META_SELECTING) != 0) {
498            // If we are in selection mode, then we want to extend the
499            // selection instead of replacing it.
500            Selection.extendSelection(content, start);
501        } else {
502            Selection.setSelection(content, start, end);
503        }
504        return true;
505    }
506
507    /**
508     * Provides standard implementation for sending a key event to the window
509     * attached to the input connection's view.
510     */
511    public boolean sendKeyEvent(KeyEvent event) {
512        synchronized (mIMM.mH) {
513            ViewRootImpl viewRootImpl = mTargetView != null ? mTargetView.getViewRootImpl() : null;
514            if (viewRootImpl == null) {
515                if (mIMM.mServedView != null) {
516                    viewRootImpl = mIMM.mServedView.getViewRootImpl();
517                }
518            }
519            if (viewRootImpl != null) {
520                viewRootImpl.dispatchKeyFromIme(event);
521            }
522        }
523        mIMM.notifyUserAction();
524        return false;
525    }
526
527    /**
528     * Updates InputMethodManager with the current fullscreen mode.
529     */
530    public boolean reportFullscreenMode(boolean enabled) {
531        mIMM.setFullscreenMode(enabled);
532        return true;
533    }
534
535    private void sendCurrentText() {
536        if (!mDummyMode) {
537            return;
538        }
539
540        Editable content = getEditable();
541        if (content != null) {
542            final int N = content.length();
543            if (N == 0) {
544                return;
545            }
546            if (N == 1) {
547                // If it's 1 character, we have a chance of being
548                // able to generate normal key events...
549                if (mKeyCharacterMap == null) {
550                    mKeyCharacterMap = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD);
551                }
552                char[] chars = new char[1];
553                content.getChars(0, 1, chars, 0);
554                KeyEvent[] events = mKeyCharacterMap.getEvents(chars);
555                if (events != null) {
556                    for (int i=0; i<events.length; i++) {
557                        if (DEBUG) Log.v(TAG, "Sending: " + events[i]);
558                        sendKeyEvent(events[i]);
559                    }
560                    content.clear();
561                    return;
562                }
563            }
564
565            // Otherwise, revert to the special key event containing
566            // the actual characters.
567            KeyEvent event = new KeyEvent(SystemClock.uptimeMillis(),
568                    content.toString(), KeyCharacterMap.VIRTUAL_KEYBOARD, 0);
569            sendKeyEvent(event);
570            content.clear();
571        }
572    }
573
574    private void ensureDefaultComposingSpans() {
575        if (mDefaultComposingSpans == null) {
576            Context context;
577            if (mTargetView != null) {
578                context = mTargetView.getContext();
579            } else if (mIMM.mServedView != null) {
580                context = mIMM.mServedView.getContext();
581            } else {
582                context = null;
583            }
584            if (context != null) {
585                TypedArray ta = context.getTheme()
586                        .obtainStyledAttributes(new int[] {
587                                com.android.internal.R.attr.candidatesTextStyleSpans
588                        });
589                CharSequence style = ta.getText(0);
590                ta.recycle();
591                if (style != null && style instanceof Spanned) {
592                    mDefaultComposingSpans = ((Spanned)style).getSpans(
593                            0, style.length(), Object.class);
594                }
595            }
596        }
597    }
598
599    private void replaceText(CharSequence text, int newCursorPosition,
600            boolean composing) {
601        final Editable content = getEditable();
602        if (content == null) {
603            return;
604        }
605
606        beginBatchEdit();
607
608        // delete composing text set previously.
609        int a = getComposingSpanStart(content);
610        int b = getComposingSpanEnd(content);
611
612        if (DEBUG) Log.v(TAG, "Composing span: " + a + " to " + b);
613
614        if (b < a) {
615            int tmp = a;
616            a = b;
617            b = tmp;
618        }
619
620        if (a != -1 && b != -1) {
621            removeComposingSpans(content);
622        } else {
623            a = Selection.getSelectionStart(content);
624            b = Selection.getSelectionEnd(content);
625            if (a < 0) a = 0;
626            if (b < 0) b = 0;
627            if (b < a) {
628                int tmp = a;
629                a = b;
630                b = tmp;
631            }
632        }
633
634        if (composing) {
635            Spannable sp = null;
636            if (!(text instanceof Spannable)) {
637                sp = new SpannableStringBuilder(text);
638                text = sp;
639                ensureDefaultComposingSpans();
640                if (mDefaultComposingSpans != null) {
641                    for (int i = 0; i < mDefaultComposingSpans.length; ++i) {
642                        sp.setSpan(mDefaultComposingSpans[i], 0, sp.length(),
643                                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE | Spanned.SPAN_COMPOSING);
644                    }
645                }
646            } else {
647                sp = (Spannable)text;
648            }
649            setComposingSpans(sp);
650        }
651
652        if (DEBUG) Log.v(TAG, "Replacing from " + a + " to " + b + " with \""
653                + text + "\", composing=" + composing
654                + ", type=" + text.getClass().getCanonicalName());
655
656        if (DEBUG) {
657            LogPrinter lp = new LogPrinter(Log.VERBOSE, TAG);
658            lp.println("Current text:");
659            TextUtils.dumpSpans(content, lp, "  ");
660            lp.println("Composing text:");
661            TextUtils.dumpSpans(text, lp, "  ");
662        }
663
664        // Position the cursor appropriately, so that after replacing the
665        // desired range of text it will be located in the correct spot.
666        // This allows us to deal with filters performing edits on the text
667        // we are providing here.
668        if (newCursorPosition > 0) {
669            newCursorPosition += b - 1;
670        } else {
671            newCursorPosition += a;
672        }
673        if (newCursorPosition < 0) newCursorPosition = 0;
674        if (newCursorPosition > content.length())
675            newCursorPosition = content.length();
676        Selection.setSelection(content, newCursorPosition);
677
678        content.replace(a, b, text);
679
680        if (DEBUG) {
681            LogPrinter lp = new LogPrinter(Log.VERBOSE, TAG);
682            lp.println("Final text:");
683            TextUtils.dumpSpans(content, lp, "  ");
684        }
685
686        endBatchEdit();
687    }
688}
689