KeySpecParser.java revision c217dc9237e5d1e1e721b9007139d771dcb41145
1/*
2 * Copyright (C) 2010 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 com.android.inputmethod.keyboard.internal;
18
19import android.content.res.Resources;
20import android.text.TextUtils;
21
22import com.android.inputmethod.keyboard.Keyboard;
23import com.android.inputmethod.latin.LatinImeLogger;
24import com.android.inputmethod.latin.R;
25import com.android.inputmethod.latin.Utils;
26
27import java.util.ArrayList;
28import java.util.Arrays;
29
30/**
31 * String parser of moreKeys attribute of Key.
32 * The string is comma separated texts each of which represents one "more key".
33 * - String resource can be embedded into specification @string/name. This is done before parsing
34 *   comma.
35 * Each "more key" specification is one of the following:
36 * - A single letter (Letter)
37 * - Label optionally followed by keyOutputText or code (keyLabel|keyOutputText).
38 * - Icon followed by keyOutputText or code (@icon/icon_name|@integer/key_code)
39 * Special character, comma ',' backslash '\', and bar '|' can be escaped by '\' character.
40 * Note that the character '@' and '\' are also parsed by XML parser and CSV parser as well.
41 * See {@link KeyboardIconsSet} about icon_name.
42 */
43public class KeySpecParser {
44    private static final boolean DEBUG = LatinImeLogger.sDBG;
45
46    private static final int MAX_STRING_REFERENCE_INDIRECTION = 10;
47
48    // Constants for parsing.
49    private static int COMMA = ',';
50    private static final char ESCAPE_CHAR = '\\';
51    private static final char PREFIX_AT = '@';
52    private static final char SUFFIX_SLASH = '/';
53    private static final String PREFIX_STRING = PREFIX_AT + "string" + SUFFIX_SLASH;
54    private static final char LABEL_END = '|';
55    private static final String PREFIX_ICON = PREFIX_AT + "icon" + SUFFIX_SLASH;
56    private static final String PREFIX_CODE = PREFIX_AT + "integer" + SUFFIX_SLASH;
57    private static final String ADDITIONAL_MORE_KEY_MARKER = "%";
58
59    private KeySpecParser() {
60        // Intentional empty constructor for utility class.
61    }
62
63    private static boolean hasIcon(String moreKeySpec) {
64        if (moreKeySpec.startsWith(PREFIX_ICON)) {
65            final int end = indexOfLabelEnd(moreKeySpec, 0);
66            if (end > 0) {
67                return true;
68            }
69            throw new KeySpecParserError("outputText or code not specified: " + moreKeySpec);
70        }
71        return false;
72    }
73
74    private static boolean hasCode(String moreKeySpec) {
75        final int end = indexOfLabelEnd(moreKeySpec, 0);
76        if (end > 0 && end + 1 < moreKeySpec.length()
77                && moreKeySpec.substring(end + 1).startsWith(PREFIX_CODE)) {
78            return true;
79        }
80        return false;
81    }
82
83    private static String parseEscape(String text) {
84        if (text.indexOf(ESCAPE_CHAR) < 0) {
85            return text;
86        }
87        final int length = text.length();
88        final StringBuilder sb = new StringBuilder();
89        for (int pos = 0; pos < length; pos++) {
90            final char c = text.charAt(pos);
91            if (c == ESCAPE_CHAR && pos + 1 < length) {
92                // Skip escape char
93                pos++;
94                sb.append(text.charAt(pos));
95            } else {
96                sb.append(c);
97            }
98        }
99        return sb.toString();
100    }
101
102    private static int indexOfLabelEnd(String moreKeySpec, int start) {
103        if (moreKeySpec.indexOf(ESCAPE_CHAR, start) < 0) {
104            final int end = moreKeySpec.indexOf(LABEL_END, start);
105            if (end == 0) {
106                throw new KeySpecParserError(LABEL_END + " at " + start + ": " + moreKeySpec);
107            }
108            return end;
109        }
110        final int length = moreKeySpec.length();
111        for (int pos = start; pos < length; pos++) {
112            final char c = moreKeySpec.charAt(pos);
113            if (c == ESCAPE_CHAR && pos + 1 < length) {
114                // Skip escape char
115                pos++;
116            } else if (c == LABEL_END) {
117                return pos;
118            }
119        }
120        return -1;
121    }
122
123    public static String getLabel(String moreKeySpec) {
124        if (hasIcon(moreKeySpec)) {
125            return null;
126        }
127        final int end = indexOfLabelEnd(moreKeySpec, 0);
128        final String label = (end > 0) ? parseEscape(moreKeySpec.substring(0, end))
129                : parseEscape(moreKeySpec);
130        if (TextUtils.isEmpty(label)) {
131            throw new KeySpecParserError("Empty label: " + moreKeySpec);
132        }
133        return label;
134    }
135
136    private static String getOutputTextInternal(String moreKeySpec) {
137        final int end = indexOfLabelEnd(moreKeySpec, 0);
138        if (end <= 0) {
139            return null;
140        }
141        if (indexOfLabelEnd(moreKeySpec, end + 1) >= 0) {
142            throw new KeySpecParserError("Multiple " + LABEL_END + ": " + moreKeySpec);
143        }
144        return parseEscape(moreKeySpec.substring(end + /* LABEL_END */1));
145    }
146
147    public static String getOutputText(String moreKeySpec) {
148        if (hasCode(moreKeySpec)) {
149            return null;
150        }
151        final String outputText = getOutputTextInternal(moreKeySpec);
152        if (outputText != null) {
153            if (Utils.codePointCount(outputText) == 1) {
154                // If output text is one code point, it should be treated as a code.
155                // See {@link #getCode(Resources, String)}.
156                return null;
157            }
158            if (!TextUtils.isEmpty(outputText)) {
159                return outputText;
160            }
161            throw new KeySpecParserError("Empty outputText: " + moreKeySpec);
162        }
163        final String label = getLabel(moreKeySpec);
164        if (label == null) {
165            throw new KeySpecParserError("Empty label: " + moreKeySpec);
166        }
167        // Code is automatically generated for one letter label. See {@link getCode()}.
168        return (Utils.codePointCount(label) == 1) ? null : label;
169    }
170
171    public static int getCode(Resources res, String moreKeySpec) {
172        if (hasCode(moreKeySpec)) {
173            final int end = indexOfLabelEnd(moreKeySpec, 0);
174            if (indexOfLabelEnd(moreKeySpec, end + 1) >= 0) {
175                throw new KeySpecParserError("Multiple " + LABEL_END + ": " + moreKeySpec);
176            }
177            final int resId = getResourceId(res,
178                    moreKeySpec.substring(end + /* LABEL_END */1 + /* PREFIX_AT */1),
179                    R.string.english_ime_name);
180            final int code = res.getInteger(resId);
181            return code;
182        }
183        final String outputText = getOutputTextInternal(moreKeySpec);
184        if (outputText != null) {
185            // If output text is one code point, it should be treated as a code.
186            // See {@link #getOutputText(String)}.
187            if (Utils.codePointCount(outputText) == 1) {
188                return outputText.codePointAt(0);
189            }
190            return Keyboard.CODE_OUTPUT_TEXT;
191        }
192        final String label = getLabel(moreKeySpec);
193        // Code is automatically generated for one letter label.
194        if (Utils.codePointCount(label) == 1) {
195            return label.codePointAt(0);
196        }
197        return Keyboard.CODE_OUTPUT_TEXT;
198    }
199
200    public static int getIconId(String moreKeySpec) {
201        if (hasIcon(moreKeySpec)) {
202            final int end = moreKeySpec.indexOf(LABEL_END, PREFIX_ICON.length());
203            final String name = moreKeySpec.substring(PREFIX_ICON.length(), end);
204            return KeyboardIconsSet.getIconId(name);
205        }
206        return KeyboardIconsSet.ICON_UNDEFINED;
207    }
208
209    public static String[] insertAddtionalMoreKeys(String[] moreKeys, String[] additionalMoreKeys) {
210        final int moreKeysCount = (moreKeys != null) ? moreKeys.length : 0;
211        final int additionalCount = (additionalMoreKeys != null) ? additionalMoreKeys.length : 0;
212        ArrayList<String> out = null;
213        int additionalIndex = 0;
214        for (int moreKeyIndex = 0; moreKeyIndex < moreKeysCount; moreKeyIndex++) {
215            final String moreKeySpec = moreKeys[moreKeyIndex];
216            if (moreKeySpec.equals(ADDITIONAL_MORE_KEY_MARKER)) {
217                if (additionalIndex < additionalCount) {
218                    // Replace '%' marker with additional more key specification.
219                    final String additionalMoreKey = additionalMoreKeys[additionalIndex];
220                    if (out != null) {
221                        out.add(additionalMoreKey);
222                    } else {
223                        moreKeys[moreKeyIndex] = additionalMoreKey;
224                    }
225                    additionalIndex++;
226                } else {
227                    // Filter out excessive '%' marker.
228                    if (out == null) {
229                        out = new ArrayList<String>(moreKeyIndex);
230                        for (int i = 0; i < moreKeyIndex; i++) {
231                            out.add(moreKeys[i]);
232                        }
233                    }
234                }
235            } else {
236                if (out != null) {
237                    out.add(moreKeySpec);
238                }
239            }
240        }
241        if (additionalCount > 0 && additionalIndex == 0) {
242            // No '%' marker is found in more keys.
243            // Insert all additional more keys to the head of more keys.
244            if (DEBUG && out != null) {
245                throw new RuntimeException("Internal logic error:"
246                        + " moreKeys=" + Arrays.toString(moreKeys)
247                        + " additionalMoreKeys=" + Arrays.toString(additionalMoreKeys));
248            }
249            out = new ArrayList<String>(additionalCount + moreKeysCount);
250            for (int i = additionalIndex; i < additionalCount; i++) {
251                out.add(additionalMoreKeys[i]);
252            }
253            for (int i = 0; i < moreKeysCount; i++) {
254                out.add(moreKeys[i]);
255            }
256        } else if (additionalIndex < additionalCount) {
257            // The number of '%' markers are less than additional more keys.
258            // Append remained additional more keys to the tail of more keys.
259            if (DEBUG && out != null) {
260                throw new RuntimeException("Internal logic error:"
261                        + " moreKeys=" + Arrays.toString(moreKeys)
262                        + " additionalMoreKeys=" + Arrays.toString(additionalMoreKeys));
263            }
264            out = new ArrayList<String>(moreKeysCount);
265            for (int i = 0; i < moreKeysCount; i++) {
266                out.add(moreKeys[i]);
267            }
268            for (int i = additionalIndex; i < additionalCount; i++) {
269                out.add(additionalMoreKeys[additionalIndex]);
270            }
271        }
272        if (out != null) {
273            return out.size() > 0 ? out.toArray(new String[out.size()]) : null;
274        } else {
275            return moreKeys;
276        }
277    }
278
279    @SuppressWarnings("serial")
280    public static class KeySpecParserError extends RuntimeException {
281        public KeySpecParserError(String message) {
282            super(message);
283        }
284    }
285
286    private static int getResourceId(Resources res, String name, int packageNameResId) {
287        String packageName = res.getResourcePackageName(packageNameResId);
288        int resId = res.getIdentifier(name, null, packageName);
289        if (resId == 0) {
290            throw new RuntimeException("Unknown resource: " + name);
291        }
292        return resId;
293    }
294
295    private static String resolveStringResource(String rawText, Resources res,
296            int packageNameResId) {
297        int level = 0;
298        String text = rawText;
299        StringBuilder sb;
300        do {
301            level++;
302            if (level >= MAX_STRING_REFERENCE_INDIRECTION) {
303                throw new RuntimeException("too many @string/resource indirection: " + text);
304            }
305
306            final int size = text.length();
307            if (size < PREFIX_STRING.length()) {
308                return text;
309            }
310
311            sb = null;
312            for (int pos = 0; pos < size; pos++) {
313                final char c = text.charAt(pos);
314                if (c == PREFIX_AT && text.startsWith(PREFIX_STRING, pos)) {
315                    if (sb == null) {
316                        sb = new StringBuilder(text.substring(0, pos));
317                    }
318                    final int end = searchResourceNameEnd(text, pos + PREFIX_STRING.length());
319                    final String resName = text.substring(pos + 1, end);
320                    final int resId = getResourceId(res, resName, packageNameResId);
321                    sb.append(res.getString(resId));
322                    pos = end - 1;
323                } else if (c == ESCAPE_CHAR) {
324                    if (sb != null) {
325                        // Append both escape character and escaped character.
326                        sb.append(text.substring(pos, Math.min(pos + 2, size)));
327                    }
328                    pos++;
329                } else if (sb != null) {
330                    sb.append(c);
331                }
332            }
333
334            if (sb != null) {
335                text = sb.toString();
336            }
337        } while (sb != null);
338
339        return text;
340    }
341
342    private static int searchResourceNameEnd(String text, int start) {
343        final int size = text.length();
344        for (int pos = start; pos < size; pos++) {
345            final char c = text.charAt(pos);
346            // String resource name should be consisted of [a-z_0-9].
347            if ((c >= 'a' && c <= 'z') || c == '_' || (c >= '0' && c <= '9')) {
348                continue;
349            }
350            return pos;
351        }
352        return size;
353    }
354
355    public static String[] parseCsvString(String rawText, Resources res, int packageNameResId) {
356        final String text = resolveStringResource(rawText, res, packageNameResId);
357        final int size = text.length();
358        if (size == 0) {
359            return null;
360        }
361        if (Utils.codePointCount(text) == 1) {
362            return text.codePointAt(0) == COMMA ? null : new String[] { text };
363        }
364
365        ArrayList<String> list = null;
366        int start = 0;
367        for (int pos = 0; pos < size; pos++) {
368            final char c = text.charAt(pos);
369            if (c == COMMA) {
370                // Skip empty entry.
371                if (pos - start > 0) {
372                    if (list == null) {
373                        list = new ArrayList<String>();
374                    }
375                    list.add(text.substring(start, pos));
376                }
377                // Skip comma
378                start = pos + 1;
379            } else if (c == ESCAPE_CHAR) {
380                // Skip escape character and escaped character.
381                pos++;
382            }
383        }
384        final String remain = (size - start > 0) ? text.substring(start) : null;
385        if (list == null) {
386            return remain != null ? new String[] { remain } : null;
387        } else {
388            if (remain != null) {
389                list.add(remain);
390            }
391            return list.toArray(new String[list.size()]);
392        }
393    }
394}
395