TextInfoCompatUtils.java revision 733ec699cdc4ace128c664ea4fe7eae46c15d0f0
1/*
2 * Copyright (C) 2014 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
17package com.android.inputmethod.compat;
18
19import android.view.textservice.TextInfo;
20
21import com.android.inputmethod.annotations.UsedForTesting;
22
23import java.lang.reflect.Constructor;
24import java.lang.reflect.Method;
25import java.util.Locale;
26
27@UsedForTesting
28public final class TextInfoCompatUtils {
29    // Note that TextInfo.getCharSequence() is supposed to be available in API level 21 and later.
30    private static final Method TEXT_INFO_GET_CHAR_SEQUENCE =
31            CompatUtils.getMethod(TextInfo.class, "getCharSequence");
32    private static final Constructor<?> TEXT_INFO_CONSTRUCTOR_FOR_CHAR_SEQUENCE =
33            CompatUtils.getConstructor(TextInfo.class, CharSequence.class, int.class, int.class,
34                    int.class, int.class);
35
36    @UsedForTesting
37    public static boolean isCharSequenceSupported() {
38        return TEXT_INFO_GET_CHAR_SEQUENCE != null &&
39                TEXT_INFO_CONSTRUCTOR_FOR_CHAR_SEQUENCE != null;
40    }
41
42    @UsedForTesting
43    public static TextInfo newInstance(CharSequence charSequence, int start, int end, int cookie,
44            int sequenceNumber) {
45        if (TEXT_INFO_CONSTRUCTOR_FOR_CHAR_SEQUENCE != null) {
46            return (TextInfo) CompatUtils.newInstance(TEXT_INFO_CONSTRUCTOR_FOR_CHAR_SEQUENCE,
47                    charSequence, start, end, cookie, sequenceNumber);
48        }
49        return new TextInfo(charSequence.subSequence(start, end).toString(), cookie,
50                sequenceNumber);
51    }
52
53    @UsedForTesting
54    public static CharSequence getCharSequence(final TextInfo textInfo,
55            final CharSequence defaultValue) {
56        return (CharSequence) CompatUtils.invoke(textInfo, defaultValue,
57                TEXT_INFO_GET_CHAR_SEQUENCE);
58    }
59}
60