summaryrefslogtreecommitdiffstats
path: root/src/com/android/launcher3/compat/AlphabeticIndexCompat.java
blob: 46c9006ddff5039449a6c3755c91f173a6f7d154 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package com.android.launcher3.compat;

import android.content.Context;
import android.icu.text.AlphabeticIndex;
import android.os.LocaleList;

import com.android.launcher3.Utilities;

import java.util.Locale;

import androidx.annotation.NonNull;

public class AlphabeticIndexCompat {

    private static final String MID_DOT = "\u2219";
    private final String mDefaultMiscLabel;

    private final AlphabeticIndex.ImmutableIndex mBaseIndex;

    public AlphabeticIndexCompat(Context context) {
        this(context.getResources().getConfiguration().getLocales());
    }

    public AlphabeticIndexCompat(LocaleList locales) {
        int localeCount = locales.size();

        Locale primaryLocale = localeCount == 0 ? Locale.ENGLISH : locales.get(0);
        AlphabeticIndex indexBuilder = new AlphabeticIndex(primaryLocale);
        for (int i = 1; i < localeCount; i++) {
            indexBuilder.addLabels(locales.get(i));
        }
        indexBuilder.addLabels(Locale.ENGLISH);
        mBaseIndex = indexBuilder.buildImmutableIndex();

        if (primaryLocale.getLanguage().equals(Locale.JAPANESE.getLanguage())) {
            // Japanese character 他 ("misc")
            mDefaultMiscLabel = "\u4ed6";
            // TODO(winsonc, omakoto): We need to handle Japanese sections better,
            // especially the kanji
        } else {
            // Dot
            mDefaultMiscLabel = MID_DOT;
        }
    }

    /**
     * Computes the section name for an given string {@param s}.
     */
    public String computeSectionName(@NonNull CharSequence cs) {
        String s = Utilities.trim(cs);
        String sectionName = mBaseIndex.getBucket(mBaseIndex.getBucketIndex(s)).getLabel();
        if (Utilities.trim(sectionName).isEmpty() && s.length() > 0) {
            int c = s.codePointAt(0);
            boolean startsWithDigit = Character.isDigit(c);
            if (startsWithDigit) {
                // Digit section
                return "#";
            } else {
                boolean startsWithLetter = Character.isLetter(c);
                if (startsWithLetter) {
                    return mDefaultMiscLabel;
                } else {
                    // In languages where these differ, this ensures that we differentiate
                    // between the misc section in the native language and a misc section
                    // for everything else.
                    return MID_DOT;
                }
            }
        }
        return sectionName;
    }
}