1/*
2 * Copyright (C) 2017 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 */
16package android.support.text.emoji.widget;
17
18import static android.support.annotation.RestrictTo.Scope.LIBRARY_GROUP;
19
20import android.support.annotation.NonNull;
21import android.support.annotation.RequiresApi;
22import android.support.annotation.RestrictTo;
23import android.support.text.emoji.EmojiCompat;
24import android.text.Editable;
25import android.view.inputmethod.EditorInfo;
26import android.view.inputmethod.InputConnection;
27import android.view.inputmethod.InputConnectionWrapper;
28import android.widget.TextView;
29
30/**
31 * InputConnectionWrapper for EditText delete operations. Keyboard does not have knowledge about
32 * emojis and therefore might send commands to delete a part of the emoji sequence which creates
33 * invalid codeunits/getCodepointAt in the text.
34 * <p/>
35 * This class tries to correctly delete an emoji checking if there is an emoji span.
36 *
37 * @hide
38 */
39@RestrictTo(LIBRARY_GROUP)
40@RequiresApi(19)
41final class EmojiInputConnection extends InputConnectionWrapper {
42    private final TextView mTextView;
43
44    EmojiInputConnection(
45            @NonNull final TextView textView,
46            @NonNull final InputConnection inputConnection,
47            @NonNull final EditorInfo outAttrs) {
48        super(inputConnection, false);
49        mTextView = textView;
50        EmojiCompat.get().updateEditorInfoAttrs(outAttrs);
51    }
52
53    @Override
54    public boolean deleteSurroundingText(final int beforeLength, final int afterLength) {
55        final boolean result = EmojiCompat.handleDeleteSurroundingText(this, getEditable(),
56                beforeLength, afterLength, false /* in code ponints */);
57        return result || super.deleteSurroundingText(beforeLength, afterLength);
58    }
59
60    @Override
61    public boolean deleteSurroundingTextInCodePoints(final int beforeLength,
62            final int afterLength) {
63        final boolean result = EmojiCompat.handleDeleteSurroundingText(this, getEditable(),
64                beforeLength, afterLength, true  /* in code ponints */);
65        return result || super.deleteSurroundingTextInCodePoints(beforeLength, afterLength);
66    }
67
68    private Editable getEditable() {
69        return mTextView.getEditableText();
70    }
71}
72