From 08e3f7cef153d55bf04353a553f14c7cce877c57 Mon Sep 17 00:00:00 2001 From: Sergey Solovyev Date: Thu, 22 Dec 2011 18:54:16 +0400 Subject: [PATCH] Custom function support + refactor of vars registry --- res/values-es/strings.xml | 18 +- res/values-it/strings.xml | 18 +- res/values-ru/strings.xml | 19 +- res/values/default_values.xml | 1 + res/values/strings.xml | 19 +- .../android/calculator/CalculatorModel.java | 7 +- .../calculator/CalculatorVarsActivity.java | 6 +- .../calculator/CalculatorVarsTabActivity.java | 23 +- .../android/calculator/math/MathType.java | 1 - .../android/calculator/model/AFunction.java | 71 ++++++ .../model/AbstractAndroidMathRegistry.java | 180 ++++++++++++++ .../model/AndroidFunctionsMathRegistry.java | 47 +++- .../calculator/model/AndroidMathRegistry.java | 5 + .../model/AndroidMathRegistryImpl.java | 99 -------- .../model/AndroidOperatorsMathRegistry.java | 44 +++- .../AndroidPostfixFunctionsRegistry.java | 44 +++- .../calculator/model/AndroidVarsRegistry.java | 76 ------ .../model/AndroidVarsRegistryImpl.java | 234 ++++-------------- .../calculator/model/CalculatorEngine.java | 5 +- .../android/calculator/model/Functions.java | 29 +++ .../model/MathEntityPersistenceContainer.java | 12 + .../model/MathPersistenceEntity.java | 14 ++ .../calculator/model/PreparedExpression.java | 7 +- .../calculator/model/ToJsclTextProcessor.java | 9 +- .../android/calculator/model/Var.java | 14 +- .../android/calculator/model/VarCategory.java | 61 +++++ .../android/calculator/model/Vars.java | 7 +- .../android/calculator/model/VarTest.java | 12 +- 28 files changed, 634 insertions(+), 448 deletions(-) create mode 100644 src/main/java/org/solovyev/android/calculator/model/AFunction.java create mode 100644 src/main/java/org/solovyev/android/calculator/model/AbstractAndroidMathRegistry.java delete mode 100644 src/main/java/org/solovyev/android/calculator/model/AndroidMathRegistryImpl.java delete mode 100644 src/main/java/org/solovyev/android/calculator/model/AndroidVarsRegistry.java create mode 100644 src/main/java/org/solovyev/android/calculator/model/Functions.java create mode 100644 src/main/java/org/solovyev/android/calculator/model/MathEntityPersistenceContainer.java create mode 100644 src/main/java/org/solovyev/android/calculator/model/MathPersistenceEntity.java create mode 100644 src/main/java/org/solovyev/android/calculator/model/VarCategory.java diff --git a/res/values-es/strings.xml b/res/values-es/strings.xml index 927a76b7..3cad0073 100644 --- a/res/values-es/strings.xml +++ b/res/values-es/strings.xml @@ -78,15 +78,15 @@ ¡Ya existe una variable con el mismo nombre! El nombre de la Constante no es válido: el nombre debe comenzar con una letra,puede contener letras, dígitos y líneas. ¡Una Variable de Sistema no puede ser cambiada! - Ratio de la circunferencia del círculo a su diámetro - Número real único como el valor de la derivada (pendiente de la línea tangente) de la función f(x) = e^x en el punto x = 0 es igual a 1 - Unidad imaginaria, definida como i^2 = −1 - Velocidad de la luz en vacío, m·s^-1 - La constante gravitatoria es una constante física empírica consistente en el cálculo de la atracción gravitatoria entre objetos con masa, m^3·kg^−1·s^−2 - Constante física que refleja los tamaños de energía cuántica en mecánica cuántica, J·s - Constante Planck reducida, J·s - No es un número - Infinito + Ratio de la circunferencia del círculo a su diámetro + Número real único como el valor de la derivada (pendiente de la línea tangente) de la función f(x) = e^x en el punto x = 0 es igual a 1 + Unidad imaginaria, definida como i^2 = −1 + Velocidad de la luz en vacío, m·s^-1 + La constante gravitatoria es una constante física empírica consistente en el cálculo de la atracción gravitatoria entre objetos con masa, m^3·kg^−1·s^−2 + Constante física que refleja los tamaños de energía cuántica en mecánica cuántica, J·s + Constante Planck reducida, J·s + No es un número + Infinito Introducir nuevo cálculo Pulsar para copiar Continuar diff --git a/res/values-it/strings.xml b/res/values-it/strings.xml index 89da8588..aa74a1a9 100644 --- a/res/values-it/strings.xml +++ b/res/values-it/strings.xml @@ -72,15 +72,15 @@ Il nome della costante non è valido: il nome deve iniziare con una lettera, può contenere lettere, cifre e underscore. La variabile di sistema non può essere cambiata! - Rapporto tra la circonferenza di qualsiasi cerchio col suo diametro - Unico numero reale tale che il valore della derivata (pendenza della retta tangente) della funzione f(x) = e^x nel punto x = 0 che è uguale a 1 - Unità immaginaria, definita come i^2 = -1 - Velocità della luce nel vuoto, m·s^-1 - La costante gravitazionale è una costante fisica empirica coinvolta nel calcolo dell\' attrazione gravitazionale tra gli oggetti con massa, m^3·kg^−1·s^−2 - Costante fisica che riflette la dimensione dei quanti di energia in meccanica quantistica, J·s - Costante di riduzione di Planck, J·s - Non è un numero - Infinito + Rapporto tra la circonferenza di qualsiasi cerchio col suo diametro + Unico numero reale tale che il valore della derivata (pendenza della retta tangente) della funzione f(x) = e^x nel punto x = 0 che è uguale a 1 + Unità immaginaria, definita come i^2 = -1 + Velocità della luce nel vuoto, m·s^-1 + La costante gravitazionale è una costante fisica empirica coinvolta nel calcolo dell\' attrazione gravitazionale tra gli oggetti con massa, m^3·kg^−1·s^−2 + Costante fisica che riflette la dimensione dei quanti di energia in meccanica quantistica, J·s + Costante di riduzione di Planck, J·s + Non è un numero + Infinito Inserisci una nuova espressione Premi per copiare diff --git a/res/values-ru/strings.xml b/res/values-ru/strings.xml index 6a09fef4..1804945e 100644 --- a/res/values-ru/strings.xml +++ b/res/values-ru/strings.xml @@ -71,15 +71,16 @@ Имя переменной не валидно: им ядолжно начинаться с буквы, может содержать буквы, цифры и знак подчёркивания. Системная переменная не может быть изменена! - Отношение длины окружности к диаметру - Вещественное число, такое что производная функции f(x) = e^x в точке x = 0 равно 1 - Мнимая единица, определённая как i^2 = −1 - Скорость света в вакууме, м·с^-1 - Гравитационная постоянная, с^3·кг^−1·с^−2 - Постоянная Планка - коэффициент, связывающий величину энергии электромагнитного излучения с его частотой, Дж·с - Приведённая постоянная Планка, Дж·с - Не число - Бесконечность + Отношение длины окружности к диаметру. Внимание: эта постоянная зависит от единиц измерения углов => rad: 3.14, deg: 180.0 + Отношение длины окружности к диаметру. Внимание: эта постоянная не зависит от единиц измерения углов => rad: 3.14, rad: 3.14 + Вещественное число, такое что производная функции f(x) = e^x в точке x = 0 равно 1 + Мнимая единица, определённая как i^2 = −1 + Скорость света в вакууме, м·с^-1 + Гравитационная постоянная, с^3·кг^−1·с^−2 + Постоянная Планка - коэффициент, связывающий величину энергии электромагнитного излучения с его частотой, Дж·с + Приведённая постоянная Планка, Дж·с + Не число + Бесконечность Введите новое выражение Продолжить Нажмите для копирования diff --git a/res/values/default_values.xml b/res/values/default_values.xml index ae2146e9..989ad97c 100644 --- a/res/values/default_values.xml +++ b/res/values/default_values.xml @@ -27,6 +27,7 @@ org.solovyev.android.calculator.CalculatorModel_round_result true + org.solovyev.android.calculator.CalculatorModel_functions org.solovyev.android.calculator.CalculatorModel_vars org.solovyev.android.calculator.CalculatorModel_history diff --git a/res/values/strings.xml b/res/values/strings.xml index b4514aba..35293def 100644 --- a/res/values/strings.xml +++ b/res/values/strings.xml @@ -74,15 +74,16 @@ Name of constant is not valid: name must start with letter, can contain letters, digits and underscore. System variable cannot be changed! - Ratio of any circle\'s circumference to its diameter - Unique real number such that the value of the derivative (slope of the tangent line) of the function f(x) = e^x at the point x = 0 is equal to 1 - Imaginary unit, defined such that i^2 = −1 - Speed of light in vacuum, m·s^-1 - The gravitational constant is an empirical physical constant involved in the calculation of the gravitational attraction between objects with mass, m^3·kg^−1·s^−2 - Physical constant reflecting the sizes of energy quanta in quantum mechanics, J·s - Reduced Planck constant, J·s - Not a number - Infinity + Ratio of any circle\'s circumference to its diameter. Note: this constant is degree unit dependent => rad: 3.14, deg: 180.0 + Ratio of any circle\'s circumference to its diameter. Note: this constant is degree unit independent => rad: 3.14, rad: 3.14 + Unique real number such that the value of the derivative (slope of the tangent line) of the function f(x) = e^x at the point x = 0 is equal to 1 + Imaginary unit, defined such that i^2 = −1 + Speed of light in vacuum, m·s^-1 + The gravitational constant is an empirical physical constant involved in the calculation of the gravitational attraction between objects with mass, m^3·kg^−1·s^−2 + Physical constant reflecting the sizes of energy quanta in quantum mechanics, J·s + Reduced Planck constant, J·s + Not a number + Infinity Enter new expression Press to copy diff --git a/src/main/java/org/solovyev/android/calculator/CalculatorModel.java b/src/main/java/org/solovyev/android/calculator/CalculatorModel.java index 69663c3e..76b06d52 100644 --- a/src/main/java/org/solovyev/android/calculator/CalculatorModel.java +++ b/src/main/java/org/solovyev/android/calculator/CalculatorModel.java @@ -20,6 +20,7 @@ import android.widget.TextView; import android.widget.Toast; import jscl.math.Generic; import jscl.math.function.Constant; +import jscl.math.function.IConstant; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.solovyev.android.calculator.history.CalculatorHistory; @@ -389,8 +390,8 @@ public enum CalculatorModel implements CursorControl, HistoryControl notSystemConstants = new HashSet(); for (Constant constant : genericResult.getConstants()) { - Var var = CalculatorEngine.instance.getVarsRegister().get(constant.getName()); - if (var != null && !var.isSystem()) { + IConstant var = CalculatorEngine.instance.getVarsRegister().get(constant.getName()); + if (var != null && !var.isSystem() && !var.isDefined()) { notSystemConstants.add(constant); } } @@ -410,6 +411,8 @@ public enum CalculatorModel implements CursorControl, HistoryControl { +public class CalculatorVarsTabActivity extends AbstractMathEntityListActivity { public static final String CREATE_VAR_EXTRA_STRING = "org.solovyev.android.calculator.CalculatorVarsActivity_create_var"; @@ -89,12 +90,12 @@ public class CalculatorVarsTabActivity extends AbstractMathEntityListActivity getMathEntities() { - final List result = new ArrayList(CalculatorEngine.instance.getVarsRegister().getEntities()); + protected List getMathEntities() { + final List result = new ArrayList(CalculatorEngine.instance.getVarsRegister().getEntities()); - CollectionsUtils.removeAll(result, new Finder() { + CollectionsUtils.removeAll(result, new Finder() { @Override - public boolean isFound(@Nullable Var var) { + public boolean isFound(@Nullable IConstant var) { return var != null && CollectionsUtils.contains(var.getName(), MathType.INFINITY_JSCL, MathType.NAN); } }); @@ -103,7 +104,7 @@ public class CalculatorVarsTabActivity extends AbstractMathEntityListActivity varsRegistry = CalculatorEngine.instance.getVarsRegister(); if (isValidName(name)) { boolean canBeSaved = false; - final Var varFromRegister = varsRegistry.get(name); + final IConstant varFromRegister = varsRegistry.get(name); if ( varFromRegister == null ) { canBeSaved = true; } else if ( editedInstance != null && varFromRegister.getId().equals(editedInstance.getId()) ) { @@ -264,7 +265,7 @@ public class CalculatorVarsTabActivity extends AbstractMathEntityListActivity varsRegistry = CalculatorEngine.instance.getVarsRegister(); varsRegistry.remove(var); varsRegistry.save(CalculatorVarsTabActivity.this); if (isInCategory(var)) { diff --git a/src/main/java/org/solovyev/android/calculator/math/MathType.java b/src/main/java/org/solovyev/android/calculator/math/MathType.java index 124b13bf..c89d4073 100644 --- a/src/main/java/org/solovyev/android/calculator/math/MathType.java +++ b/src/main/java/org/solovyev/android/calculator/math/MathType.java @@ -331,7 +331,6 @@ public enum MathType { public final static String INFINITY = "∞"; public final static String INFINITY_JSCL = "Infinity"; - public static final List constants = Arrays.asList(E, PI, C, G, H_REDUCED, IMAGINARY_NUMBER, NAN, INFINITY); /** * Method determines mathematical entity type for text substring starting from ith index diff --git a/src/main/java/org/solovyev/android/calculator/model/AFunction.java b/src/main/java/org/solovyev/android/calculator/model/AFunction.java new file mode 100644 index 00000000..c672d40e --- /dev/null +++ b/src/main/java/org/solovyev/android/calculator/model/AFunction.java @@ -0,0 +1,71 @@ +package org.solovyev.android.calculator.model; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.simpleframework.xml.Element; +import org.simpleframework.xml.Root; +import org.solovyev.common.utils.CollectionsUtils; +import org.solovyev.common.utils.StringMapper; + +import java.util.List; + +/** + * User: serso + * Date: 12/22/11 + * Time: 5:25 PM + */ + +@Root +public class AFunction implements MathPersistenceEntity { + + @Element + @NotNull + private String name; + + @Element + @NotNull + private String content; + + + @Element(required = false) + @Nullable + private String parameterNames; + + + @NotNull + public String getName() { + return name; + } + + public void setName(@NotNull String name) { + this.name = name; + } + + @NotNull + public String getContent() { + return content; + } + + public void setContent(@NotNull String content) { + this.content = content; + } + + @Nullable + public String getParameterNames() { + return parameterNames; + } + + public void setParameterNames(@Nullable String[] parameterNames) { + this.parameterNames = CollectionsUtils.formatValue(CollectionsUtils.asList(parameterNames), ";", new StringMapper()); + } + + public void setParameterNames(@Nullable String parameterNames) { + this.parameterNames = parameterNames; + } + + @NotNull + public String[] getParameterNamesAsArray() { + final List parameterNamesAsList = CollectionsUtils.split(parameterNames, ";"); + return parameterNamesAsList.toArray(new String[parameterNamesAsList.size()]); + } +} diff --git a/src/main/java/org/solovyev/android/calculator/model/AbstractAndroidMathRegistry.java b/src/main/java/org/solovyev/android/calculator/model/AbstractAndroidMathRegistry.java new file mode 100644 index 00000000..84637142 --- /dev/null +++ b/src/main/java/org/solovyev/android/calculator/model/AbstractAndroidMathRegistry.java @@ -0,0 +1,180 @@ +/* + * Copyright (c) 2009-2011. Created by serso aka se.solovyev. + * For more information, please, contact se.solovyev@gmail.com + * or visit http://se.solovyev.org + */ + +package org.solovyev.android.calculator.model; + +import android.content.Context; +import android.content.SharedPreferences; +import android.preference.PreferenceManager; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.simpleframework.xml.Serializer; +import org.simpleframework.xml.core.Persister; +import org.solovyev.android.view.prefs.ResourceCache; +import org.solovyev.common.definitions.IBuilder; +import org.solovyev.common.math.MathEntity; +import org.solovyev.common.math.MathRegistry; + +import java.io.StringWriter; +import java.util.List; +import java.util.Map; + +/** + * User: serso + * Date: 10/30/11 + * Time: 1:03 AM + */ +public abstract class AbstractAndroidMathRegistry implements AndroidMathRegistry { + + @NotNull + private final MathRegistry mathRegistry; + + @NotNull + private final String prefix; + + protected AbstractAndroidMathRegistry(@NotNull MathRegistry mathRegistry, @NotNull String prefix) { + this.mathRegistry = mathRegistry; + this.prefix = prefix; + } + + @NotNull + protected abstract Map getSubstitutes(); + + @Nullable + @Override + public String getDescription(@NotNull Context context, @NotNull String mathEntityName) { + final String stringName; + + final Map substitutes = getSubstitutes(); + final String substitute = substitutes.get(mathEntityName); + if (substitute == null) { + stringName = prefix + mathEntityName; + } else { + stringName = prefix + substitute; + } + + return ResourceCache.instance.getCaption(stringName); + } + + public synchronized void load(@Nullable Context context, @Nullable SharedPreferences preferences) { + + if (context != null && preferences != null) { + final Integer preferenceStringId = getPreferenceStringId(); + if (preferenceStringId != null) { + final String value = preferences.getString(context.getString(preferenceStringId), null); + if (value != null) { + final Serializer serializer = new Persister(); + try { + final MathEntityPersistenceContainer

