CombinerChain.java revision 99aff0af98e66b1d8515225a103f5beb84d098b9
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.event;
18
19import android.text.SpannableStringBuilder;
20import android.text.TextUtils;
21
22import com.android.inputmethod.latin.Constants;
23
24import java.util.ArrayList;
25import java.util.HashMap;
26
27/**
28 * This class implements the logic chain between receiving events and generating code points.
29 *
30 * Event sources are multiple. It may be a hardware keyboard, a D-PAD, a software keyboard,
31 * or any exotic input source.
32 * This class will orchestrate the composing chain that starts with an event as its input. Each
33 * composer will be given turns one after the other.
34 * The output is composed of two sequences of code points: the first, representing the already
35 * finished combining part, will be shown normally as the composing string, while the second is
36 * feedback on the composing state and will typically be shown with different styling such as
37 * a colored background.
38 */
39public class CombinerChain {
40    // The already combined text, as described above
41    private StringBuilder mCombinedText;
42    // The feedback on the composing state, as described above
43    private SpannableStringBuilder mStateFeedback;
44    private final ArrayList<Combiner> mCombiners;
45
46    private static final HashMap<String, Class<? extends Combiner>> IMPLEMENTED_COMBINERS =
47            new HashMap<>();
48    static {
49        IMPLEMENTED_COMBINERS.put("MyanmarReordering", MyanmarReordering.class);
50    }
51    private static final String COMBINER_SPEC_SEPARATOR = ";";
52
53    /**
54     * Create an combiner chain.
55     *
56     * The combiner chain takes events as inputs and outputs code points and combining state.
57     * For example, if the input language is Japanese, the combining chain will typically perform
58     * kana conversion. This takes a string for initial text, taken to be present before the
59     * cursor: we'll start after this.
60     *
61     * @param initialText The text that has already been combined so far.
62     * @param combinerList A list of combiners to be applied in order.
63     */
64    public CombinerChain(final String initialText, final Combiner... combinerList) {
65        mCombiners = new ArrayList<>();
66        // The dead key combiner is always active, and always first
67        mCombiners.add(new DeadKeyCombiner());
68        for (final Combiner combiner : combinerList) {
69            mCombiners.add(combiner);
70        }
71        mCombinedText = new StringBuilder(initialText);
72        mStateFeedback = new SpannableStringBuilder();
73    }
74
75    public void reset() {
76        mCombinedText.setLength(0);
77        mStateFeedback.clear();
78        for (final Combiner c : mCombiners) {
79            c.reset();
80        }
81    }
82
83    /**
84     * Process an event through the combining chain, and return a processed event to apply.
85     * @param previousEvents the list of previous events in this composition
86     * @param newEvent the new event to process
87     * @return the processed event. It may be the same event, or a consumed event, or a completely
88     *   new event. However it may never be null.
89     */
90    public Event processEvent(final ArrayList<Event> previousEvents, final Event newEvent) {
91        final ArrayList<Event> modifiablePreviousEvents = new ArrayList<>(previousEvents);
92        Event event = newEvent;
93        for (final Combiner combiner : mCombiners) {
94            // A combiner can never return more than one event; it can return several
95            // code points, but they should be encapsulated within one event.
96            event = combiner.processEvent(modifiablePreviousEvents, event);
97            if (null == event) {
98                // Combiners return null if they eat the event.
99                break;
100            }
101        }
102        return event;
103    }
104
105    /**
106     * Apply a processed event.
107     * @param event the event to be applied
108     */
109    public void applyProcessedEvent(final Event event) {
110        if (null != event) {
111            // TODO: figure out the generic way of doing this
112            if (Constants.CODE_DELETE == event.mKeyCode) {
113                final int length = mCombinedText.length();
114                if (length > 0) {
115                    final int lastCodePoint = mCombinedText.codePointBefore(length);
116                    mCombinedText.delete(length - Character.charCount(lastCodePoint), length);
117                }
118            } else {
119                final CharSequence textToCommit = event.getTextToCommit();
120                if (!TextUtils.isEmpty(textToCommit)) {
121                    mCombinedText.append(textToCommit);
122                }
123            }
124        }
125        mStateFeedback.clear();
126        for (int i = mCombiners.size() - 1; i >= 0; --i) {
127            mStateFeedback.append(mCombiners.get(i).getCombiningStateFeedback());
128        }
129    }
130
131    /**
132     * Get the char sequence that should be displayed as the composing word. It may include
133     * styling spans.
134     */
135    public CharSequence getComposingWordWithCombiningFeedback() {
136        final SpannableStringBuilder s = new SpannableStringBuilder(mCombinedText);
137        return s.append(mStateFeedback);
138    }
139
140    public static Combiner[] createCombiners(final String spec) {
141        if (TextUtils.isEmpty(spec)) {
142            return new Combiner[0];
143        }
144        final String[] combinerDescriptors = spec.split(COMBINER_SPEC_SEPARATOR);
145        final Combiner[] combiners = new Combiner[combinerDescriptors.length];
146        int i = 0;
147        for (final String combinerDescriptor : combinerDescriptors) {
148            final Class<? extends Combiner> combinerClass =
149                    IMPLEMENTED_COMBINERS.get(combinerDescriptor);
150            if (null == combinerClass) {
151                throw new RuntimeException("Unknown combiner descriptor: " + combinerDescriptor);
152            }
153            try {
154                combiners[i++] = combinerClass.newInstance();
155            } catch (InstantiationException e) {
156                throw new RuntimeException("Unable to instantiate combiner: " + combinerDescriptor,
157                        e);
158            } catch (IllegalAccessException e) {
159                throw new RuntimeException("Unable to instantiate combiner: " + combinerDescriptor,
160                        e);
161            }
162        }
163        return combiners;
164    }
165}
166