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 17 package com.android.calculator2; 18 19 import android.content.Context; 20 21 import java.text.DecimalFormat; 22 import java.text.DecimalFormatSymbols; 23 import java.text.NumberFormat; 24 import java.util.HashMap; 25 import java.util.Locale; 26 import java.util.Map; 27 import java.util.Map.Entry; 28 29 public class CalculatorExpressionTokenizer { 30 31 private final Map<String, String> mReplacementMap; 32 33 public CalculatorExpressionTokenizer(Context context) { 34 mReplacementMap = new HashMap<>(); 35 36 Locale locale = context.getResources().getConfiguration().locale; 37 if (!context.getResources().getBoolean(R.bool.use_localized_digits)) { 38 locale = new Locale.Builder() 39 .setLocale(locale) 40 .setUnicodeLocaleKeyword("nu", "latn") 41 .build(); 42 } 43 44 final DecimalFormatSymbols symbols = new DecimalFormatSymbols(locale); 45 final char zeroDigit = symbols.getZeroDigit(); 46 47 mReplacementMap.put(".", String.valueOf(symbols.getDecimalSeparator())); 48 49 for (int i = 0; i <= 9; ++i) { 50 mReplacementMap.put(Integer.toString(i), String.valueOf((char) (i + zeroDigit))); 51 } 52 53 mReplacementMap.put("/", context.getString(R.string.op_div)); 54 mReplacementMap.put("*", context.getString(R.string.op_mul)); 55 mReplacementMap.put("-", context.getString(R.string.op_sub)); 56 57 mReplacementMap.put("cos", context.getString(R.string.fun_cos)); 58 mReplacementMap.put("ln", context.getString(R.string.fun_ln)); 59 mReplacementMap.put("log", context.getString(R.string.fun_log)); 60 mReplacementMap.put("sin", context.getString(R.string.fun_sin)); 61 mReplacementMap.put("tan", context.getString(R.string.fun_tan)); 62 63 mReplacementMap.put("Infinity", context.getString(R.string.inf)); 64 } 65 66 public String getNormalizedExpression(String expr) { 67 for (Entry<String, String> replacementEntry : mReplacementMap.entrySet()) { 68 expr = expr.replace(replacementEntry.getValue(), replacementEntry.getKey()); 69 } 70 return expr; 71 } 72 73 public String getLocalizedExpression(String expr) { 74 for (Entry<String, String> replacementEntry : mReplacementMap.entrySet()) { 75 expr = expr.replace(replacementEntry.getKey(), replacementEntry.getValue()); 76 } 77 return expr; 78 } 79 } 80