persistenceContainer = serializer.read(getPersistenceContainerClass(), value); + for (P entity : persistenceContainer.getEntities()) { + if (!contains(entity.getName())) { + add(createBuilder(entity)); + } + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } + } + } + + /*Log.d(AndroidVarsRegistry.class.getName(), vars.size() + " variables registered!"); + for (Var var : vars) { + Log.d(AndroidVarsRegistry.class.getName(), var.toString()); + }*/ + } + + @NotNull + protected abstract IBuilder createBuilder(@NotNull P entity); + + @NotNull + protected abstract Class> getPersistenceContainerClass(); + + @Nullable + protected abstract Integer getPreferenceStringId(); + + + @Override + public synchronized void save(@NotNull Context context) { + final Integer preferenceStringId = getPreferenceStringId(); + + if (preferenceStringId != null) { + final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context); + final SharedPreferences.Editor editor = settings.edit(); + + final MathEntityPersistenceContainer

container = createPersistenceContainer(); + for (T entity : this.getEntities()) { + if (!entity.isSystem()) { + final P persistenceEntity = transform(entity); + if (persistenceEntity != null) { + container.getEntities().add(persistenceEntity); + } + } + } + + final StringWriter sw = new StringWriter(); + final Serializer serializer = new Persister(); + try { + serializer.write(container, sw); + } catch (Exception e) { + throw new RuntimeException(e); + } + + editor.putString(context.getString(preferenceStringId), sw.toString()); + + editor.commit(); + } + } + + @Nullable + protected abstract P transform(@NotNull T entity); + + @NotNull + protected abstract MathEntityPersistenceContainer

createPersistenceContainer(); + + @NotNull + @Override + public List getEntities() { + return mathRegistry.getEntities(); + } + + @NotNull + @Override + public List getSystemEntities() { + return mathRegistry.getSystemEntities(); + } + + @Override + public T add(@NotNull IBuilder IBuilder) { + return mathRegistry.add(IBuilder); + } + + @Override + public void remove(@NotNull T var) { + mathRegistry.remove(var); + } + + @NotNull + @Override + public List getNames() { + return mathRegistry.getNames(); + } + + @Override + public boolean contains(@NotNull String name) { + return mathRegistry.contains(name); + } + + @Override + public T get(@NotNull String name) { + return mathRegistry.get(name); + } + + @Override + public T getById(@NotNull Integer id) { + return mathRegistry.getById(id); + } +} diff --git a/src/main/java/org/solovyev/android/calculator/model/AndroidFunctionsMathRegistry.java b/src/main/java/org/solovyev/android/calculator/model/AndroidFunctionsMathRegistry.java index c5204baa..c6af473a 100644 --- a/src/main/java/org/solovyev/android/calculator/model/AndroidFunctionsMathRegistry.java +++ b/src/main/java/org/solovyev/android/calculator/model/AndroidFunctionsMathRegistry.java @@ -6,12 +6,13 @@ package org.solovyev.android.calculator.model; -import jscl.math.function.ArcTrigonometric; -import jscl.math.function.Comparison; -import jscl.math.function.Function; -import jscl.math.function.Trigonometric; +import android.content.Context; +import android.content.SharedPreferences; +import jscl.math.function.*; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.solovyev.android.calculator.R; +import org.solovyev.common.definitions.IBuilder; import org.solovyev.common.math.MathRegistry; import org.solovyev.common.utils.CollectionsUtils; @@ -22,7 +23,7 @@ import java.util.*; * Date: 11/17/11 * Time: 11:28 PM */ -public class AndroidFunctionsMathRegistry extends AndroidMathRegistryImpl { +public class AndroidFunctionsMathRegistry extends AbstractAndroidMathRegistry { public static enum Category { @@ -124,4 +125,40 @@ public class AndroidFunctionsMathRegistry extends AndroidMathRegistryImpl createBuilder(@NotNull AFunction entity) { + return new CustomFunction.Builder(entity.getName(), entity.getParameterNamesAsArray(), entity.getContent()); + } + + @NotNull + @Override + protected Class> getPersistenceContainerClass() { + return Functions.class; + } + + @Override + protected Integer getPreferenceStringId() { + return R.string.p_calc_functions; + } + + @Override + protected AFunction transform(@NotNull Function entity) { + if (entity instanceof CustomFunction) { + final AFunction result = new AFunction(); + result.setName(entity.getName()); + result.setContent(((CustomFunction) entity).getContent()); + result.setParameterNames(((CustomFunction) entity).getParameterNames()); + return result; + } else { + return null; + } + } + + @NotNull + @Override + protected MathEntityPersistenceContainer createPersistenceContainer() { + return new Functions(); + } } diff --git a/src/main/java/org/solovyev/android/calculator/model/AndroidMathRegistry.java b/src/main/java/org/solovyev/android/calculator/model/AndroidMathRegistry.java index 8d898582..4f174a7c 100644 --- a/src/main/java/org/solovyev/android/calculator/model/AndroidMathRegistry.java +++ b/src/main/java/org/solovyev/android/calculator/model/AndroidMathRegistry.java @@ -7,6 +7,7 @@ package org.solovyev.android.calculator.model; import android.content.Context; +import android.content.SharedPreferences; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.solovyev.common.math.MathEntity; @@ -24,4 +25,8 @@ public interface AndroidMathRegistry extends MathRegistry< @Nullable String getCategory(@NotNull T mathEntity); + + void load(@Nullable Context context, @Nullable SharedPreferences preferences); + + void save(@NotNull Context context); } diff --git a/src/main/java/org/solovyev/android/calculator/model/AndroidMathRegistryImpl.java b/src/main/java/org/solovyev/android/calculator/model/AndroidMathRegistryImpl.java deleted file mode 100644 index ae7135e6..00000000 --- a/src/main/java/org/solovyev/android/calculator/model/AndroidMathRegistryImpl.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (c) 2009-2011. Created by serso aka se.solovyev. - * For more information, please, contact se.solovyev@gmail.com - * or visit http://se.solovyev.org - */ - -package org.solovyev.android.calculator.model; - -import android.content.Context; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.solovyev.android.view.prefs.ResourceCache; -import org.solovyev.common.definitions.IBuilder; -import org.solovyev.common.math.MathEntity; -import org.solovyev.common.math.MathRegistry; - -import java.util.List; -import java.util.Map; - -/** - * User: serso - * Date: 10/30/11 - * Time: 1:03 AM - */ -public abstract class AndroidMathRegistryImpl implements AndroidMathRegistry { - - @NotNull - private final MathRegistry functionsRegistry; - - @NotNull - private final String prefix; - - protected AndroidMathRegistryImpl(@NotNull MathRegistry functionsRegistry, @NotNull String prefix) { - this.functionsRegistry = functionsRegistry; - this.prefix = prefix; - } - - @NotNull - protected abstract Map getSubstitutes(); - - @Nullable - @Override - public String getDescription(@NotNull Context context, @NotNull String mathEntityName) { - final String stringName; - - final Map substitutes = getSubstitutes(); - final String substitute = substitutes.get(mathEntityName); - if (substitute == null) { - stringName = prefix + mathEntityName; - } else { - stringName = prefix + substitute; - } - - return ResourceCache.instance.getCaption(stringName); - } - - @NotNull - @Override - public List getEntities() { - return functionsRegistry.getEntities(); - } - - @NotNull - @Override - public List getSystemEntities() { - return functionsRegistry.getSystemEntities(); - } - - @Override - public T add(@NotNull IBuilder IBuilder) { - return functionsRegistry.add(IBuilder); - } - - @Override - public void remove(@NotNull T var) { - functionsRegistry.remove(var); - } - - @NotNull - @Override - public List getNames() { - return functionsRegistry.getNames(); - } - - @Override - public boolean contains(@NotNull String name) { - return functionsRegistry.contains(name); - } - - @Override - public T get(@NotNull String name) { - return functionsRegistry.get(name); - } - - @Override - public T getById(@NotNull Integer id) { - return functionsRegistry.getById(id); - } -} diff --git a/src/main/java/org/solovyev/android/calculator/model/AndroidOperatorsMathRegistry.java b/src/main/java/org/solovyev/android/calculator/model/AndroidOperatorsMathRegistry.java index 79b37cf2..a4fb8050 100644 --- a/src/main/java/org/solovyev/android/calculator/model/AndroidOperatorsMathRegistry.java +++ b/src/main/java/org/solovyev/android/calculator/model/AndroidOperatorsMathRegistry.java @@ -6,8 +6,12 @@ package org.solovyev.android.calculator.model; +import android.content.Context; +import android.content.SharedPreferences; import jscl.math.operator.Operator; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.solovyev.common.definitions.IBuilder; import org.solovyev.common.math.MathRegistry; import java.util.HashMap; @@ -18,7 +22,7 @@ import java.util.Map; * Date: 11/17/11 * Time: 11:29 PM */ -public class AndroidOperatorsMathRegistry extends AndroidMathRegistryImpl { +public class AndroidOperatorsMathRegistry extends AbstractAndroidMathRegistry { @NotNull private static final Map substitutes = new HashMap(); @@ -48,4 +52,42 @@ public class AndroidOperatorsMathRegistry extends AndroidMathRegistryImpl createBuilder(@NotNull MathPersistenceEntity entity) { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + @NotNull + @Override + protected Class> getPersistenceContainerClass() { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + protected Integer getPreferenceStringId() { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public void save(@NotNull Context context) { + // not supported yet + } + + @Override + protected MathPersistenceEntity transform(@NotNull Operator entity) { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + @NotNull + @Override + protected MathEntityPersistenceContainer createPersistenceContainer() { + return null; //To change body of implemented methods use File | Settings | File Templates. + } } diff --git a/src/main/java/org/solovyev/android/calculator/model/AndroidPostfixFunctionsRegistry.java b/src/main/java/org/solovyev/android/calculator/model/AndroidPostfixFunctionsRegistry.java index 58075907..ecb7157b 100644 --- a/src/main/java/org/solovyev/android/calculator/model/AndroidPostfixFunctionsRegistry.java +++ b/src/main/java/org/solovyev/android/calculator/model/AndroidPostfixFunctionsRegistry.java @@ -6,8 +6,12 @@ package org.solovyev.android.calculator.model; +import android.content.Context; +import android.content.SharedPreferences; import jscl.math.operator.Operator; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.solovyev.common.definitions.IBuilder; import org.solovyev.common.math.MathRegistry; import java.util.HashMap; @@ -18,7 +22,7 @@ import java.util.Map; * Date: 11/19/11 * Time: 1:48 PM */ -public class AndroidPostfixFunctionsRegistry extends AndroidMathRegistryImpl { +public class AndroidPostfixFunctionsRegistry extends AbstractAndroidMathRegistry { @NotNull private static final Map substitutes = new HashMap(); @@ -47,4 +51,42 @@ public class AndroidPostfixFunctionsRegistry extends AndroidMathRegistryImpl createBuilder(@NotNull MathPersistenceEntity entity) { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + @NotNull + @Override + protected Class> getPersistenceContainerClass() { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + protected Integer getPreferenceStringId() { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public void save(@NotNull Context context) { + // not supported yet + } + + @Override + protected MathPersistenceEntity transform(@NotNull Operator entity) { + return null; //To change body of implemented methods use File | Settings | File Templates. + } + + @NotNull + @Override + protected MathEntityPersistenceContainer createPersistenceContainer() { + return null; //To change body of implemented methods use File | Settings | File Templates. + } } diff --git a/src/main/java/org/solovyev/android/calculator/model/AndroidVarsRegistry.java b/src/main/java/org/solovyev/android/calculator/model/AndroidVarsRegistry.java deleted file mode 100644 index 80b2b85e..00000000 --- a/src/main/java/org/solovyev/android/calculator/model/AndroidVarsRegistry.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (c) 2009-2011. Created by serso aka se.solovyev. - * For more information, please, contact se.solovyev@gmail.com - * or visit http://se.solovyev.org - */ - -package org.solovyev.android.calculator.model; - -import android.content.Context; -import android.content.SharedPreferences; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.solovyev.android.calculator.R; -import org.solovyev.common.utils.CollectionsUtils; - -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - -/** - * User: serso - * Date: 10/6/11 - * Time: 9:31 PM - */ -public interface AndroidVarsRegistry extends AndroidMathRegistry{ - - public static enum Category { - - system(R.string.c_var_system, 100){ - @Override - boolean isInCategory(@NotNull Var var) { - return var.isSystem(); - } - }, - - my(R.string.c_var_my, 0) { - @Override - boolean isInCategory(@NotNull Var var) { - return !var.isSystem(); - } - }; - - private final int captionId; - - private final int tabOrder; - - Category(int captionId, int tabOrder) { - this.captionId = captionId; - this.tabOrder = tabOrder; - } - - public int getCaptionId() { - return captionId; - } - - abstract boolean isInCategory(@NotNull Var var); - - @NotNull - public static List getCategoriesByTabOrder() { - final List result = CollectionsUtils.asList(Category.values()); - - Collections.sort(result, new Comparator() { - @Override - public int compare(Category category, Category category1) { - return category.tabOrder - category1.tabOrder; - } - }); - - return result; - } - } - - void load(@Nullable Context context, @Nullable SharedPreferences preferences); - - void save(@NotNull Context context); -} diff --git a/src/main/java/org/solovyev/android/calculator/model/AndroidVarsRegistryImpl.java b/src/main/java/org/solovyev/android/calculator/model/AndroidVarsRegistryImpl.java index c6267e4c..96dfb8bb 100644 --- a/src/main/java/org/solovyev/android/calculator/model/AndroidVarsRegistryImpl.java +++ b/src/main/java/org/solovyev/android/calculator/model/AndroidVarsRegistryImpl.java @@ -15,92 +15,41 @@ import org.jetbrains.annotations.Nullable; import org.simpleframework.xml.Serializer; import org.simpleframework.xml.core.Persister; import org.solovyev.android.calculator.R; -import org.solovyev.android.calculator.math.MathType; import org.solovyev.common.definitions.IBuilder; import org.solovyev.common.math.MathRegistry; import java.io.StringWriter; -import java.util.ArrayList; -import java.util.List; +import java.util.HashMap; +import java.util.Map; /** * User: serso * Date: 9/29/11 * Time: 4:57 PM */ -class AndroidVarsRegistryImpl implements AndroidVarsRegistry { +class AndroidVarsRegistryImpl extends AbstractAndroidMathRegistry { @NotNull - private final MathRegistry mathRegistry; + private static final Map substitutes = new HashMap(); + static { + substitutes.put("π", "pi"); + substitutes.put("∞", "inf"); + substitutes.put("h", "h_reduced"); + substitutes.put("NaN", "nan"); + } protected AndroidVarsRegistryImpl(@NotNull MathRegistry mathRegistry) { - this.mathRegistry = mathRegistry; + super(mathRegistry, "c_var_description_"); + } + + @NotNull + @Override + protected Map getSubstitutes() { + return substitutes; } public synchronized void load(@Nullable Context context, @Nullable SharedPreferences preferences) { - - if (context != null && preferences != null) { - final String value = preferences.getString(context.getString(R.string.p_calc_vars), null); - if (value != null) { - final Serializer serializer = new Persister(); - try { - final Vars vars = serializer.read(Vars.class, value); - for (Var var : vars.getVars()) { - if (!contains(var.getName())) { - add(new Var.Builder(var)); - } - } - } catch (Exception e) { - throw new RuntimeException(e); - } - } - } - - - for (String systemVarName : MathType.constants) { - - final Var.Builder builder; - final Integer varDescription; - - if (systemVarName.equals(MathType.E)) { - builder = createBuilder(systemVarName, String.valueOf(Math.E)); - varDescription = R.string.c_e_description; - } else if (systemVarName.equals(MathType.PI)) { - builder = createBuilder(systemVarName, String.valueOf(Math.PI)); - varDescription = R.string.c_pi_description; - } else if (systemVarName.equals(MathType.C)) { - builder = createBuilder(systemVarName, String.valueOf(MathType.C_VALUE)); - varDescription = R.string.c_c_description; - } else if (systemVarName.equals(MathType.G)) { - builder = createBuilder(systemVarName, String.valueOf(MathType.G_VALUE)); - varDescription = R.string.c_g_description; - /* } else if (systemVarName.equals(MathType.H)) { - builder = new Var.Builder(systemVarName, MathType.H_VALUE); - varDescription = R.string.c_h_description;*/ - } else if (systemVarName.equals(MathType.H_REDUCED)) { - builder = createBuilder(systemVarName, String.valueOf(MathType.H_REDUCED_VALUE)); - varDescription = R.string.c_h_reduced_description; - } else if (systemVarName.equals(MathType.IMAGINARY_NUMBER)) { - builder = createBuilder(systemVarName, MathType.IMAGINARY_NUMBER_JSCL); - varDescription = R.string.c_i_description; - } else if (systemVarName.equals(MathType.NAN)) { - builder = createBuilder(systemVarName, MathType.NAN); - varDescription = R.string.c_nan_description; - } else if (systemVarName.equals(MathType.INFINITY)) { - builder = createBuilder(systemVarName, MathType.INFINITY_JSCL); - varDescription = R.string.c_infinity_description; - } else { - throw new IllegalArgumentException(systemVarName + " is not supported yet!"); - } - - builder.setSystem(true); - - if (context != null) { - builder.setDescription(context.getString(varDescription)); - } - - add(builder); - } + super.load(context, preferences); tryToAddAuxVar("x"); tryToAddAuxVar("y"); @@ -114,140 +63,59 @@ class AndroidVarsRegistryImpl implements AndroidVarsRegistry { }*/ } + + @NotNull + @Override + protected IBuilder createBuilder(@NotNull Var entity) { + return new Var.Builder(entity); + } + + @NotNull + @Override + protected Class> getPersistenceContainerClass() { + return Vars.class; + } + + @NotNull + @Override + protected MathEntityPersistenceContainer createPersistenceContainer() { + return new Vars(); + } + + @NotNull + protected Integer getPreferenceStringId() { + return R.string.p_calc_vars; + } + private void tryToAddAuxVar(@NotNull String name) { if ( !contains(name) ) { add(new Var.Builder(name, (String)null)); } } - private Var.Builder createBuilder(@NotNull String varName, @NotNull String varValue) { - final Var.Builder result; - - final IConstant varFromRegistry = mathRegistry.get(varName); - if (varFromRegistry == null) { - result = new Var.Builder(varName, varValue); - } else { - result = new Var.Builder(varFromRegistry); - } - - return result; - } - - @Override - public synchronized void save(@NotNull Context context) { - final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context); - final SharedPreferences.Editor editor = settings.edit(); - - final Vars vars = new Vars(); - for (Var var : this.getEntities()) { - if (!var.isSystem()) { - vars.getVars().add(var); - } - } - - final StringWriter sw = new StringWriter(); - final Serializer serializer = new Persister(); - try { - serializer.write(vars, sw); - } catch (Exception e) { - throw new RuntimeException(e); - } - - editor.putString(context.getString(R.string.p_calc_vars), sw.toString()); - - editor.commit(); - } - @NotNull @Override - public List getEntities() { - final List result = new ArrayList(); - for (IConstant iConstant : mathRegistry.getEntities()) { - result.add(transform(iConstant)); - } - return result; - } - - @NotNull - @Override - public List getSystemEntities() { - final List result = new ArrayList(); - for (IConstant iConstant : mathRegistry.getSystemEntities()) { - result.add(transform(iConstant)); - } - return result; - } - - @Override - public Var add(@NotNull IBuilder IBuilder) { - IConstant result = mathRegistry.add(IBuilder); - if (result instanceof Var) { - return (Var) result; - } else if (result != null) { - return transform(result); + protected Var transform(@NotNull IConstant entity) { + if (entity instanceof Var) { + return (Var) entity; } else { - return null; - } - } - - @NotNull - private Var transform(@NotNull IConstant result) { - return new Var.Builder(result).create(); - } - - @Override - public void remove(@NotNull Var var) { - mathRegistry.remove(var); - } - - @NotNull - @Override - public List getNames() { - return mathRegistry.getNames(); - } - - @Override - public boolean contains(@NotNull String name) { - return mathRegistry.contains(name); - } - - @Override - public Var get(@NotNull String name) { - IConstant result = mathRegistry.get(name); - if (result instanceof Var) { - return (Var) result; - } else if (result != null) { - return transform(result); - } else { - return null; + return new Var.Builder(entity).create(); } } @Override - public Var getById(@NotNull Integer id) { - final IConstant result = mathRegistry.getById(id); - if (result instanceof Var) { - return (Var) result; - } else if (result != null) { - return transform(result); - } else { - return null; - } - } - - @Override public String getDescription(@NotNull Context context, @NotNull String mathEntityName) { - final Var var = get(mathEntityName); - if (var != null) { + final IConstant var = get(mathEntityName); + if (var != null && !var.isSystem()) { return var.getDescription(); } else { - return null; + return super.getDescription(context, mathEntityName); } } @Override - public String getCategory(@NotNull Var var) { - for (Category category : Category.values()) { + public String getCategory(@NotNull IConstant var) { + for (VarCategory category : VarCategory.values()) { if ( category.isInCategory(var) ) { return category.name(); } diff --git a/src/main/java/org/solovyev/android/calculator/model/CalculatorEngine.java b/src/main/java/org/solovyev/android/calculator/model/CalculatorEngine.java index 9a5afa82..6ca6da8a 100644 --- a/src/main/java/org/solovyev/android/calculator/model/CalculatorEngine.java +++ b/src/main/java/org/solovyev/android/calculator/model/CalculatorEngine.java @@ -10,6 +10,7 @@ import android.content.SharedPreferences; import jscl.*; import jscl.math.Generic; import jscl.math.function.Function; +import jscl.math.function.IConstant; import jscl.math.operator.Operator; import jscl.text.ParseInterruptedException; import org.jetbrains.annotations.NotNull; @@ -64,7 +65,7 @@ public enum CalculatorEngine { public final TextProcessor preprocessor = new ToJsclTextProcessor(); @NotNull - private final AndroidVarsRegistry varsRegister = new AndroidVarsRegistryImpl(engine.getConstantsRegistry()); + private final AndroidMathRegistry varsRegister = new AndroidVarsRegistryImpl(engine.getConstantsRegistry()); @NotNull private final AndroidMathRegistry functionsRegistry = new AndroidFunctionsMathRegistry(engine.getFunctionsRegistry()); @@ -304,7 +305,7 @@ public enum CalculatorEngine { } @NotNull - public AndroidVarsRegistry getVarsRegister() { + public AndroidMathRegistry getVarsRegister() { return varsRegister; } diff --git a/src/main/java/org/solovyev/android/calculator/model/Functions.java b/src/main/java/org/solovyev/android/calculator/model/Functions.java new file mode 100644 index 00000000..35ae2b76 --- /dev/null +++ b/src/main/java/org/solovyev/android/calculator/model/Functions.java @@ -0,0 +1,29 @@ +package org.solovyev.android.calculator.model; + +import jscl.math.function.CustomFunction; +import jscl.math.function.Function; +import jscl.math.function.IConstant; +import org.simpleframework.xml.ElementList; +import org.simpleframework.xml.Root; + +import java.util.ArrayList; +import java.util.List; + +/** + * User: serso + * Date: 12/22/11 + * Time: 5:15 PM + */ +@Root +public class Functions implements MathEntityPersistenceContainer { + + @ElementList(type = CustomFunction.class) + private List functions = new ArrayList(); + + public Functions() { + } + + public List getEntities() { + return functions; + } +} diff --git a/src/main/java/org/solovyev/android/calculator/model/MathEntityPersistenceContainer.java b/src/main/java/org/solovyev/android/calculator/model/MathEntityPersistenceContainer.java new file mode 100644 index 00000000..7406b223 --- /dev/null +++ b/src/main/java/org/solovyev/android/calculator/model/MathEntityPersistenceContainer.java @@ -0,0 +1,12 @@ +package org.solovyev.android.calculator.model; + +import java.util.List; + +/** + * User: serso + * Date: 12/22/11 + * Time: 5:03 PM + */ +public interface MathEntityPersistenceContainer { + public List getEntities(); +} diff --git a/src/main/java/org/solovyev/android/calculator/model/MathPersistenceEntity.java b/src/main/java/org/solovyev/android/calculator/model/MathPersistenceEntity.java new file mode 100644 index 00000000..abf4e48f --- /dev/null +++ b/src/main/java/org/solovyev/android/calculator/model/MathPersistenceEntity.java @@ -0,0 +1,14 @@ +package org.solovyev.android.calculator.model; + +import org.jetbrains.annotations.NotNull; + +/** + * User: serso + * Date: 12/22/11 + * Time: 5:27 PM + */ +public interface MathPersistenceEntity { + + @NotNull + String getName(); +} diff --git a/src/main/java/org/solovyev/android/calculator/model/PreparedExpression.java b/src/main/java/org/solovyev/android/calculator/model/PreparedExpression.java index 820ae664..879b99f0 100644 --- a/src/main/java/org/solovyev/android/calculator/model/PreparedExpression.java +++ b/src/main/java/org/solovyev/android/calculator/model/PreparedExpression.java @@ -6,6 +6,7 @@ package org.solovyev.android.calculator.model; +import jscl.math.function.IConstant; import org.jetbrains.annotations.NotNull; import java.util.List; @@ -21,9 +22,9 @@ public class PreparedExpression implements CharSequence{ private String expression; @NotNull - private List undefinedVars; + private List undefinedVars; - public PreparedExpression(@NotNull String expression, @NotNull List undefinedVars) { + public PreparedExpression(@NotNull String expression, @NotNull List undefinedVars) { this.expression = expression; this.undefinedVars = undefinedVars; } @@ -38,7 +39,7 @@ public class PreparedExpression implements CharSequence{ } @NotNull - public List getUndefinedVars() { + public List getUndefinedVars() { return undefinedVars; } diff --git a/src/main/java/org/solovyev/android/calculator/model/ToJsclTextProcessor.java b/src/main/java/org/solovyev/android/calculator/model/ToJsclTextProcessor.java index 2e764b8b..6b46a57d 100644 --- a/src/main/java/org/solovyev/android/calculator/model/ToJsclTextProcessor.java +++ b/src/main/java/org/solovyev/android/calculator/model/ToJsclTextProcessor.java @@ -6,6 +6,7 @@ package org.solovyev.android.calculator.model; +import jscl.math.function.IConstant; import org.jetbrains.annotations.NotNull; import org.solovyev.android.calculator.StartsWithFinder; import org.solovyev.android.calculator.math.MathType; @@ -22,10 +23,10 @@ class ToJsclTextProcessor implements TextProcessor { @Override @NotNull public PreparedExpression process(@NotNull String s) throws CalculatorParseException { - return processWithDepth(s, 0, new ArrayList()); + return processWithDepth(s, 0, new ArrayList()); } - private static PreparedExpression processWithDepth(@NotNull String s, int depth, @NotNull List undefinedVars) throws CalculatorParseException { + private static PreparedExpression processWithDepth(@NotNull String s, int depth, @NotNull List undefinedVars) throws CalculatorParseException { return replaceVariables(processExpression(s).toString(), depth, undefinedVars); } @@ -69,7 +70,7 @@ class ToJsclTextProcessor implements TextProcessor { } @NotNull - private static PreparedExpression replaceVariables(@NotNull final String s, int depth, @NotNull List undefinedVars) throws CalculatorParseException { + private static PreparedExpression replaceVariables(@NotNull final String s, int depth, @NotNull List undefinedVars) throws CalculatorParseException { if (depth >= MAX_DEPTH) { throw new CalculatorParseException(Messages.msg_6, s); } else { @@ -89,7 +90,7 @@ class ToJsclTextProcessor implements TextProcessor { if (operatorName == null) { String varName = CollectionsUtils.find(CalculatorEngine.instance.getVarsRegister().getNames(), startsWithFinder); if (varName != null) { - final Var var = CalculatorEngine.instance.getVarsRegister().get(varName); + final IConstant var = CalculatorEngine.instance.getVarsRegister().get(varName); if (var != null) { if (!var.isDefined()) { undefinedVars.add(var); diff --git a/src/main/java/org/solovyev/android/calculator/model/Var.java b/src/main/java/org/solovyev/android/calculator/model/Var.java index 8d75275f..f561a75a 100644 --- a/src/main/java/org/solovyev/android/calculator/model/Var.java +++ b/src/main/java/org/solovyev/android/calculator/model/Var.java @@ -25,7 +25,7 @@ import org.solovyev.common.utils.StringUtils; */ @Root -public class Var implements IConstant { +public class Var implements IConstant, MathPersistenceEntity { @Transient private Integer id; @@ -225,17 +225,7 @@ public class Var implements IConstant { @Override public String toString() { - final Double doubleValue = getDoubleValue(); - if (doubleValue == null) { - final String stringValue = getValue(); - if (!StringUtils.isEmpty(stringValue)) { - return getName() + " = " + stringValue; - } else { - return getName(); - } - } else { - return getName() + " = " + doubleValue; - } + return ExtendedConstant.toString(this); } @Override diff --git a/src/main/java/org/solovyev/android/calculator/model/VarCategory.java b/src/main/java/org/solovyev/android/calculator/model/VarCategory.java new file mode 100644 index 00000000..9914e4f2 --- /dev/null +++ b/src/main/java/org/solovyev/android/calculator/model/VarCategory.java @@ -0,0 +1,61 @@ +package org.solovyev.android.calculator.model; + +import jscl.math.function.IConstant; +import org.jetbrains.annotations.NotNull; +import org.solovyev.android.calculator.R; +import org.solovyev.common.utils.CollectionsUtils; + +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +/** +* User: serso +* Date: 12/22/11 +* Time: 4:25 PM +*/ +public enum VarCategory { + + system(R.string.c_var_system, 100){ + @Override + boolean isInCategory(@NotNull IConstant var) { + return var.isSystem(); + } + }, + + my(R.string.c_var_my, 0) { + @Override + boolean isInCategory(@NotNull IConstant var) { + return !var.isSystem(); + } + }; + + private final int captionId; + + private final int tabOrder; + + VarCategory(int captionId, int tabOrder) { + this.captionId = captionId; + this.tabOrder = tabOrder; + } + + public int getCaptionId() { + return captionId; + } + + abstract boolean isInCategory(@NotNull IConstant var); + + @NotNull + public static List getCategoriesByTabOrder() { + final List result = CollectionsUtils.asList(VarCategory.values()); + + Collections.sort(result, new Comparator() { + @Override + public int compare(VarCategory category, VarCategory category1) { + return category.tabOrder - category1.tabOrder; + } + }); + + return result; + } +} diff --git a/src/main/java/org/solovyev/android/calculator/model/Vars.java b/src/main/java/org/solovyev/android/calculator/model/Vars.java index 9e7b866a..edd94ffb 100644 --- a/src/main/java/org/solovyev/android/calculator/model/Vars.java +++ b/src/main/java/org/solovyev/android/calculator/model/Vars.java @@ -1,5 +1,6 @@ package org.solovyev.android.calculator.model; +import jscl.math.function.IConstant; import org.simpleframework.xml.ElementList; import org.simpleframework.xml.Root; @@ -13,15 +14,15 @@ import java.util.List; */ @Root -public class Vars { +public class Vars implements MathEntityPersistenceContainer { - @ElementList + @ElementList(type = Var.class) private List vars = new ArrayList(); public Vars() { } - public List getVars() { + public List getEntities() { return vars; } } diff --git a/src/test/java/org/solovyev/android/calculator/model/VarTest.java b/src/test/java/org/solovyev/android/calculator/model/VarTest.java index cc17a44d..3b4f0435 100644 --- a/src/test/java/org/solovyev/android/calculator/model/VarTest.java +++ b/src/test/java/org/solovyev/android/calculator/model/VarTest.java @@ -6,6 +6,7 @@ package org.solovyev.android.calculator.model; +import jscl.math.function.IConstant; import junit.framework.Assert; import org.junit.Test; import org.simpleframework.xml.Serializer; @@ -40,9 +41,9 @@ public class VarTest { public void testXml() throws Exception { final Vars vars = new Vars(); Var first = new Var.Builder("e", Math.E).setDescription("description").setSystem(true).create(); - vars.getVars().add(first); + vars.getEntities().add(first); Var second = new Var.Builder(";", 3d).setSystem(true).create(); - vars.getVars().add(second); + vars.getEntities().add(second); final StringWriter sw = new StringWriter(); final Serializer serializer = new Persister(); @@ -50,17 +51,16 @@ public class VarTest { Assert.assertEquals(xml, sw.toString()); - final Vars result = serializer.read(Vars.class, xml); - final Var actualFirst = result.getVars().get(0); - final Var actualSecond = result.getVars().get(1); + final IConstant actualFirst = result.getEntities().get(0); + final IConstant actualSecond = result.getEntities().get(1); areEqual(first, actualFirst); areEqual(second, actualSecond); } - private void areEqual(Var expected, Var actual) { + private void areEqual(IConstant expected, IConstant actual) { Assert.assertEquals(expected.getName(), actual.getName()); Assert.assertEquals(expected.getDescription(), actual.getDescription()); Assert.assertEquals(expected.getValue(), actual.getValue());