Remove Locator class

This commit is contained in:
serso 2016-02-28 23:49:41 +01:00
parent 218dec4a36
commit d1d6ab62dd
49 changed files with 704 additions and 1593 deletions

View File

@ -41,7 +41,6 @@ import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
@ -60,9 +59,7 @@ import org.solovyev.android.wizard.Wizards;
import org.solovyev.common.JPredicate;
import java.util.Collection;
import java.util.Formatter;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicInteger;
@ -79,16 +76,6 @@ public final class App {
public static final String TAG = "C++";
@Nonnull
public static String subTag(@Nonnull String subTag) {
return sub(TAG, subTag);
}
@NonNull
public static String sub(@Nonnull String tag, @Nonnull String subTag) {
return tag + "/" + subTag;
}
@Nonnull
private static Languages languages;
@Nonnull

View File

@ -28,10 +28,7 @@ import android.text.TextUtils;
import android.util.Log;
import com.squareup.otto.Bus;
import com.squareup.otto.Subscribe;
import jscl.JsclArithmeticException;
import jscl.JsclMathEngine;
import jscl.NumeralBase;
import jscl.NumeralBaseException;
import jscl.*;
import jscl.math.Generic;
import jscl.math.function.Constants;
import jscl.math.function.IConstant;
@ -65,16 +62,12 @@ public class Calculator implements SharedPreferences.OnSharedPreferenceChangeLis
public static final long NO_SEQUENCE = -1;
@Nonnull
private final CalculatorEventContainer calculatorEventContainer = new ListCalculatorEventContainer();
@Nonnull
private static final AtomicLong SEQUENCER = new AtomicLong(NO_SEQUENCE);
@Nonnull
private final SharedPreferences preferences;
@Nonnull
private final Bus bus;
@Nonnull
private final Executor ui;
final Bus bus;
@Nonnull
private final Executor background;
@ -85,15 +78,14 @@ public class Calculator implements SharedPreferences.OnSharedPreferenceChangeLis
@Inject
Editor editor;
@Inject
JsclMathEngine mathEngine;
Engine engine;
@Inject
ToJsclTextProcessor preprocessor;
@Inject
public Calculator(@Nonnull SharedPreferences preferences, @Nonnull Bus bus, @Named(AppModule.THREAD_UI) @Nonnull Executor ui, @Named(AppModule.THREAD_BACKGROUND) @Nonnull Executor background) {
public Calculator(@Nonnull SharedPreferences preferences, @Nonnull Bus bus, @Named(AppModule.THREAD_BACKGROUND) @Nonnull Executor background) {
this.preferences = preferences;
this.bus = bus;
this.ui = ui;
this.background = background;
bus.register(this);
preferences.registerOnSharedPreferenceChangeListener(this);
@ -109,12 +101,6 @@ public class Calculator implements SharedPreferences.OnSharedPreferenceChangeLis
return to.toString(value);
}
@Nonnull
private CalculatorEventData nextEventData() {
final long eventId = nextSequence();
return CalculatorEventDataImpl.newInstance(eventId, eventId);
}
public void evaluate() {
final EditorState state = editor.getState();
evaluate(JsclOperation.numeric, state.getTextString());
@ -143,7 +129,7 @@ public class Calculator implements SharedPreferences.OnSharedPreferenceChangeLis
}
public void init(@Nonnull Executor init) {
Locator.getInstance().getEngine().init(init);
engine.init(init);
setCalculateOnFly(Preferences.Calculations.calculateOnFly.getPreference(preferences));
}
@ -180,6 +166,7 @@ public class Calculator implements SharedPreferences.OnSharedPreferenceChangeLis
pe = prepare(e);
try {
final MathEngine mathEngine = engine.getMathEngine();
mathEngine.setMessageRegistry(mr);
final Generic result = o.evaluateGeneric(pe.value, mathEngine);
@ -188,7 +175,7 @@ public class Calculator implements SharedPreferences.OnSharedPreferenceChangeLis
//noinspection ResultOfMethodCallIgnored
result.toString();
final String stringResult = o.getFromProcessor().process(result);
final String stringResult = o.getFromProcessor(engine).process(result);
bus.post(new CalculationFinishedEvent(o, e, sequence, result, stringResult, collectMessages(mr)));
} catch (JsclArithmeticException exception) {
@ -252,7 +239,7 @@ public class Calculator implements SharedPreferences.OnSharedPreferenceChangeLis
public void convert(@Nonnull final DisplayState state, @Nonnull final NumeralBase to) {
final Generic value = state.getResult();
Check.isNotNull(value);
final NumeralBase from = mathEngine.getNumeralBase();
final NumeralBase from = engine.getMathEngine().getNumeralBase();
if (from == to) {
return;
}
@ -282,24 +269,6 @@ public class Calculator implements SharedPreferences.OnSharedPreferenceChangeLis
}
}
public void fireCalculatorEvent(@Nonnull final CalculatorEventData calculatorEventData, @Nonnull final CalculatorEventType calculatorEventType, @Nullable final Object data) {
ui.execute(new Runnable() {
@Override
public void run() {
calculatorEventContainer.fireCalculatorEvent(calculatorEventData, calculatorEventType, data);
}
});
}
@Nonnull
public CalculatorEventData fireCalculatorEvent(@Nonnull final CalculatorEventType calculatorEventType, @Nullable final Object data) {
final CalculatorEventData eventData = nextEventData();
fireCalculatorEvent(eventData, calculatorEventType, data);
return eventData;
}
@Subscribe
public void onEditorChanged(@Nonnull Editor.ChangedEvent e) {
if (!calculateOnFly) {
@ -324,8 +293,8 @@ public class Calculator implements SharedPreferences.OnSharedPreferenceChangeLis
updateAnsVariable(text);
}
private void updateAnsVariable(@NonNull String value) {
final VariablesRegistry variablesRegistry = Locator.getInstance().getEngine().getVariablesRegistry();
void updateAnsVariable(@NonNull String value) {
final VariablesRegistry variablesRegistry = engine.getVariablesRegistry();
final IConstant variable = variablesRegistry.get(Constants.ANS);
final CppVariable.Builder b = variable != null ? CppVariable.builder(variable) : CppVariable.builder(Constants.ANS);

View File

@ -137,8 +137,6 @@ public class CalculatorApplication extends android.app.Application implements Sh
languages.updateContextLocale(this, true);
App.getGa().reportInitially(preferences);
Locator.getInstance().init(engine);
calculator.init(initThread);
initThread.execute(new Runnable() {

View File

@ -1,79 +0,0 @@
/*
* Copyright 2013 serso aka se.solovyev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Contact details
*
* Email: se.solovyev@gmail.com
* Site: http://se.solovyev.org
*/
package org.solovyev.android.calculator;
import java.util.List;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* User: Solovyev_S
* Date: 20.09.12
* Time: 16:39
*/
public interface CalculatorEventContainer {
void addCalculatorEventListener(@Nonnull CalculatorEventListener calculatorEventListener);
void removeCalculatorEventListener(@Nonnull CalculatorEventListener calculatorEventListener);
void fireCalculatorEvent(@Nonnull CalculatorEventData calculatorEventData, @Nonnull CalculatorEventType calculatorEventType, @Nullable Object data);
void fireCalculatorEvents(@Nonnull List<CalculatorEvent> calculatorEvents);
class CalculatorEvent {
@Nonnull
private CalculatorEventData calculatorEventData;
@Nonnull
private CalculatorEventType calculatorEventType;
@Nullable
private Object data;
public CalculatorEvent(@Nonnull CalculatorEventData calculatorEventData,
@Nonnull CalculatorEventType calculatorEventType,
@Nullable Object data) {
this.calculatorEventData = calculatorEventData;
this.calculatorEventType = calculatorEventType;
this.data = data;
}
@Nonnull
public CalculatorEventData getCalculatorEventData() {
return calculatorEventData;
}
@Nonnull
public CalculatorEventType getCalculatorEventType() {
return calculatorEventType;
}
@Nullable
public Object getData() {
return data;
}
}
}

View File

@ -1,39 +0,0 @@
/*
* Copyright 2013 serso aka se.solovyev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Contact details
*
* Email: se.solovyev@gmail.com
* Site: http://se.solovyev.org
*/
package org.solovyev.android.calculator;
import java.util.EventListener;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* User: Solovyev_S
* Date: 20.09.12
* Time: 16:39
*/
public interface CalculatorEventListener extends EventListener {
void onCalculatorEvent(@Nonnull CalculatorEventData calculatorEventData, @Nonnull CalculatorEventType calculatorEventType, @Nullable Object data);
}

View File

@ -1,29 +0,0 @@
/*
* Copyright 2013 serso aka se.solovyev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Contact details
*
* Email: se.solovyev@gmail.com
* Site: http://se.solovyev.org
*/
package org.solovyev.android.calculator;
public enum CalculatorEventType {
;
}

View File

@ -1,34 +0,0 @@
/*
* Copyright 2013 serso aka se.solovyev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Contact details
*
* Email: se.solovyev@gmail.com
* Site: http://se.solovyev.org
*/
package org.solovyev.android.calculator;
import javax.annotation.Nonnull;
public interface CalculatorLocator {
void init(@Nonnull Engine engine);
@Nonnull
Engine getEngine();
}

View File

@ -1,36 +0,0 @@
/*
* Copyright 2013 serso aka se.solovyev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Contact details
*
* Email: se.solovyev@gmail.com
* Site: http://se.solovyev.org
*/
package org.solovyev.android.calculator;
/**
* User: serso
* Date: 9/22/12
* Time: 7:13 PM
*/
public final class CalculatorUtils {
private CalculatorUtils() {
throw new AssertionError();
}
}

View File

@ -1,40 +0,0 @@
/*
* Copyright 2013 serso aka se.solovyev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Contact details
*
* Email: se.solovyev@gmail.com
* Site: http://se.solovyev.org
*/
package org.solovyev.android.calculator;
import javax.annotation.Nonnull;
/**
* User: serso
* Date: 10/1/12
* Time: 11:16 PM
*/
public interface Change<T> {
@Nonnull
T getOldValue();
@Nonnull
T getNewValue();
}

View File

@ -1,64 +0,0 @@
/*
* Copyright 2013 serso aka se.solovyev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Contact details
*
* Email: se.solovyev@gmail.com
* Site: http://se.solovyev.org
*/
package org.solovyev.android.calculator;
import javax.annotation.Nonnull;
/**
* User: serso
* Date: 10/1/12
* Time: 11:18 PM
*/
public class ChangeImpl<T> implements Change<T> {
@Nonnull
private T oldValue;
@Nonnull
private T newValue;
private ChangeImpl() {
}
@Nonnull
public static <T> Change<T> newInstance(@Nonnull T oldValue, @Nonnull T newValue) {
final ChangeImpl<T> result = new ChangeImpl<T>();
result.oldValue = oldValue;
result.newValue = newValue;
return result;
}
@Nonnull
@Override
public T getOldValue() {
return this.oldValue;
}
@Nonnull
@Override
public T getNewValue() {
return this.newValue;
}
}

View File

@ -1,54 +0,0 @@
/*
* Copyright 2013 serso aka se.solovyev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Contact details
*
* Email: se.solovyev@gmail.com
* Site: http://se.solovyev.org
*/
package org.solovyev.android.calculator;
import org.solovyev.common.JPredicate;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* User: serso
* Date: 10/3/11
* Time: 12:54 AM
*/
public class CharacterAtPositionFinder implements JPredicate<Character> {
@Nonnull
private final String targetString;
private int i;
public CharacterAtPositionFinder(@Nonnull String targetString, int i) {
this.targetString = targetString;
this.i = i;
}
@Override
public boolean apply(@Nullable Character s) {
return s != null && s.equals(targetString.charAt(i));
}
public void setI(int i) {
this.i = i;
}
}

View File

@ -1,48 +0,0 @@
/*
* Copyright 2013 serso aka se.solovyev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Contact details
*
* Email: se.solovyev@gmail.com
* Site: http://se.solovyev.org
*/
package org.solovyev.android.calculator;
import android.graphics.PointF;
import android.view.MotionEvent;
import org.solovyev.android.views.dragbutton.DirectionDragButton;
import org.solovyev.android.views.dragbutton.DragButton;
import org.solovyev.android.views.dragbutton.DragDirection;
import org.solovyev.android.views.dragbutton.SimpleDragListener;
import javax.annotation.Nonnull;
public class DigitButtonDragProcessor implements SimpleDragListener.DragProcessor {
@Nonnull
private Keyboard keyboard;
public DigitButtonDragProcessor(@Nonnull Keyboard keyboard) {
this.keyboard = keyboard;
}
@Override
public boolean processDragEvent(@Nonnull DragDirection direction, @Nonnull DragButton button, @Nonnull PointF startPoint, @Nonnull MotionEvent motionEvent) {
final String text = ((DirectionDragButton) button).getText(direction);
return keyboard.buttonPressed(text);
}
}

View File

@ -92,6 +92,8 @@ public class DisplayFragment extends BaseFragment implements View.OnClickListene
Plotter plotter;
@Inject
Calculator calculator;
@Inject
Engine engine;
public DisplayFragment() {
super(R.layout.cpp_app_display);
@ -149,8 +151,7 @@ public class DisplayFragment extends BaseFragment implements View.OnClickListene
protected boolean isMenuItemVisible(@NonNull ConversionMenuItem menuItem,
@Nonnull Generic generic) {
final NumeralBase fromNumeralBase =
Locator.getInstance().getEngine().getMathEngine().getNumeralBase();
final NumeralBase fromNumeralBase = engine.getMathEngine().getNumeralBase();
if (fromNumeralBase != menuItem.toNumeralBase) {
return calculator.canConvert(generic, fromNumeralBase, menuItem.toNumeralBase);
}

View File

@ -30,8 +30,6 @@ public class FloatingCalculatorKeyboard extends BaseFloatingKeyboard {
private final List<String> parameterNames;
@NonNull
private final SimpleDragListener dragListener;
@NonNull
private final String multiplicationSign = Locator.getInstance().getEngine().getMultiplicationSign();
public FloatingCalculatorKeyboard(@NonNull User user, @NonNull List<String> parameterNames) {
super(user);
@ -76,7 +74,7 @@ public class FloatingCalculatorKeyboard extends BaseFloatingKeyboard {
addButton(row, 0, "7");
addButton(row, 0, "8");
addButton(row, 0, "9").setText("π", up).setText("e", down);
addOperationButton(row, R.id.cpp_kb_button_multiply, Locator.getInstance().getEngine().getMultiplicationSign()).setText("^n", up).setText("^2", down);
addOperationButton(row, R.id.cpp_kb_button_multiply, "×").setText("^n", up).setText("^2", down);
addOperationButton(row, R.id.cpp_kb_button_plus, "+");
addButton(row, R.id.cpp_kb_button_clear, "C");
@ -107,7 +105,7 @@ public class FloatingCalculatorKeyboard extends BaseFloatingKeyboard {
addButton(row, 0, "7");
addButton(row, 0, "8");
addButton(row, 0, "9").setText("π", up).setText("e", down);
addOperationButton(row, R.id.cpp_kb_button_multiply, multiplicationSign).setText("^n", up).setText("^2", down);
addOperationButton(row, R.id.cpp_kb_button_multiply, "×").setText("^n", up).setText("^2", down);
addButton(row, R.id.cpp_kb_button_clear, "C");
row = makeRow();
@ -186,7 +184,7 @@ public class FloatingCalculatorKeyboard extends BaseFloatingKeyboard {
user.insertOperator('-');
break;
case R.id.cpp_kb_button_multiply:
user.insertOperator(multiplicationSign);
user.insertOperator("×");
break;
case R.id.cpp_kb_button_functions_constants:
user.showFunctionsConstants(v);

View File

@ -49,6 +49,8 @@ public class Keyboard implements SharedPreferences.OnSharedPreferenceChangeListe
@Inject
Calculator calculator;
@Inject
Engine engine;
@Inject
Lazy<Clipboard> clipboard;
@Inject
Lazy<Bus> bus;
@ -81,7 +83,7 @@ public class Keyboard implements SharedPreferences.OnSharedPreferenceChangeListe
int cursorPositionOffset = 0;
final StringBuilder textToBeInserted = new StringBuilder(text);
MathType.getType(text, 0, false, mathType);
MathType.getType(text, 0, false, mathType, engine);
switch (mathType.type) {
case function:
textToBeInserted.append("()");

View File

@ -1,83 +0,0 @@
/*
* Copyright 2013 serso aka se.solovyev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Contact details
*
* Email: se.solovyev@gmail.com
* Site: http://se.solovyev.org
*/
package org.solovyev.android.calculator;
import org.solovyev.common.listeners.JListeners;
import org.solovyev.common.listeners.Listeners;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* User: Solovyev_S
* Date: 20.09.12
* Time: 16:42
*/
public class ListCalculatorEventContainer implements CalculatorEventContainer {
@Nonnull
private static final String TAG = "CalculatorEventData";
@Nonnull
private final JListeners<CalculatorEventListener> listeners = Listeners.newWeakRefListeners();
@Override
public void addCalculatorEventListener(@Nonnull CalculatorEventListener calculatorEventListener) {
listeners.addListener(calculatorEventListener);
}
@Override
public void removeCalculatorEventListener(@Nonnull CalculatorEventListener calculatorEventListener) {
listeners.removeListener(calculatorEventListener);
}
@Override
public void fireCalculatorEvent(@Nonnull CalculatorEventData calculatorEventData, @Nonnull CalculatorEventType calculatorEventType, @Nullable Object data) {
fireCalculatorEvents(Arrays.asList(new CalculatorEvent(calculatorEventData, calculatorEventType, data)));
}
@Override
public void fireCalculatorEvents(@Nonnull List<CalculatorEvent> calculatorEvents) {
final Collection<CalculatorEventListener> listeners = this.listeners.getListeners();
//final CalculatorLogger logger = Locator.getInstance().getLogger();
for (CalculatorEvent e : calculatorEvents) {
//Locator.getInstance().getLogger().debug(TAG, "Event fired: " + e.getCalculatorEventType());
for (CalculatorEventListener listener : listeners) {
/*long startTime = System.currentTimeMillis();*/
listener.onCalculatorEvent(e.getCalculatorEventData(), e.getCalculatorEventType(), e.getData());
/* long endTime = System.currentTimeMillis();
long totalTime = (endTime - startTime);
if ( totalTime > 300 ) {
logger.debug(TAG + "_" + e.getCalculatorEventData().getEventId(), "Started event: " + e.getCalculatorEventType() + " with data: " + e.getData() + " for: " + listener.getClass().getSimpleName());
logger.debug(TAG + "_" + e.getCalculatorEventData().getEventId(), "Total time, ms: " + totalTime);
}*/
}
}
}
}

View File

@ -1,54 +0,0 @@
/*
* Copyright 2013 serso aka se.solovyev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Contact details
*
* Email: se.solovyev@gmail.com
* Site: http://se.solovyev.org
*/
package org.solovyev.android.calculator;
import javax.annotation.Nonnull;
public class Locator implements CalculatorLocator {
@Nonnull
private static final Locator instance = new Locator();
@Nonnull
private Engine engine;
public Locator() {
}
@Nonnull
public static CalculatorLocator getInstance() {
return instance;
}
@Override
public void init(@Nonnull Engine engine) {
this.engine = engine;
}
@Nonnull
@Override
public Engine getEngine() {
return engine;
}
}

View File

@ -23,15 +23,6 @@
package org.solovyev.android.calculator;
import android.text.SpannableStringBuilder;
import org.solovyev.android.calculator.math.MathType;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import jscl.MathContext;
import jscl.MathEngine;
import jscl.NumeralBase;
@ -40,6 +31,12 @@ import jscl.text.DoubleParser;
import jscl.text.JsclIntegerParser;
import jscl.text.ParseException;
import jscl.text.Parser;
import org.solovyev.android.calculator.math.MathType;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
public class NumberBuilder extends BaseNumberBuilder {
@ -178,7 +175,7 @@ public class NumberBuilder extends BaseNumberBuilder {
// let's get rid of unnecessary characters (grouping separators, + after E)
final List<String> tokens = new ArrayList<String>();
tokens.addAll(MathType.grouping_separator.getTokens());
tokens.addAll(MathType.grouping_separator.getTokens(engine));
// + after E can be omitted: 10+E = 10E (NOTE: - cannot be omitted )
tokens.add("+");
for (String groupingSeparator : tokens) {

View File

@ -22,11 +22,6 @@
package org.solovyev.android.calculator;
import static org.solovyev.android.Android.isPhoneModel;
import static org.solovyev.android.DeviceModel.samsung_galaxy_s;
import static org.solovyev.android.DeviceModel.samsung_galaxy_s_2;
import static org.solovyev.android.prefs.IntegerPreference.DEF_VALUE;
import android.app.Application;
import android.content.ContentResolver;
import android.content.Context;
@ -39,7 +34,8 @@ import android.support.annotation.LayoutRes;
import android.support.annotation.StyleRes;
import android.util.SparseArray;
import android.view.ContextThemeWrapper;
import jscl.AngleUnit;
import jscl.NumeralBase;
import org.solovyev.android.Check;
import org.solovyev.android.calculator.about.AboutActivity;
import org.solovyev.android.calculator.functions.FunctionsActivity;
@ -50,22 +46,19 @@ import org.solovyev.android.calculator.operators.OperatorsActivity;
import org.solovyev.android.calculator.preferences.PreferencesActivity;
import org.solovyev.android.calculator.variables.VariablesActivity;
import org.solovyev.android.calculator.wizard.WizardActivity;
import org.solovyev.android.prefs.BooleanPreference;
import org.solovyev.android.prefs.IntegerPreference;
import org.solovyev.android.prefs.NumberToStringPreference;
import org.solovyev.android.prefs.Preference;
import org.solovyev.android.prefs.StringPreference;
import jscl.AngleUnit;
import jscl.NumeralBase;
import org.solovyev.android.prefs.*;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.text.DecimalFormatSymbols;
import java.util.EnumMap;
import java.util.Locale;
import java.util.Map;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import static org.solovyev.android.Android.isPhoneModel;
import static org.solovyev.android.DeviceModel.samsung_galaxy_s;
import static org.solovyev.android.DeviceModel.samsung_galaxy_s_2;
import static org.solovyev.android.prefs.IntegerPreference.DEF_VALUE;
public final class Preferences {

View File

@ -1,39 +0,0 @@
/*
* Copyright 2013 serso aka se.solovyev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Contact details
*
* Email: se.solovyev@gmail.com
* Site: http://se.solovyev.org
*/
package org.solovyev.android.calculator;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public class SystemErrorReporter implements ErrorReporter {
@Override
public void onException(@Nonnull Throwable e) {
e.printStackTrace(System.out);
}
@Override
public void onError(@Nullable String message) {
System.out.println(message);
}
}

View File

@ -41,29 +41,32 @@ public class ToJsclTextProcessor implements TextProcessor<PreparedExpression, St
@Nonnull
private static final Integer MAX_DEPTH = 20;
@Inject
Engine engine;
@Inject
public ToJsclTextProcessor() {
}
private static PreparedExpression processWithDepth(@Nonnull String s, int depth, @Nonnull List<IConstant> undefinedVars) throws ParseException {
return replaceVariables(processExpression(s).toString(), depth, undefinedVars);
private static PreparedExpression processWithDepth(@Nonnull String s, int depth, @Nonnull List<IConstant> undefinedVars, @Nonnull Engine engine) throws ParseException {
return replaceVariables(processExpression(s, engine).toString(), depth, undefinedVars, engine);
}
@Nonnull
private static StringBuilder processExpression(@Nonnull String s) throws ParseException {
private static StringBuilder processExpression(@Nonnull String s, @Nonnull Engine engine) throws ParseException {
final StringBuilder result = new StringBuilder();
final MathType.Results results = new MathType.Results();
MathType.Result mathTypeResult = null;
MathType.Result mathTypeBefore = null;
final LiteNumberBuilder nb = new LiteNumberBuilder(Locator.getInstance().getEngine());
final LiteNumberBuilder nb = new LiteNumberBuilder(engine);
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ' ') continue;
results.release(mathTypeBefore);
mathTypeBefore = mathTypeResult == null ? null : mathTypeResult;
mathTypeResult = MathType.getType(s, i, nb.isHexMode(), results.obtain());
mathTypeResult = MathType.getType(s, i, nb.isHexMode(), engine);
nb.process(mathTypeResult);
@ -80,7 +83,7 @@ public class ToJsclTextProcessor implements TextProcessor<PreparedExpression, St
(mathTypeBefore.type == MathType.function || mathTypeBefore.type == MathType.operator) &&
App.find(MathType.groupSymbols, s, i) != null) {
final String functionName = mathTypeBefore.match;
final Function function = Locator.getInstance().getEngine().getFunctionsRegistry().get(functionName);
final Function function = engine.getFunctionsRegistry().get(functionName);
if (function == null || function.getMinParameters() > 0) {
throw new ParseException(i, s, new CalculatorMessage(CalculatorMessages.msg_005, MessageType.error, mathTypeBefore.match));
}
@ -92,7 +95,7 @@ public class ToJsclTextProcessor implements TextProcessor<PreparedExpression, St
}
@Nonnull
private static PreparedExpression replaceVariables(@Nonnull final String s, int depth, @Nonnull List<IConstant> undefinedVars) throws ParseException {
private static PreparedExpression replaceVariables(@Nonnull final String s, int depth, @Nonnull List<IConstant> undefinedVars, @Nonnull Engine engine) throws ParseException {
if (depth >= MAX_DEPTH) {
throw new ParseException(s, new CalculatorMessage(CalculatorMessages.msg_006, MessageType.error));
} else {
@ -106,13 +109,13 @@ public class ToJsclTextProcessor implements TextProcessor<PreparedExpression, St
startsWithFinder.setI(i);
int offset = 0;
String functionName = App.find(MathType.function.getTokens(), startsWithFinder);
String functionName = App.find(MathType.function.getTokens(engine), startsWithFinder);
if (functionName == null) {
String operatorName = App.find(MathType.operator.getTokens(), startsWithFinder);
String operatorName = App.find(MathType.operator.getTokens(engine), startsWithFinder);
if (operatorName == null) {
String varName = App.find(Locator.getInstance().getEngine().getVariablesRegistry().getNames(), startsWithFinder);
String varName = App.find(engine.getVariablesRegistry().getNames(), startsWithFinder);
if (varName != null) {
final IConstant var = Locator.getInstance().getEngine().getVariablesRegistry().get(varName);
final IConstant var = engine.getVariablesRegistry().get(varName);
if (var != null) {
if (!var.isDefined()) {
undefinedVars.add(var);
@ -127,7 +130,7 @@ public class ToJsclTextProcessor implements TextProcessor<PreparedExpression, St
// NOTE: append varName as JSCL engine will convert it to double if needed
result.append(varName);
} else {
result.append("(").append(processWithDepth(value, depth, undefinedVars)).append(")");
result.append("(").append(processWithDepth(value, depth, undefinedVars, engine)).append(")");
}
offset = varName.length();
}
@ -156,6 +159,6 @@ public class ToJsclTextProcessor implements TextProcessor<PreparedExpression, St
@Override
@Nonnull
public PreparedExpression process(@Nonnull String s) throws ParseException {
return processWithDepth(s, 0, new ArrayList<IConstant>());
return processWithDepth(s, 0, new ArrayList<IConstant>(), engine);
}
}

View File

@ -23,9 +23,11 @@
package org.solovyev.android.calculator.jscl;
import android.support.annotation.Nullable;
import jscl.MathEngine;
import jscl.math.Generic;
import jscl.text.ParseException;
import org.solovyev.android.calculator.Engine;
import org.solovyev.android.calculator.text.DummyTextProcessor;
import org.solovyev.android.calculator.text.FromJsclSimplifyTextProcessor;
import org.solovyev.android.calculator.text.TextProcessor;
@ -34,26 +36,44 @@ import javax.annotation.Nonnull;
public enum JsclOperation {
simplify,
elementary,
numeric;
simplify {
@Nonnull
@Override
TextProcessor<String, Generic> makeFromProcessor(@Nonnull Engine engine) {
return new FromJsclSimplifyTextProcessor(engine);
}
},
elementary {
@Nonnull
@Override
TextProcessor<String, Generic> makeFromProcessor(@Nonnull Engine engine) {
return DummyTextProcessor.instance;
}
},
numeric {
@Nonnull
@Override
TextProcessor<String, Generic> makeFromProcessor(@Nonnull Engine engine) {
return FromJsclNumericTextProcessor.instance;
}
};
@Nullable
TextProcessor<String, Generic> fromProcessor;
JsclOperation() {
}
@Nonnull
abstract TextProcessor<String, Generic> makeFromProcessor(@Nonnull Engine engine);
@Nonnull
public TextProcessor<String, Generic> getFromProcessor() {
switch (this) {
case simplify:
return FromJsclSimplifyTextProcessor.instance;
case elementary:
return DummyTextProcessor.instance;
case numeric:
return FromJsclNumericTextProcessor.instance;
default:
throw new UnsupportedOperationException();
public TextProcessor<String, Generic> getFromProcessor(@Nonnull Engine engine) {
if (fromProcessor == null) {
fromProcessor = makeFromProcessor(engine);
}
return fromProcessor;
}
@Nonnull

View File

@ -22,11 +22,13 @@
package org.solovyev.android.calculator.math;
import android.support.annotation.NonNull;
import jscl.JsclMathEngine;
import jscl.NumeralBase;
import jscl.math.function.Constants;
import org.solovyev.android.Check;
import org.solovyev.android.calculator.App;
import org.solovyev.android.calculator.Locator;
import org.solovyev.android.calculator.Engine;
import org.solovyev.android.calculator.ParseException;
import javax.annotation.Nonnull;
@ -39,20 +41,12 @@ import java.util.List;
public enum MathType {
numeral_base(50, true, false, MathGroupType.number) {
private final List<String> tokens = new ArrayList<>(10);
numeral_base(50, true, false, MathGroupType.number, new ArrayList<String>()) {
{
for (NumeralBase numeralBase : NumeralBase.values()) {
tokens.add(numeralBase.getJsclPrefix());
}
}
@Nonnull
@Override
public List<String> getTokens() {
return tokens;
}
},
dot(200, true, true, MathGroupType.number, ".") {
@ -74,8 +68,8 @@ public enum MathType {
postfix_function(400, false, true, MathGroupType.function) {
@Nonnull
@Override
public List<String> getTokens() {
return Locator.getInstance().getEngine().getPostfixFunctionsRegistry().getNames();
public List<String> getTokens(@NonNull Engine engine) {
return engine.getPostfixFunctionsRegistry().getNames();
}
},
@ -151,26 +145,47 @@ public enum MathType {
},
function(1000, true, true, MathGroupType.function) {
@Nonnull
@Override
public List<String> getTokens(@NonNull Engine engine) {
return engine.getFunctionsRegistry().getNames();
}
@Nonnull
@Override
public List<String> getTokens() {
return Locator.getInstance().getEngine().getFunctionsRegistry().getNames();
Check.shouldNotHappen();
return super.getTokens();
}
},
operator(1050, true, true, MathGroupType.function) {
@Nonnull
@Override
public List<String> getTokens(@NonNull Engine engine) {
return engine.getOperatorsRegistry().getNames();
}
@Nonnull
@Override
public List<String> getTokens() {
return Locator.getInstance().getEngine().getOperatorsRegistry().getNames();
Check.shouldNotHappen();
return super.getTokens();
}
},
constant(1100, true, true, MathGroupType.other) {
@Nonnull
@Override
public List<String> getTokens(@NonNull Engine engine) {
return engine.getVariablesRegistry().getNames();
}
@Nonnull
@Override
public List<String> getTokens() {
return Locator.getInstance().getEngine().getVariablesRegistry().getNames();
Check.shouldNotHappen();
return super.getTokens();
}
@Override
@ -179,9 +194,7 @@ public enum MathType {
}
},
digit(1125, true, true, MathGroupType.number) {
private final List<String> tokens = new ArrayList<>(16);
digit(1125, true, true, MathGroupType.number, new ArrayList<String>()) {
{
for (Character character : NumeralBase.hex.getAcceptableCharacters()) {
tokens.add(character.toString());
@ -192,12 +205,6 @@ public enum MathType {
public boolean isNeedMultiplicationSignBefore(@Nonnull MathType mathTypeBefore) {
return super.isNeedMultiplicationSignBefore(mathTypeBefore) && mathTypeBefore != digit && mathTypeBefore != dot /*&& mathTypeBefore != numeral_base*/;
}
@Nonnull
@Override
public List<String> getTokens() {
return tokens;
}
},
comma(1150, false, false, MathGroupType.other, ","),
@ -222,7 +229,7 @@ public enum MathType {
public final static String INFINITY_JSCL = "Infinity";
private static List<MathType> mathTypesByPriority;
@Nonnull
private final List<String> tokens;
protected final List<String> tokens;
@Nonnull
private final Integer priority;
private final boolean needMultiplicationSignBefore;
@ -246,7 +253,7 @@ public enum MathType {
this.needMultiplicationSignBefore = needMultiplicationSignBefore;
this.needMultiplicationSignAfter = needMultiplicationSignAfter;
this.groupType = groupType;
this.tokens = java.util.Collections.unmodifiableList(tokens);
this.tokens = tokens;
}
/**
@ -255,15 +262,16 @@ public enum MathType {
* @param text analyzed text
* @param i index which points to start of substring
* @param hexMode true if current mode if HEX
* @param engine math engine
* @return math entity type of substring starting from ith index of specified text
*/
@Nonnull
public static Result getType(@Nonnull String text, int i, boolean hexMode) {
return getType(text, i, hexMode, new Result());
public static Result getType(@Nonnull String text, int i, boolean hexMode, @Nonnull Engine engine) {
return getType(text, i, hexMode, new Result(), engine);
}
@Nonnull
public static Result getType(@Nonnull String text, int i, boolean hexMode, @Nonnull Result result) {
public static Result getType(@Nonnull String text, int i, boolean hexMode, @Nonnull Result result, @Nonnull Engine engine) {
if (i < 0) {
throw new IllegalArgumentException("I must be more or equals to 0.");
} else if (i >= text.length() && i != 0) {
@ -274,7 +282,7 @@ public enum MathType {
final List<MathType> mathTypes = getMathTypesByPriority();
for (int j = 0; j < mathTypes.size(); j++) {
final MathType mathType = mathTypes.get(j);
final String s = App.find(mathType.getTokens(), text, i);
final String s = App.find(mathType.getTokens(engine), text, i);
if (s == null) {
continue;
}
@ -304,7 +312,7 @@ public enum MathType {
}
if (mathType == MathType.grouping_separator) {
if (i + 1 < text.length() && getType(text, i + 1, hexMode, result).type == MathType.digit) {
if (i + 1 < text.length() && getType(text, i + 1, hexMode, result, engine).type == MathType.digit) {
return result.set(mathType, s);
}
continue;
@ -339,6 +347,11 @@ public enum MathType {
return groupType;
}
@Nonnull
public List<String> getTokens(@Nonnull Engine engine) {
return getTokens();
}
@Nonnull
public List<String> getTokens() {
return tokens;
@ -400,7 +413,8 @@ public enum MathType {
public String match;
public Result(@Nonnull MathType type, @Nonnull String match) {
set(type, match);
this.type = type;
this.match = match;
}
@Nonnull
@ -411,6 +425,7 @@ public enum MathType {
}
public Result() {
this(MathType.text, "");
}
public int processToJscl(@Nonnull StringBuilder result, int i) throws ParseException {

View File

@ -23,7 +23,7 @@
package org.solovyev.android.calculator.text;
import jscl.math.Generic;
import org.solovyev.android.calculator.Locator;
import org.solovyev.android.calculator.Engine;
import org.solovyev.android.calculator.math.MathType;
import javax.annotation.Nonnull;
@ -33,10 +33,13 @@ import java.util.List;
public class FromJsclSimplifyTextProcessor implements TextProcessor<String, Generic> {
public static final FromJsclSimplifyTextProcessor instance = new FromJsclSimplifyTextProcessor();
private final List<MathType> mathTypes = Arrays.asList(MathType.function, MathType.constant);
public FromJsclSimplifyTextProcessor() {
@Nonnull
private final Engine engine;
public FromJsclSimplifyTextProcessor(@Nonnull Engine engine) {
this.engine = engine;
}
@Nonnull
@ -63,7 +66,7 @@ public class FromJsclSimplifyTextProcessor implements TextProcessor<String, Gene
mathTypeBefore = mathType;
if (mathTypeAfter == null) {
mathType = MathType.getType(s, i, false, results.obtain());
mathType = MathType.getType(s, i, false, results.obtain(), engine);
} else {
mathType = mathTypeAfter;
}
@ -71,13 +74,13 @@ public class FromJsclSimplifyTextProcessor implements TextProcessor<String, Gene
char ch = s.charAt(i);
if (ch == '*') {
if (i + 1 < s.length()) {
mathTypeAfter = MathType.getType(s, i + 1, false, results.obtain());
mathTypeAfter = MathType.getType(s, i + 1, false, results.obtain(), engine);
} else {
mathTypeAfter = null;
}
if (needMultiplicationSign(mathTypeBefore == null ? null : mathTypeBefore.type, mathTypeAfter == null ? null : mathTypeAfter.type)) {
sb.append(Locator.getInstance().getEngine().getMultiplicationSign());
sb.append(engine.getMultiplicationSign());
}
} else {

View File

@ -99,6 +99,8 @@ public class EditVariableFragment extends BaseDialogFragment implements View.OnF
VariablesRegistry variablesRegistry;
@Inject
Lazy<ToJsclTextProcessor> toJsclTextProcessor;
@Inject
Engine engine;
@Nullable
private CppVariable variable;
@ -275,7 +277,7 @@ public class EditVariableFragment extends BaseDialogFragment implements View.OnF
}
}
final MathType.Result type = MathType.getType(name, 0, false);
final MathType.Result type = MathType.getType(name, 0, false, engine);
if (type.type != MathType.text && type.type != MathType.constant) {
setError(nameLabel, getString(R.string.c_var_name_clashes));
return false;

View File

@ -22,9 +22,12 @@ public final class EditorTextProcessor implements TextProcessor<TextProcessorEdi
@Nullable
private TextHighlighter textHighlighter;
@Nonnull
private final SharedPreferences preferences;
@Nonnull
private final Engine engine;
public EditorTextProcessor(@Nonnull SharedPreferences preferences, @Nonnull Engine engine) {
this.preferences = preferences;
this.engine = engine;
preferences.registerOnSharedPreferenceChangeListener(this);
onSharedPreferenceChanged(preferences, colorDisplay.getKey());
@ -43,7 +46,7 @@ public final class EditorTextProcessor implements TextProcessor<TextProcessorEdi
@Nonnull
private TextHighlighter getTextHighlighter() {
if (textHighlighter == null) {
onSharedPreferenceChanged(App.getPreferences(), theme.getKey());
onSharedPreferenceChanged(preferences, theme.getKey());
}
return textHighlighter;
}

View File

@ -89,7 +89,7 @@ public class TextHighlighter implements TextProcessor<TextProcessorEditorResult,
int openGroupsCount = 0;
for (int i = 0; i < text.length(); i++) {
MathType.getType(text, i, nb.isHexMode(), result);
MathType.getType(text, i, nb.isHexMode(), result, engine);
offset += nb.process(sb, result);

View File

@ -1,46 +0,0 @@
/*
* Copyright 2013 serso aka se.solovyev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Contact details
*
* Email: se.solovyev@gmail.com
* Site: http://se.solovyev.org
*/
package org.solovyev.android.calculator;
import java.util.concurrent.Executor;
import static org.mockito.Mockito.mock;
/**
* User: serso
* Date: 10/7/12
* Time: 6:30 PM
*/
public class AbstractCalculatorTest {
protected void setUp() throws Exception {
Locator.getInstance().init(CalculatorTestUtils.newCalculatorEngine());
Locator.getInstance().getEngine().init(new Executor() {
@Override
public void execute(Runnable command) {
command.run();
}
});
}
}

View File

@ -23,10 +23,7 @@
package org.solovyev.android.calculator;
import android.os.Build;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricGradleTestRunner;
@ -40,27 +37,10 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* User: serso
* Date: 10/13/12
* Time: 1:11 PM
*/
@Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.LOLLIPOP)
@RunWith(value = RobolectricGradleTestRunner.class)
public class AndroidEditorViewTest {
@BeforeClass
public static void staticSetUp() throws Exception {
/*CalculatorTestUtils.staticSetUp(null);*/
}
@Before
public void setUp() throws Exception {
/* CalculatorActivity context = new CalculatorActivity();
CalculatorTestUtils.initViews(context);*/
}
@Test
public void testCreation() throws Exception {
new EditorView(RuntimeEnvironment.application);

View File

@ -0,0 +1,103 @@
package org.solovyev.android.calculator;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import com.squareup.otto.Bus;
import jscl.JsclMathEngine;
import org.hamcrest.Description;
import org.junit.Before;
import org.mockito.ArgumentMatcher;
import org.solovyev.android.calculator.calculations.CalculationFailedEvent;
import org.solovyev.android.calculator.calculations.CalculationFinishedEvent;
import org.solovyev.android.calculator.functions.FunctionsRegistry;
import org.solovyev.android.calculator.jscl.JsclOperation;
import org.solovyev.android.calculator.operators.OperatorsRegistry;
import org.solovyev.android.calculator.operators.PostfixFunctionsRegistry;
import static org.mockito.Matchers.argThat;
import static org.mockito.Mockito.*;
import static org.solovyev.android.calculator.jscl.JsclOperation.numeric;
public abstract class BaseCalculatorTest {
protected Calculator calculator;
protected Bus bus;
protected Engine engine;
@Before
public void setUp() throws Exception {
bus = mock(Bus.class);
calculator = new Calculator(mock(SharedPreferences.class), bus, Tests.sameThreadExecutor());
final JsclMathEngine mathEngine = JsclMathEngine.getInstance();
engine = new Engine(mathEngine);
engine.postfixFunctionsRegistry = new PostfixFunctionsRegistry(mathEngine);
engine.functionsRegistry = new FunctionsRegistry(mathEngine);
engine.variablesRegistry = new VariablesRegistry(mathEngine);
engine.variablesRegistry.bus = bus;
engine.operatorsRegistry = new OperatorsRegistry(mathEngine);
calculator.engine = engine;
calculator.preferredPreferences = mock(PreferredPreferences.class);
final ToJsclTextProcessor processor = new ToJsclTextProcessor();
processor.engine = engine;
calculator.preprocessor = processor;
}
protected final void assertError(@NonNull String expression) {
calculator.evaluate(numeric, expression);
verify(calculator.bus, atLeastOnce()).post(argThat(failed()));
}
@NonNull
private static ArgumentMatcher<CalculationFailedEvent> failed() {
return new ArgumentMatcher<CalculationFailedEvent>() {
@Override
public boolean matches(Object o) {
if (!(o instanceof CalculationFailedEvent)) {
return false;
}
final CalculationFailedEvent e = (CalculationFailedEvent) o;
return e.operation == numeric;
}
};
}
protected final void assertEval(@NonNull String expected, @NonNull String expression) {
assertEval(expected, expression, numeric);
}
protected final void assertEval(@NonNull final String expected, @NonNull final String expression, final JsclOperation operation) {
calculator.evaluate(operation, expression);
verify(calculator.bus, atLeastOnce()).post(finishedEvent(expected, expression, operation));
}
protected static CalculationFinishedEvent finishedEvent(@NonNull String expected, @NonNull String expression, JsclOperation operation) {
return argThat(finished(expected, expression, operation));
}
protected static CalculationFinishedEvent anyFinishedEvent() {
return argThat(new ArgumentMatcher<CalculationFinishedEvent>() {
@Override
public boolean matches(Object o) {
return o instanceof CalculationFinishedEvent;
}
});
}
@NonNull
protected static ArgumentMatcher<CalculationFinishedEvent> finished(@NonNull final String expected, @NonNull final String expression, final JsclOperation operation) {
return new ArgumentMatcher<CalculationFinishedEvent>() {
@Override
public boolean matches(Object o) {
if (!(o instanceof CalculationFinishedEvent)) {
return false;
}
final CalculationFinishedEvent e = (CalculationFinishedEvent) o;
return e.operation == operation && e.expression.equals(expression) && e.stringResult.equals(expected);
}
@Override
public void describeTo(Description description) {
description.appendText(expected);
}
};
}
}

View File

@ -24,30 +24,42 @@ package org.solovyev.android.calculator;
import org.junit.Before;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.solovyev.android.calculator.calculations.CalculationFinishedEvent;
/**
* User: Solovyev_S
* Date: 15.10.12
* Time: 12:30
*/
public class CalculatorTest extends AbstractCalculatorTest {
import static org.mockito.Mockito.doAnswer;
public class CalculatorTest extends BaseCalculatorTest {
@Override
@Before
public void setUp() throws Exception {
super.setUp();
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
final Object[] args = invocationOnMock.getArguments();
final CalculationFinishedEvent e = (CalculationFinishedEvent) args[0];
calculator.updateAnsVariable(e.stringResult);
return null;
}
}).when(bus).post(anyFinishedEvent());
}
@Test
public void testAnsVariable() throws Exception {
CalculatorTestUtils.assertEval("2", "2");
CalculatorTestUtils.assertEval("2", "ans");
CalculatorTestUtils.assertEval("4", "ans^2");
CalculatorTestUtils.assertEval("16", "ans^2");
CalculatorTestUtils.assertEval("0", "0");
CalculatorTestUtils.assertEval("0", "ans");
CalculatorTestUtils.assertEval("3", "3");
CalculatorTestUtils.assertEval("9", "ans*ans");
CalculatorTestUtils.assertError("ans*an");
CalculatorTestUtils.assertEval("81", "ans*ans");
assertEval("2", "2");
assertEval("2", "2");
assertEval("2", "ans");
assertEval("4", "ans^2");
assertEval("16", "ans^2");
assertEval("0", "0");
assertEval("0", "ans");
assertEval("3", "3");
assertEval("9", "ans*ans");
assertError("ans*an");
assertEval("81", "ans*ans");
}
}

View File

@ -1,248 +0,0 @@
/*
* Copyright 2013 serso aka se.solovyev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Contact details
*
* Email: se.solovyev@gmail.com
* Site: http://se.solovyev.org
*/
package org.solovyev.android.calculator;
import static org.mockito.Mockito.mock;
import android.content.Context;
import org.junit.Assert;
import org.robolectric.fakes.RoboSharedPreferences;
import org.solovyev.android.calculator.functions.FunctionsRegistry;
import org.solovyev.android.calculator.jscl.JsclOperation;
import org.solovyev.android.calculator.language.Languages;
import org.solovyev.android.calculator.operators.OperatorsRegistry;
import org.solovyev.android.calculator.operators.PostfixFunctionsRegistry;
import jscl.JsclMathEngine;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.text.DecimalFormatSymbols;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* User: serso
* Date: 10/7/12
* Time: 8:40 PM
*/
public class CalculatorTestUtils {
// in seconds
public static final int TIMEOUT = 3;
public static void staticSetUp() throws Exception {
App.init(new CalculatorApplication(), new Languages(new RoboSharedPreferences(new HashMap<String, Map<String, Object>>(), "test", 0)));
Locator.getInstance().init(newCalculatorEngine());
Locator.getInstance().getEngine().init(new Executor() {
@Override
public void execute(Runnable command) {
command.run();
}
});
final DecimalFormatSymbols decimalGroupSymbols = new DecimalFormatSymbols();
decimalGroupSymbols.setDecimalSeparator('.');
decimalGroupSymbols.setGroupingSeparator(' ');
Locator.getInstance().getEngine().getMathEngine().setDecimalGroupSymbols(decimalGroupSymbols);
}
public static void staticSetUp(@Nullable Context context) throws Exception {
Locator.getInstance().init(newCalculatorEngine());
Locator.getInstance().getEngine().init(new Executor() {
@Override
public void execute(Runnable command) {
command.run();
}
});
if (context != null) {
initViews(context);
}
}
public static void initViews(@Nonnull Context context) {
App.getEditor().setView(new EditorView(context));
App.getDisplay().setView(new DisplayView(context));
}
@Nonnull
static Engine newCalculatorEngine() {
final JsclMathEngine jsclEngine = JsclMathEngine.getInstance();
final VariablesRegistry variablesRegistry = new VariablesRegistry(jsclEngine);
final FunctionsRegistry functionsRegistry = new FunctionsRegistry(jsclEngine);
final OperatorsRegistry operatorsRegistry = new OperatorsRegistry(jsclEngine);
final PostfixFunctionsRegistry postfixFunctionsRegistry = new PostfixFunctionsRegistry(jsclEngine);
return new Engine(jsclEngine, variablesRegistry, functionsRegistry, operatorsRegistry, postfixFunctionsRegistry);
}
public static void assertEval(@Nonnull String expected, @Nonnull String expression) {
assertEval(expected, expression, JsclOperation.numeric);
}
public static void assertEval(@Nonnull String expected, @Nonnull String expression, @Nonnull JsclOperation operation) {
final Calculator calculator = Locator.getInstance().getCalculator();
App.getDisplay().setState(DisplayState.empty());
final CountDownLatch latch = new CountDownLatch(1);
final TestCalculatorEventListener calculatorEventListener = new TestCalculatorEventListener(latch);
try {
calculator.addCalculatorEventListener(calculatorEventListener);
//calculatorEventListener.setCalculatorEventData(calculator.evaluate(operation, expression));
if (latch.await(TIMEOUT, TimeUnit.SECONDS)) {
Assert.assertNotNull(calculatorEventListener.getResult());
Assert.assertEquals(expected, calculatorEventListener.getResult().text);
} else {
Assert.fail("Too long wait for: " + expression);
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
calculator.removeCalculatorEventListener(calculatorEventListener);
}
}
public static void assertError(@Nonnull String expression) {
assertError(expression, JsclOperation.numeric);
}
public static <S extends Serializable> S testSerialization(@Nonnull S serializable) throws IOException, ClassNotFoundException {
final ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(out);
oos.writeObject(serializable);
} finally {
if (oos != null) {
oos.close();
}
}
byte[] serialized = out.toByteArray();
Assert.assertTrue(serialized.length > 0);
final ObjectInputStream resultStream = new ObjectInputStream(new ByteArrayInputStream(out.toByteArray()));
final S result = (S) resultStream.readObject();
Assert.assertNotNull(result);
return result;
}
public static void assertError(@Nonnull String expression, @Nonnull JsclOperation operation) {
final Calculator calculator = Locator.getInstance().getCalculator();
App.getDisplay().setState(DisplayState.empty());
final CountDownLatch latch = new CountDownLatch(1);
final TestCalculatorEventListener calculatorEventListener = new TestCalculatorEventListener(latch);
try {
calculator.addCalculatorEventListener(calculatorEventListener);
//calculatorEventListener.setCalculatorEventData(calculator.evaluate(operation, expression));
if (latch.await(TIMEOUT, TimeUnit.SECONDS)) {
Assert.assertNotNull(calculatorEventListener.getResult());
Assert.assertFalse(calculatorEventListener.getResult().valid);
} else {
Assert.fail("Too long wait for: " + expression);
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
calculator.removeCalculatorEventListener(calculatorEventListener);
}
}
private static final class TestCalculatorEventListener implements CalculatorEventListener {
@Nonnull
private final CountDownLatch latch;
@Nullable
private CalculatorEventData calculatorEventData;
@Nullable
private volatile DisplayState result = null;
public TestCalculatorEventListener(@Nonnull CountDownLatch latch) {
this.latch = latch;
}
public void setCalculatorEventData(@Nullable CalculatorEventData calculatorEventData) {
this.calculatorEventData = calculatorEventData;
}
@Override
public void onCalculatorEvent(@Nonnull CalculatorEventData calculatorEventData, @Nonnull CalculatorEventType calculatorEventType, @Nullable Object data) {
waitForEventData();
if (calculatorEventData.isSameSequence(this.calculatorEventData)) {
/*if (calculatorEventType == CalculatorEventType.display_state_changed) {
final Display.ChangedEvent displayChange = (Display.ChangedEvent) data;
result = displayChange.newState;
try {
// need to sleep a little bit as await
new CountDownLatch(1).await(100, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
}
latch.countDown();
}*/
}
}
private void waitForEventData() {
while (this.calculatorEventData == null) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
}
}
}
@Nullable
public DisplayState getResult() {
return result;
}
}
}

View File

@ -22,211 +22,203 @@
package org.solovyev.android.calculator;
import android.preference.PreferenceManager;
import android.content.SharedPreferences;
import jscl.JsclMathEngine;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.robolectric.RuntimeEnvironment;
import org.mockito.Mockito;
import javax.annotation.Nonnull;
public class EditorTest {
/**
* User: Solovyev_S
* Date: 21.09.12
* Time: 12:44
*/
public class EditorTest extends AbstractCalculatorTest {
@Nonnull
private Editor editor;
@Before
public void setUp() throws Exception {
super.setUp();
this.editor = new Editor(PreferenceManager.getDefaultSharedPreferences(RuntimeEnvironment.application));
this.editor = new Editor(Mockito.mock(SharedPreferences.class), new Engine(new JsclMathEngine()));
}
@Test
public void testInsert() throws Exception {
EditorState viewState = this.editor.getState();
EditorState viewState = editor.getState();
Assert.assertEquals("", viewState.getTextString());
Assert.assertEquals(0, viewState.selection);
viewState = this.editor.insert("");
viewState = editor.insert("");
Assert.assertEquals("", viewState.getTextString());
Assert.assertEquals(0, viewState.selection);
viewState = this.editor.insert("test");
viewState = editor.insert("test");
Assert.assertEquals("test", viewState.getTextString());
Assert.assertEquals(4, viewState.selection);
viewState = this.editor.insert("test");
viewState = editor.insert("test");
Assert.assertEquals("testtest", viewState.getTextString());
Assert.assertEquals(8, viewState.selection);
viewState = this.editor.insert("");
viewState = editor.insert("");
Assert.assertEquals("testtest", viewState.getTextString());
Assert.assertEquals(8, viewState.selection);
viewState = this.editor.insert("1234567890");
viewState = editor.insert("1234567890");
Assert.assertEquals("testtest1234567890", viewState.getTextString());
Assert.assertEquals(18, viewState.selection);
viewState = this.editor.moveCursorLeft();
viewState = this.editor.insert("9");
editor.moveCursorLeft();
viewState = editor.insert("9");
Assert.assertEquals("testtest12345678990", viewState.getTextString());
Assert.assertEquals(18, viewState.selection);
viewState = this.editor.setCursorOnStart();
viewState = this.editor.insert("9");
editor.setCursorOnStart();
viewState = editor.insert("9");
Assert.assertEquals("9testtest12345678990", viewState.getTextString());
Assert.assertEquals(1, viewState.selection);
viewState = this.editor.erase();
viewState = this.editor.insert("9");
editor.erase();
viewState = editor.insert("9");
Assert.assertEquals("9testtest12345678990", viewState.getTextString());
Assert.assertEquals(1, viewState.selection);
viewState = this.editor.insert("öäü");
viewState = editor.insert("öäü");
Assert.assertEquals("9öäütesttest12345678990", viewState.getTextString());
this.editor.setCursorOnEnd();
viewState = this.editor.insert("öäü");
editor.setCursorOnEnd();
viewState = editor.insert("öäü");
Assert.assertEquals("9öäütesttest12345678990öäü", viewState.getTextString());
}
@Test
public void testErase() throws Exception {
this.editor.setText("");
this.editor.erase();
editor.setText("");
editor.erase();
Assert.assertEquals("", this.editor.getState().getTextString());
Assert.assertEquals("", editor.getState().getTextString());
this.editor.setText("test");
this.editor.erase();
Assert.assertEquals("tes", this.editor.getState().getTextString());
editor.setText("test");
editor.erase();
Assert.assertEquals("tes", editor.getState().getTextString());
this.editor.erase();
Assert.assertEquals("te", this.editor.getState().getTextString());
editor.erase();
Assert.assertEquals("te", editor.getState().getTextString());
this.editor.erase();
Assert.assertEquals("t", this.editor.getState().getTextString());
editor.erase();
Assert.assertEquals("t", editor.getState().getTextString());
this.editor.erase();
Assert.assertEquals("", this.editor.getState().getTextString());
editor.erase();
Assert.assertEquals("", editor.getState().getTextString());
this.editor.erase();
Assert.assertEquals("", this.editor.getState().getTextString());
editor.erase();
Assert.assertEquals("", editor.getState().getTextString());
this.editor.setText("1234");
this.editor.moveCursorLeft();
this.editor.erase();
Assert.assertEquals("124", this.editor.getState().getTextString());
editor.setText("1234");
editor.moveCursorLeft();
editor.erase();
Assert.assertEquals("124", editor.getState().getTextString());
this.editor.erase();
Assert.assertEquals("14", this.editor.getState().getTextString());
editor.erase();
Assert.assertEquals("14", editor.getState().getTextString());
this.editor.erase();
Assert.assertEquals("4", this.editor.getState().getTextString());
editor.erase();
Assert.assertEquals("4", editor.getState().getTextString());
this.editor.setText("1");
this.editor.moveCursorLeft();
this.editor.erase();
Assert.assertEquals("1", this.editor.getState().getTextString());
editor.setText("1");
editor.moveCursorLeft();
editor.erase();
Assert.assertEquals("1", editor.getState().getTextString());
}
@Test
public void testMoveSelection() throws Exception {
this.editor.setText("");
editor.setText("");
EditorState viewState = this.editor.moveSelection(0);
EditorState viewState = editor.moveSelection(0);
Assert.assertEquals(0, viewState.selection);
viewState = this.editor.moveSelection(2);
viewState = editor.moveSelection(2);
Assert.assertEquals(0, viewState.selection);
viewState = this.editor.moveSelection(100);
viewState = editor.moveSelection(100);
Assert.assertEquals(0, viewState.selection);
viewState = this.editor.moveSelection(-3);
viewState = editor.moveSelection(-3);
Assert.assertEquals(0, viewState.selection);
viewState = this.editor.moveSelection(-100);
viewState = editor.moveSelection(-100);
Assert.assertEquals(0, viewState.selection);
viewState = this.editor.setText("0123456789");
editor.setText("0123456789");
viewState = this.editor.moveSelection(0);
viewState = editor.moveSelection(0);
Assert.assertEquals(10, viewState.selection);
viewState = this.editor.moveSelection(1);
viewState = editor.moveSelection(1);
Assert.assertEquals(10, viewState.selection);
viewState = this.editor.moveSelection(-2);
viewState = editor.moveSelection(-2);
Assert.assertEquals(8, viewState.selection);
viewState = this.editor.moveSelection(1);
viewState = editor.moveSelection(1);
Assert.assertEquals(9, viewState.selection);
viewState = this.editor.moveSelection(-9);
viewState = editor.moveSelection(-9);
Assert.assertEquals(0, viewState.selection);
viewState = this.editor.moveSelection(-10);
viewState = editor.moveSelection(-10);
Assert.assertEquals(0, viewState.selection);
viewState = this.editor.moveSelection(2);
viewState = editor.moveSelection(2);
Assert.assertEquals(2, viewState.selection);
viewState = this.editor.moveSelection(2);
viewState = editor.moveSelection(2);
Assert.assertEquals(4, viewState.selection);
viewState = this.editor.moveSelection(-6);
viewState = editor.moveSelection(-6);
Assert.assertEquals(0, viewState.selection);
}
@Test
public void testSetText() throws Exception {
EditorState viewState = this.editor.setText("test");
EditorState viewState = editor.setText("test");
Assert.assertEquals("test", viewState.getTextString());
Assert.assertEquals(4, viewState.selection);
viewState = this.editor.setText("testtest");
viewState = editor.setText("testtest");
Assert.assertEquals("testtest", viewState.getTextString());
Assert.assertEquals(8, viewState.selection);
viewState = this.editor.setText("");
viewState = editor.setText("");
Assert.assertEquals("", viewState.getTextString());
Assert.assertEquals(0, viewState.selection);
viewState = this.editor.setText("testtest", 0);
viewState = editor.setText("testtest", 0);
Assert.assertEquals("testtest", viewState.getTextString());
Assert.assertEquals(0, viewState.selection);
viewState = this.editor.setText("testtest", 2);
viewState = editor.setText("testtest", 2);
Assert.assertEquals("testtest", viewState.getTextString());
Assert.assertEquals(2, viewState.selection);
viewState = this.editor.setText("", 0);
viewState = editor.setText("", 0);
Assert.assertEquals("", viewState.getTextString());
Assert.assertEquals(0, viewState.selection);
viewState = this.editor.setText("", 3);
viewState = editor.setText("", 3);
Assert.assertEquals("", viewState.getTextString());
Assert.assertEquals(0, viewState.selection);
viewState = this.editor.setText("", -3);
viewState = editor.setText("", -3);
Assert.assertEquals("", viewState.getTextString());
Assert.assertEquals(0, viewState.selection);
viewState = this.editor.setText("test");
viewState = editor.setText("test");
Assert.assertEquals("test", viewState.getTextString());
Assert.assertEquals(4, viewState.selection);
viewState = this.editor.setText("", 2);
viewState = editor.setText("", 2);
Assert.assertEquals("", viewState.getTextString());
Assert.assertEquals(0, viewState.selection);
}

View File

@ -22,72 +22,64 @@
package org.solovyev.android.calculator;
import org.junit.Assert;
import org.junit.BeforeClass;
import jscl.JsclMathEngine;
import org.junit.Test;
import org.solovyev.android.calculator.text.FromJsclSimplifyTextProcessor;
import org.solovyev.android.calculator.variables.CppVariable;
import java.text.DecimalFormatSymbols;
/**
* User: serso
* Date: 10/20/11
* Time: 3:43 PM
*/
public class FromJsclSimplifyTextProcessorTest extends AbstractCalculatorTest {
import static org.junit.Assert.assertEquals;
@BeforeClass
public static void staticSetUp() throws Exception {
CalculatorTestUtils.staticSetUp();
}
public class FromJsclSimplifyTextProcessorTest {
@Test
public void testProcess() throws Exception {
FromJsclSimplifyTextProcessor tp = new FromJsclSimplifyTextProcessor();
final Engine engine = new Engine(new JsclMathEngine());
FromJsclSimplifyTextProcessor tp = new FromJsclSimplifyTextProcessor(engine);
//Assert.assertEquals("(e)", tp.process("(2.718281828459045)"));
//Assert.assertEquals("ee", tp.process("2.718281828459045*2.718281828459045"));
//Assert.assertEquals("((e)(e))", tp.process("((2.718281828459045)*(2.718281828459045))"));
DecimalFormatSymbols decimalGroupSymbols = new DecimalFormatSymbols();
decimalGroupSymbols.setGroupingSeparator(' ');
Locator.getInstance().getEngine().getMathEngine().setDecimalGroupSymbols(decimalGroupSymbols);
engine.getMathEngine().setDecimalGroupSymbols(decimalGroupSymbols);
//Assert.assertEquals("123 456 789e", tp.process("123456789*2.718281828459045"));
//Assert.assertEquals("123 456 789e", tp.process("123 456 789 * 2.718281828459045"));
//Assert.assertEquals("t11e", tp.process("t11*2.718281828459045"));
//Assert.assertEquals("e", tp.process("2.718281828459045"));
//Assert.assertEquals("tee", tp.process("t2.718281828459045*2.718281828459045"));
Locator.getInstance().getEngine().getVariablesRegistry().add(CppVariable.builder("t2.718281828459045", 2).build().toJsclBuilder());
Locator.getInstance().getEngine().getVariablesRegistry().add(CppVariable.builder("t").build().toJsclBuilder());
engine.getVariablesRegistry().add(CppVariable.builder("t2.718281828459045", 2).build().toJsclBuilder());
engine.getVariablesRegistry().add(CppVariable.builder("t").build().toJsclBuilder());
//Assert.assertEquals("t2.718281828459045e", tp.process("t2.718281828459045*2.718281828459045"));
//Assert.assertEquals("ee", tp.process("2.718281828459045*2.718281828459045"));
Assert.assertEquals("t×", tp.process("t*"));
Assert.assertEquals("×t", tp.process("*t"));
Assert.assertEquals("t2", tp.process("t*2"));
Assert.assertEquals("2t", tp.process("2*t"));
Locator.getInstance().getEngine().getVariablesRegistry().add(CppVariable.builder("t").build().toJsclBuilder());
Assert.assertEquals("t×", tp.process("t*"));
Assert.assertEquals("×t", tp.process("*t"));
assertEquals("t×", tp.process("t*"));
assertEquals("×t", tp.process("*t"));
assertEquals("t2", tp.process("t*2"));
assertEquals("2t", tp.process("2*t"));
engine.getVariablesRegistry().add(CppVariable.builder("t").build().toJsclBuilder());
assertEquals("t×", tp.process("t*"));
assertEquals("×t", tp.process("*t"));
Assert.assertEquals("t2", tp.process("t*2"));
Assert.assertEquals("2t", tp.process("2*t"));
assertEquals("t2", tp.process("t*2"));
assertEquals("2t", tp.process("2*t"));
Assert.assertEquals("t^2×2", tp.process("t^2*2"));
Assert.assertEquals("2t^2", tp.process("2*t^2"));
assertEquals("t^2×2", tp.process("t^2*2"));
assertEquals("2t^2", tp.process("2*t^2"));
Assert.assertEquals("t^[2×2t]", tp.process("t^[2*2*t]"));
Assert.assertEquals("2t^2[2t]", tp.process("2*t^2[2*t]"));
assertEquals("t^[2×2t]", tp.process("t^[2*2*t]"));
assertEquals("2t^2[2t]", tp.process("2*t^2[2*t]"));
Locator.getInstance().getEngine().getVariablesRegistry().add(CppVariable.builder("k").build().toJsclBuilder());
Assert.assertEquals("(t+2k)[k+2t]", tp.process("(t+2*k)*[k+2*t]"));
Assert.assertEquals("(te+2k)e[k+2te]", tp.process("(t*e+2*k)*e*[k+2*t*e]"));
engine.getVariablesRegistry().add(CppVariable.builder("k").build().toJsclBuilder());
assertEquals("(t+2k)[k+2t]", tp.process("(t+2*k)*[k+2*t]"));
assertEquals("(te+2k)e[k+2te]", tp.process("(t*e+2*k)*e*[k+2*t*e]"));
Assert.assertEquals("tlog(3)", tp.process("t*log(3)"));
Assert.assertEquals("t√(3)", tp.process("t*√(3)"));
Assert.assertEquals("20x", tp.process("20*x"));
Assert.assertEquals("20x", tp.process("20x"));
Assert.assertEquals("2×0x3", tp.process("2*0x3"));
Assert.assertEquals("2×0x:3", tp.process("2*0x:3"));
assertEquals("tlog(3)", tp.process("t*log(3)"));
assertEquals("t√(3)", tp.process("t*√(3)"));
assertEquals("20x", tp.process("20*x"));
assertEquals("20x", tp.process("20x"));
assertEquals("2×0x3", tp.process("2*0x3"));
assertEquals("2×0x:3", tp.process("2*0x:3"));
}
}

View File

@ -1,9 +1,17 @@
package org.solovyev.android.calculator;
import android.support.annotation.NonNull;
import org.solovyev.android.calculator.calculations.CalculationFailedEvent;
import org.solovyev.android.calculator.calculations.CalculationFinishedEvent;
import org.solovyev.common.msg.Message;
import java.util.ArrayList;
import java.util.concurrent.Executor;
import static org.mockito.Matchers.refEq;
import static org.mockito.Mockito.verify;
import static org.solovyev.android.calculator.jscl.JsclOperation.numeric;
public class Tests {
@NonNull
@ -15,4 +23,14 @@ public class Tests {
}
};
}
static void assertError(@NonNull Calculator calculator, @NonNull String expression) {
calculator.evaluate(numeric, expression);
verify(calculator.bus).post(refEq(new CalculationFailedEvent(numeric, expression, 0, new Exception()), "exception", "sequence"));
}
static void assertEval(@NonNull Calculator calculator, @NonNull String expression, @NonNull String expected) {
calculator.evaluate(numeric, expression);
verify(calculator.bus).post(refEq(new CalculationFinishedEvent(numeric, expression, 0, null, expected, new ArrayList<Message>()), "result", "sequence"));
}
}

View File

@ -23,6 +23,7 @@
package org.solovyev.android.calculator;
import android.graphics.Color;
import jscl.JsclMathEngine;
import jscl.MathEngine;
import jscl.NumeralBase;
import org.junit.Before;
@ -35,16 +36,13 @@ import java.util.Random;
import static org.junit.Assert.*;
/**
* User: serso
* Date: 10/12/11
* Time: 10:07 PM
*/
public class TextHighlighterTest {
private Engine engine;
@Before
public void setUp() throws Exception {
CalculatorTestUtils.staticSetUp();
engine = new Engine(new JsclMathEngine());
}
@Test
@ -115,7 +113,7 @@ public class TextHighlighterTest {
assertEquals("<b>0x:</b>FF33233FFE", textHighlighter.process("0x:FF33233FFE").toString());
assertEquals("<b>0x:</b>FF33 233 FFE", textHighlighter.process("0x:FF33 233 FFE").toString());
final MathEngine me = Locator.getInstance().getEngine().getMathEngine();
final MathEngine me = engine.getMathEngine();
try {
me.setNumeralBase(NumeralBase.hex);
assertEquals("E", textHighlighter.process("E").toString());

View File

@ -20,44 +20,31 @@
* Site: http://se.solovyev.org
*/
package org.solovyev.android.calculator.model;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.solovyev.android.calculator.AbstractCalculatorTest;
import org.solovyev.android.calculator.ParseException;
import org.solovyev.android.calculator.CalculatorTestUtils;
import org.solovyev.android.calculator.Locator;
import org.solovyev.android.calculator.PreparedExpression;
import org.solovyev.android.calculator.ToJsclTextProcessor;
import org.solovyev.android.calculator.text.TextProcessor;
package org.solovyev.android.calculator;
import jscl.JsclMathEngine;
import jscl.NumeralBase;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* User: serso
* Date: 9/26/11
* Time: 12:13 PM
*/
public class ToJsclTextProcessorTest extends AbstractCalculatorTest {
public class ToJsclTextProcessorTest {
@BeforeClass
public static void staticSetUp() throws Exception {
CalculatorTestUtils.staticSetUp();
private ToJsclTextProcessor preprocessor;
@Before
public void setUp() throws Exception {
preprocessor = new ToJsclTextProcessor();
preprocessor.engine = new Engine(new JsclMathEngine());
}
@Test
public void testSpecialCases() throws ParseException {
final TextProcessor<PreparedExpression, String> preprocessor = ToJsclTextProcessor.getInstance();
Assert.assertEquals("3^E10", preprocessor.process("3^E10").toString());
}
@Test
public void testProcess() throws Exception {
final TextProcessor<PreparedExpression, String> preprocessor = ToJsclTextProcessor.getInstance();
Assert.assertEquals("", preprocessor.process("").toString());
Assert.assertEquals("()", preprocessor.process("[]").toString());
Assert.assertEquals("()*()", preprocessor.process("[][]").toString());
@ -87,10 +74,10 @@ public class ToJsclTextProcessorTest extends AbstractCalculatorTest {
Assert.assertEquals("EE", preprocessor.process("EE").toString());
try {
Locator.getInstance().getEngine().getMathEngine().setNumeralBase(NumeralBase.hex);
preprocessor.engine.getMathEngine().setNumeralBase(NumeralBase.hex);
Assert.assertEquals("22F*exp(F)", preprocessor.process("22Fexp(F)").toString());
} finally {
Locator.getInstance().getEngine().getMathEngine().setNumeralBase(NumeralBase.dec);
preprocessor.engine.getMathEngine().setNumeralBase(NumeralBase.dec);
}
Assert.assertEquals("0x:ABCDEF", preprocessor.process("0x:ABCDEF").toString());
Assert.assertEquals("0x:ABCDEF", preprocessor.process("0x:A BC DEF").toString());
@ -108,30 +95,30 @@ public class ToJsclTextProcessorTest extends AbstractCalculatorTest {
try {
preprocessor.process("ln()");
Assert.fail();
} catch (ParseException e) {
} catch (ParseException ignored) {
}
try {
preprocessor.process("ln()ln()");
Assert.fail();
} catch (ParseException e) {
} catch (ParseException ignored) {
}
try {
preprocessor.process("eln()eln()ln()ln()ln()e");
Assert.fail();
} catch (ParseException e) {
} catch (ParseException ignored) {
}
try {
preprocessor.process("ln(ln(ln(ln(ln(ln(ln(ln(ln(ln(ln(ln(ln(ln(ln()))))))))))))))");
Assert.fail();
} catch (ParseException e) {
} catch (ParseException ignored) {
}
try {
preprocessor.process("cos(cos(cos(cos(acos(acos(acos(acos(acos(acos(acos(acos(cos(cos(cos(cos(cosh(acos(cos(cos(cos(cos(cos(acos(acos(acos(acos(acos(acos(acos(acos(cos(cos(cos(cos(cosh(acos(cos())))))))))))))))))))))))))))))))))))))");
Assert.fail();
} catch (ParseException e) {
} catch (ParseException ignored) {
}
}
@ -141,15 +128,13 @@ public class ToJsclTextProcessorTest extends AbstractCalculatorTest {
@Test
public void testNumeralBases() throws Exception {
final TextProcessor<PreparedExpression, String> processor = ToJsclTextProcessor.getInstance();
final NumeralBase defaultNumeralBase = JsclMathEngine.getInstance().getNumeralBase();
try {
JsclMathEngine.getInstance().setNumeralBase(NumeralBase.bin);
Assert.assertEquals("101", JsclMathEngine.getInstance().evaluate("10+11"));
JsclMathEngine.getInstance().setNumeralBase(NumeralBase.hex);
Assert.assertEquals("56CE+CAD", processor.process("56CE+CAD").getValue());
Assert.assertEquals("56CE+CAD", preprocessor.process("56CE+CAD").getValue());
} finally {
JsclMathEngine.getInstance().setNumeralBase(defaultNumeralBase);
}

View File

@ -2,6 +2,7 @@ package org.solovyev.android.calculator;
import android.content.Intent;
import android.os.Build;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
@ -18,26 +19,31 @@ import static org.solovyev.android.calculator.WidgetReceiver.*;
@RunWith(RobolectricGradleTestRunner.class)
public class WidgetReceiverTest {
private WidgetReceiver widgetReceiver;
@Before
public void setUp() throws Exception {
widgetReceiver.keyboard = Mockito.mock(Keyboard.class);
}
@Test
public void testShouldPressButtonOnIntent() throws Exception {
//Locator.setKeyboard(mock(Keyboard.class));
final Intent intent = newButtonClickedIntent(application, four);
new WidgetReceiver().onReceive(application, intent);
widgetReceiver = new WidgetReceiver();
widgetReceiver.onReceive(application, intent);
verify(Locator.getInstance().getKeyboard(), times(1)).buttonPressed(Mockito.anyString());
verify(Locator.getInstance().getKeyboard(), times(1)).buttonPressed("4");
verify(widgetReceiver.keyboard, times(1)).buttonPressed(Mockito.anyString());
verify(widgetReceiver.keyboard, times(1)).buttonPressed("4");
}
@Test
public void testShouldDoNothingIfButtonInvalid() throws Exception {
//Locator.setKeyboard(mock(Keyboard.class));
final Intent intent = new Intent(application, WidgetReceiver.class);
intent.setAction(ACTION_BUTTON_PRESSED);
intent.putExtra(ACTION_BUTTON_ID_EXTRA, "test!@");
new WidgetReceiver().onReceive(application, intent);
widgetReceiver.onReceive(application, intent);
verify(Locator.getInstance().getKeyboard(), times(0)).buttonPressed(Mockito.anyString());
verify(widgetReceiver.keyboard, times(0)).buttonPressed(Mockito.anyString());
}
}

View File

@ -22,28 +22,15 @@
package org.solovyev.android.calculator.jscl;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.solovyev.android.calculator.AbstractCalculatorTest;
import org.solovyev.android.calculator.CalculatorTestUtils;
import jscl.AngleUnit;
import jscl.JsclMathEngine;
import jscl.math.Expression;
import jscl.math.Generic;
import org.junit.Test;
/**
* User: serso
* Date: 10/18/11
* Time: 10:42 PM
*/
public class FromJsclNumericTextProcessorTest extends AbstractCalculatorTest {
import static org.junit.Assert.assertEquals;
@BeforeClass
public static void staticSetUp() throws Exception {
CalculatorTestUtils.staticSetUp();
}
public class FromJsclNumericTextProcessorTest {
@Test
public void testCreateResultForComplexNumber() throws Exception {
@ -52,18 +39,18 @@ public class FromJsclNumericTextProcessorTest extends AbstractCalculatorTest {
final JsclMathEngine me = JsclMathEngine.getInstance();
final AngleUnit defaultAngleUnits = me.getAngleUnits();
Assert.assertEquals("1.22133+23 123i", cm.process(Expression.valueOf("1.22133232+23123*i").numeric()));
Assert.assertEquals("1.22133+1.2i", cm.process(Expression.valueOf("1.22133232+1.2*i").numeric()));
Assert.assertEquals("1.22133+0i", cm.process(Expression.valueOf("1.22133232+0.000000001*i").numeric()));
assertEquals("1.22133+23 123i", cm.process(Expression.valueOf("1.22133232+23123*i").numeric()));
assertEquals("1.22133+1.2i", cm.process(Expression.valueOf("1.22133232+1.2*i").numeric()));
assertEquals("1.22133+0i", cm.process(Expression.valueOf("1.22133232+0.000000001*i").numeric()));
try {
me.setAngleUnits(AngleUnit.rad);
Assert.assertEquals("1-0i", cm.process(Expression.valueOf("-(e^(i*π))").numeric()));
assertEquals("1-0i", cm.process(Expression.valueOf("-(e^(i*π))").numeric()));
} finally {
me.setAngleUnits(defaultAngleUnits);
}
Assert.assertEquals("1.22i", cm.process(Expression.valueOf("1.22*i").numeric()));
Assert.assertEquals("i", cm.process(Expression.valueOf("i").numeric()));
assertEquals("1.22i", cm.process(Expression.valueOf("1.22*i").numeric()));
assertEquals("i", cm.process(Expression.valueOf("i").numeric()));
Generic numeric = Expression.valueOf("e^(Π*i)+1").numeric();
junit.framework.Assert.assertEquals("0i", cm.process(numeric));
assertEquals("0i", cm.process(numeric));
}
}

View File

@ -22,52 +22,49 @@
package org.solovyev.android.calculator.math;
import jscl.JsclMathEngine;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Before;
import org.junit.Test;
import org.solovyev.android.calculator.AbstractCalculatorTest;
import org.solovyev.android.calculator.CalculatorTestUtils;
import org.solovyev.android.calculator.Engine;
import static org.junit.Assert.assertEquals;
import static org.solovyev.android.calculator.math.MathType.postfix_function;
/**
* User: serso
* Date: 10/5/11
* Time: 1:25 AM
*/
public class MathTypeTest extends AbstractCalculatorTest {
public class MathTypeTest {
@BeforeClass
public static void staticSetUp() throws Exception {
CalculatorTestUtils.staticSetUp();
Engine engine;
@Before
public void setUp() throws Exception {
engine = new Engine(new JsclMathEngine());
}
@Test
public void testGetType() throws Exception {
assertEquals(MathType.function, MathType.getType("sin", 0, false).type);
assertEquals(MathType.text, MathType.getType("sn", 0, false).type);
assertEquals(MathType.text, MathType.getType("s", 0, false).type);
assertEquals(MathType.text, MathType.getType("", 0, false).type);
assertEquals(MathType.function, MathType.getType("sin", 0, false, engine).type);
assertEquals(MathType.text, MathType.getType("sn", 0, false, engine).type);
assertEquals(MathType.text, MathType.getType("s", 0, false, engine).type);
assertEquals(MathType.text, MathType.getType("", 0, false, engine).type);
try {
assertEquals(MathType.text, MathType.getType("22", -1, false).type);
assertEquals(MathType.text, MathType.getType("22", -1, false, engine).type);
Assert.fail();
} catch (IllegalArgumentException e) {
}
try {
assertEquals(MathType.text, MathType.getType("22", 2, false).type);
assertEquals(MathType.text, MathType.getType("22", 2, false, engine).type);
Assert.fail();
} catch (IllegalArgumentException e) {
}
assertEquals("atanh", MathType.getType("atanh", 0, false).match);
assertEquals("atanh", MathType.getType("atanh", 0, false, engine).match);
}
@Test
public void testPostfixFunctionsProcessing() throws Exception {
assertEquals(postfix_function, MathType.getType("5!", 1, false).type);
assertEquals(postfix_function, MathType.getType("!", 0, false).type);
assertEquals(postfix_function, MathType.getType("5!", 1, false, engine).type);
assertEquals(postfix_function, MathType.getType("!", 0, false, engine).type);
}
}

View File

@ -30,11 +30,9 @@ import jscl.math.Expression;
import jscl.math.function.CustomFunction;
import jscl.text.ParseException;
import junit.framework.Assert;
import org.junit.BeforeClass;
import org.junit.Before;
import org.junit.Test;
import org.solovyev.android.calculator.AbstractCalculatorTest;
import org.solovyev.android.calculator.CalculatorTestUtils;
import org.solovyev.android.calculator.Locator;
import org.solovyev.android.calculator.BaseCalculatorTest;
import org.solovyev.android.calculator.jscl.JsclOperation;
import org.solovyev.android.calculator.variables.CppVariable;
@ -43,57 +41,45 @@ import java.util.Locale;
import static org.junit.Assert.fail;
public class AndroidEngineTest extends BaseCalculatorTest {
/**
* User: serso
* Date: 9/17/11
* Time: 9:47 PM
*/
@SuppressWarnings("deprecation")
public class AndroidEngineTest extends AbstractCalculatorTest {
@BeforeClass
public static void staticSetUp() throws Exception {
CalculatorTestUtils.staticSetUp();
Locator.getInstance().getEngine().getMathEngine().setPrecision(3);
@Before
public void setUp() throws Exception {
super.setUp();
engine.getMathEngine().setPrecision(3);
}
@Test
public void testDegrees() throws Exception {
final MathEngine cm = Locator.getInstance().getEngine().getMathEngine();
final AngleUnit defaultAngleUnit = cm.getAngleUnits();
final MathEngine me = engine.getMathEngine();
final AngleUnit defaultAngleUnit = me.getAngleUnits();
try {
cm.setAngleUnits(AngleUnit.rad);
cm.setPrecision(3);
CalculatorTestUtils.assertError("°");
CalculatorTestUtils.assertEval("0.017", "");
CalculatorTestUtils.assertEval("0.349", "20.0°");
CalculatorTestUtils.assertEval("0.5", "sin(30°)");
CalculatorTestUtils.assertEval("0.524", "asin(sin(30°))");
CalculatorTestUtils.assertEval("∂(cos(t), t, t, 1°)", "∂(cos(t),t,t,1°)");
me.setAngleUnits(AngleUnit.rad);
me.setPrecision(3);
assertError("°");
assertEval("0.017", "");
assertEval("0.349", "20.0°");
assertEval("0.5", "sin(30°)");
assertEval("0.524", "asin(sin(30°))");
assertEval("∂(cos(t), t, t, 1°)", "∂(cos(t),t,t,1°)");
CalculatorTestUtils.assertEval("∂(cos(t), t, t, 1°)", "∂(cos(t),t,t,1°)", JsclOperation.simplify);
assertEval("∂(cos(t), t, t, 1°)", "∂(cos(t),t,t,1°)", JsclOperation.simplify);
} finally {
cm.setAngleUnits(defaultAngleUnit);
me.setAngleUnits(defaultAngleUnit);
}
}
@Test
public void testFormatting() throws Exception {
final MathEngine ce = Locator.getInstance().getEngine().getMathEngine();
CalculatorTestUtils.assertEval("12 345", ce.simplify("12345"));
final MathEngine me = engine.getMathEngine();
assertEval("12 345", me.simplify("12345"));
}
@Test
public void testI() throws ParseException {
final MathEngine cm = Locator.getInstance().getEngine().getMathEngine();
final MathEngine me = engine.getMathEngine();
CalculatorTestUtils.assertEval("-i", cm.evaluate("i^3"));
assertEval("-i", me.evaluate("i^3"));
for (int i = 0; i < 1000; i++) {
double real = (Math.random() - 0.5) * 1000;
double imag = (Math.random() - 0.5) * 1000;
@ -107,7 +93,7 @@ public class AndroidEngineTest extends AbstractCalculatorTest {
sb.append(imag);
sb.append("^").append(exp);
try {
cm.evaluate(sb.toString());
me.evaluate(sb.toString());
} catch (Throwable e) {
fail(sb.toString());
}
@ -116,101 +102,101 @@ public class AndroidEngineTest extends AbstractCalculatorTest {
@Test
public void testEmptyFunction() throws Exception {
final MathEngine cm = Locator.getInstance().getEngine().getMathEngine();
final MathEngine me = engine.getMathEngine();
try {
cm.evaluate("cos(cos(cos(cos(acos(acos(acos(acos(acos(acos(acos(acos(cos(cos(cos(cos(cosh(acos(cos(cos(cos(cos(cos(acos(acos(acos(acos(acos(acos(acos(acos(cos(cos(cos(cos(cosh(acos(cos())))))))))))))))))))))))))))))))))))))");
me.evaluate("cos(cos(cos(cos(acos(acos(acos(acos(acos(acos(acos(acos(cos(cos(cos(cos(cosh(acos(cos(cos(cos(cos(cos(acos(acos(acos(acos(acos(acos(acos(acos(cos(cos(cos(cos(cosh(acos(cos())))))))))))))))))))))))))))))))))))))");
Assert.fail();
} catch (ParseException e) {
} catch (ParseException ignored) {
}
CalculatorTestUtils.assertEval("0.34+1.382i", "ln(ln(ln(ln(ln(ln(ln(ln(ln(ln(ln(ln(ln(ln(ln(100)))))))))))))))");
assertEval("0.34+1.382i", "ln(ln(ln(ln(ln(ln(ln(ln(ln(ln(ln(ln(ln(ln(ln(100)))))))))))))))");
try {
cm.evaluate("cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos())))))))))))))))))))))))))))))))))))");
me.evaluate("cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos())))))))))))))))))))))))))))))))))))");
Assert.fail();
} catch (ParseException e) {
} catch (ParseException ignored) {
}
final AngleUnit defaultAngleUnit = cm.getAngleUnits();
final AngleUnit defaultAngleUnit = me.getAngleUnits();
try {
cm.setAngleUnits(AngleUnit.rad);
CalculatorTestUtils.assertEval("0.739", cm.evaluate("cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(1))))))))))))))))))))))))))))))))))))"));
me.setAngleUnits(AngleUnit.rad);
assertEval("0.739", me.evaluate("cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(cos(1))))))))))))))))))))))))))))))))))))"));
} finally {
cm.setAngleUnits(defaultAngleUnit);
me.setAngleUnits(defaultAngleUnit);
}
Locator.getInstance().getEngine().getVariablesRegistry().add(CppVariable.builder("si").withValue(5d).build().toJsclBuilder());
CalculatorTestUtils.assertEval("5", cm.evaluate("si"));
engine.getVariablesRegistry().add(CppVariable.builder("si").withValue(5d).build().toJsclBuilder());
assertEval("5", me.evaluate("si"));
CalculatorTestUtils.assertError("sin");
assertError("sin");
}
@Test
public void testRounding() throws Exception {
final MathEngine cm = Locator.getInstance().getEngine().getMathEngine();
final MathEngine me = engine.getMathEngine();
try {
DecimalFormatSymbols decimalGroupSymbols = new DecimalFormatSymbols(Locale.getDefault());
decimalGroupSymbols.setDecimalSeparator('.');
decimalGroupSymbols.setGroupingSeparator('\'');
cm.setDecimalGroupSymbols(decimalGroupSymbols);
cm.setPrecision(2);
CalculatorTestUtils.assertEval("12'345'678.9", cm.evaluate("1.23456789E7"));
cm.setPrecision(10);
CalculatorTestUtils.assertEval("12'345'678.9", cm.evaluate("1.23456789E7"));
CalculatorTestUtils.assertEval("123'456'789", cm.evaluate("1.234567890E8"));
CalculatorTestUtils.assertEval("1'234'567'890.1", cm.evaluate("1.2345678901E9"));
me.setDecimalGroupSymbols(decimalGroupSymbols);
me.setPrecision(2);
assertEval("12'345'678.9", me.evaluate("1.23456789E7"));
me.setPrecision(10);
assertEval("12'345'678.9", me.evaluate("1.23456789E7"));
assertEval("123'456'789", me.evaluate("1.234567890E8"));
assertEval("1'234'567'890.1", me.evaluate("1.2345678901E9"));
} finally {
cm.setPrecision(3);
me.setPrecision(3);
DecimalFormatSymbols decimalGroupSymbols = new DecimalFormatSymbols(Locale.getDefault());
decimalGroupSymbols.setDecimalSeparator('.');
decimalGroupSymbols.setGroupingSeparator(JsclMathEngine.GROUPING_SEPARATOR_DEFAULT.charAt(0));
cm.setDecimalGroupSymbols(decimalGroupSymbols);
me.setDecimalGroupSymbols(decimalGroupSymbols);
}
}
@Test
public void testNumeralSystems() throws Exception {
final MathEngine cm = Locator.getInstance().getEngine().getMathEngine();
final MathEngine me = engine.getMathEngine();
CalculatorTestUtils.assertEval("11 259 375", "0x:ABCDEF");
CalculatorTestUtils.assertEval("30 606 154.462", "0x:ABCDEF*e");
CalculatorTestUtils.assertEval("30 606 154.462", "e*0x:ABCDEF");
CalculatorTestUtils.assertEval("e", "e*0x:ABCDEF/0x:ABCDEF");
CalculatorTestUtils.assertEval("30 606 154.462", "0x:ABCDEF*e*0x:ABCDEF/0x:ABCDEF");
CalculatorTestUtils.assertEval("30 606 154.462", "c+0x:ABCDEF*e*0x:ABCDEF/0x:ABCDEF-c+0x:C-0x:C");
CalculatorTestUtils.assertEval("1 446 257 064 651.832", "28*28 * sin(28) - 0b:1101 + √(28) + exp ( 28) ");
CalculatorTestUtils.assertEval("13", "0b:1101");
assertEval("11 259 375", "0x:ABCDEF");
assertEval("30 606 154.462", "0x:ABCDEF*e");
assertEval("30 606 154.462", "e*0x:ABCDEF");
assertEval("e", "e*0x:ABCDEF/0x:ABCDEF");
assertEval("30 606 154.462", "0x:ABCDEF*e*0x:ABCDEF/0x:ABCDEF");
assertEval("30 606 154.462", "c+0x:ABCDEF*e*0x:ABCDEF/0x:ABCDEF-c+0x:C-0x:C");
assertEval("1 446 257 064 651.832", "28*28 * sin(28) - 0b:1101 + √(28) + exp ( 28) ");
assertEval("13", "0b:1101");
CalculatorTestUtils.assertError("0b:π");
assertError("0b:π");
final NumeralBase defaultNumeralBase = cm.getNumeralBase();
final NumeralBase defaultNumeralBase = me.getNumeralBase();
try {
cm.setNumeralBase(NumeralBase.bin);
CalculatorTestUtils.assertEval("101", "10+11");
CalculatorTestUtils.assertEval("0.101", "10/11");
me.setNumeralBase(NumeralBase.bin);
assertEval("101", "10+11");
assertEval("0.101", "10/11");
cm.setNumeralBase(NumeralBase.hex);
CalculatorTestUtils.assertEval("63 7B", "56CE+CAD");
CalculatorTestUtils.assertEval("E", "E");
me.setNumeralBase(NumeralBase.hex);
assertEval("63 7B", "56CE+CAD");
assertEval("E", "E");
} finally {
cm.setNumeralBase(defaultNumeralBase);
me.setNumeralBase(defaultNumeralBase);
}
}
@Test
public void testLog() throws Exception {
final MathEngine cm = Locator.getInstance().getEngine().getMathEngine();
final MathEngine me = engine.getMathEngine();
CalculatorTestUtils.assertEval("", Expression.valueOf("1/0").numeric().toString());
CalculatorTestUtils.assertEval("", Expression.valueOf("ln(10)/ln(1)").numeric().toString());
assertEval("", Expression.valueOf("1/0").numeric().toString());
assertEval("", Expression.valueOf("ln(10)/ln(1)").numeric().toString());
// logarithm
CalculatorTestUtils.assertEval("ln(x)/ln(base)", ((CustomFunction) cm.getFunctionsRegistry().get("log")).getContent());
CalculatorTestUtils.assertEval("", "log(1, 10)");
CalculatorTestUtils.assertEval("3.322", "log(2, 10)");
CalculatorTestUtils.assertEval("1.431", "log(5, 10)");
CalculatorTestUtils.assertEval("0.96", "log(11, 10)");
CalculatorTestUtils.assertEval("1/(bln(a))", "∂(log(a, b), b)", JsclOperation.simplify);
CalculatorTestUtils.assertEval("-ln(b)/(aln(a)^2)", "∂(log(a, b), a)", JsclOperation.simplify);
assertEval("ln(x)/ln(base)", ((CustomFunction) me.getFunctionsRegistry().get("log")).getContent());
assertEval("", "log(1, 10)");
assertEval("3.322", "log(2, 10)");
assertEval("1.431", "log(5, 10)");
assertEval("0.96", "log(11, 10)");
assertEval("1/(bln(a))", "∂(log(a, b), b)", JsclOperation.simplify);
assertEval("-ln(b)/(aln(a)^2)", "∂(log(a, b), a)", JsclOperation.simplify);
}
}

View File

@ -22,59 +22,48 @@
package org.solovyev.android.calculator.model;
import org.junit.BeforeClass;
import org.junit.Before;
import org.junit.Test;
import org.solovyev.android.calculator.AbstractCalculatorTest;
import org.solovyev.android.calculator.CalculatorTestUtils;
import org.solovyev.android.calculator.Locator;
import org.solovyev.android.calculator.BaseCalculatorTest;
public class ComparisonTest extends BaseCalculatorTest {
/**
* User: serso
* Date: 9/17/11
* Time: 9:47 PM
*/
@SuppressWarnings("deprecation")
public class ComparisonTest extends AbstractCalculatorTest {
@BeforeClass
public static void staticSetUp() throws Exception {
CalculatorTestUtils.staticSetUp();
Locator.getInstance().getEngine().getMathEngine().setPrecision(3);
@Before
public void setUp() throws Exception {
super.setUp();
engine.getMathEngine().setPrecision(3);
}
@Test
public void testComparisonFunction() throws Exception {
CalculatorTestUtils.assertEval("0", "eq(0, 1)");
CalculatorTestUtils.assertEval("1", "eq(1, 1)");
CalculatorTestUtils.assertEval("1", "eq(1, 1.0)");
CalculatorTestUtils.assertEval("0", "eq(1, 1.000000000000001)");
CalculatorTestUtils.assertEval("0", "eq(1, 0)");
assertEval("0", "eq(0, 1)");
assertEval("1", "eq(1, 1)");
assertEval("1", "eq(1, 1.0)");
assertEval("0", "eq(1, 1.000000000000001)");
assertEval("0", "eq(1, 0)");
CalculatorTestUtils.assertEval("1", "lt(0, 1)");
CalculatorTestUtils.assertEval("0", "lt(1, 1)");
CalculatorTestUtils.assertEval("0", "lt(1, 0)");
assertEval("1", "lt(0, 1)");
assertEval("0", "lt(1, 1)");
assertEval("0", "lt(1, 0)");
CalculatorTestUtils.assertEval("0", "gt(0, 1)");
CalculatorTestUtils.assertEval("0", "gt(1, 1)");
CalculatorTestUtils.assertEval("1", "gt(1, 0)");
assertEval("0", "gt(0, 1)");
assertEval("0", "gt(1, 1)");
assertEval("1", "gt(1, 0)");
CalculatorTestUtils.assertEval("1", "ne(0, 1)");
CalculatorTestUtils.assertEval("0", "ne(1, 1)");
CalculatorTestUtils.assertEval("1", "ne(1, 0)");
assertEval("1", "ne(0, 1)");
assertEval("0", "ne(1, 1)");
assertEval("1", "ne(1, 0)");
CalculatorTestUtils.assertEval("1", "le(0, 1)");
CalculatorTestUtils.assertEval("1", "le(1, 1)");
CalculatorTestUtils.assertEval("0", "le(1, 0)");
assertEval("1", "le(0, 1)");
assertEval("1", "le(1, 1)");
assertEval("0", "le(1, 0)");
CalculatorTestUtils.assertEval("0", "ge(0, 1)");
CalculatorTestUtils.assertEval("1", "ge(1, 1)");
CalculatorTestUtils.assertEval("1", "ge(1, 0)");
CalculatorTestUtils.assertEval("0", "ap(0, 1)");
CalculatorTestUtils.assertEval("1", "ap(1, 1)");
CalculatorTestUtils.assertEval("0", "ap(1, 0)");
assertEval("0", "ge(0, 1)");
assertEval("1", "ge(1, 1)");
assertEval("1", "ge(1, 0)");
assertEval("0", "ap(0, 1)");
assertEval("1", "ap(1, 1)");
assertEval("0", "ap(1, 0)");
}
}

View File

@ -28,147 +28,138 @@ import jscl.NumeralBase;
import jscl.math.Expression;
import jscl.math.Generic;
import jscl.math.function.Constant;
import org.junit.BeforeClass;
import org.junit.Before;
import org.junit.Test;
import org.solovyev.android.calculator.AbstractCalculatorTest;
import org.solovyev.android.calculator.CalculatorTestUtils;
import org.solovyev.android.calculator.Locator;
import org.solovyev.android.calculator.BaseCalculatorTest;
import org.solovyev.android.calculator.jscl.JsclOperation;
import org.solovyev.android.calculator.variables.CppVariable;
/**
* User: serso
* Date: 9/17/11
* Time: 9:47 PM
*/
public class EvaluateTest extends BaseCalculatorTest {
@SuppressWarnings("deprecation")
public class EvaluateTest extends AbstractCalculatorTest {
@BeforeClass
public static void staticSetUp() throws Exception {
CalculatorTestUtils.staticSetUp();
Locator.getInstance().getEngine().getMathEngine().setPrecision(3);
@Before
public void setUp() throws Exception {
super.setUp();
engine.getMathEngine().setPrecision(3);
}
@Test
public void testEvaluate() throws Exception {
final MathEngine cm = Locator.getInstance().getEngine().getMathEngine();
final MathEngine cm = engine.getMathEngine();
final AngleUnit defaultAngleUnit = cm.getAngleUnits();
CalculatorTestUtils.assertEval("cos(t)+10%", "cos(t)+10%", JsclOperation.simplify);
assertEval("cos(t)+10%", "cos(t)+10%", JsclOperation.simplify);
final Generic expression = cm.simplifyGeneric("cos(t)+10%");
expression.substitute(new Constant("t"), Expression.valueOf(100d));
CalculatorTestUtils.assertEval("it", "it", JsclOperation.simplify);
CalculatorTestUtils.assertEval("10%", "10%", JsclOperation.simplify);
CalculatorTestUtils.assertEval("0", "eq(0, 1)");
CalculatorTestUtils.assertEval("1", "eq(1, 1)");
CalculatorTestUtils.assertEval("1", "eq( 1, 1)");
CalculatorTestUtils.assertEval("1", "eq( 1, 1)", JsclOperation.simplify);
CalculatorTestUtils.assertEval("1", "lg(10)");
CalculatorTestUtils.assertEval("4", "2+2");
assertEval("it", "it", JsclOperation.simplify);
assertEval("10%", "10%", JsclOperation.simplify);
assertEval("0", "eq(0, 1)");
assertEval("1", "eq(1, 1)");
assertEval("1", "eq( 1, 1)");
assertEval("1", "eq( 1, 1)", JsclOperation.simplify);
assertEval("1", "lg(10)");
assertEval("4", "2+2");
try {
cm.setAngleUnits(AngleUnit.rad);
CalculatorTestUtils.assertEval("-0.757", "sin(4)");
CalculatorTestUtils.assertEval("0.524", "asin(0.5)");
CalculatorTestUtils.assertEval("-0.396", "sin(4)asin(0.5)");
CalculatorTestUtils.assertEval("-0.56", "sin(4)asin(0.5)√(2)");
CalculatorTestUtils.assertEval("-0.56", "sin(4)asin(0.5)√(2)");
assertEval("-0.757", "sin(4)");
assertEval("0.524", "asin(0.5)");
assertEval("-0.396", "sin(4)asin(0.5)");
assertEval("-0.56", "sin(4)asin(0.5)√(2)");
assertEval("-0.56", "sin(4)asin(0.5)√(2)");
} finally {
cm.setAngleUnits(defaultAngleUnit);
}
CalculatorTestUtils.assertEval("7.389", "e^2");
CalculatorTestUtils.assertEval("7.389", "exp(1)^2");
CalculatorTestUtils.assertEval("7.389", "exp(2)");
CalculatorTestUtils.assertEval("2+i", "2*1+√(-1)");
assertEval("7.389", "e^2");
assertEval("7.389", "exp(1)^2");
assertEval("7.389", "exp(2)");
assertEval("2+i", "2*1+√(-1)");
try {
cm.setAngleUnits(AngleUnit.rad);
CalculatorTestUtils.assertEval("0.921+Πi", "ln(5cosh(38π√(2cos(2))))");
CalculatorTestUtils.assertEval("-3.41+3.41i", "(5tan(2i)+2i)/(1-i)");
assertEval("0.921+Πi", "ln(5cosh(38π√(2cos(2))))");
assertEval("-3.41+3.41i", "(5tan(2i)+2i)/(1-i)");
} finally {
cm.setAngleUnits(defaultAngleUnit);
}
CalculatorTestUtils.assertEval("7.389i", "iexp(2)");
CalculatorTestUtils.assertEval("2+7.389i", "2+iexp(2)");
CalculatorTestUtils.assertEval("2+7.389i", "2+√(-1)exp(2)");
CalculatorTestUtils.assertEval("2-2.5i", "2-2.5i");
CalculatorTestUtils.assertEval("-2-2.5i", "-2-2.5i");
CalculatorTestUtils.assertEval("-2+2.5i", "-2+2.5i");
CalculatorTestUtils.assertEval("-2+2.1i", "-2+2.1i");
CalculatorTestUtils.assertEval("-0.1-0.2i", "(1-i)/(2+6i)");
assertEval("7.389i", "iexp(2)");
assertEval("2+7.389i", "2+iexp(2)");
assertEval("2+7.389i", "2+√(-1)exp(2)");
assertEval("2-2.5i", "2-2.5i");
assertEval("-2-2.5i", "-2-2.5i");
assertEval("-2+2.5i", "-2+2.5i");
assertEval("-2+2.1i", "-2+2.1i");
assertEval("-0.1-0.2i", "(1-i)/(2+6i)");
CalculatorTestUtils.assertEval("24", "4!");
CalculatorTestUtils.assertEval("24", "(2+2)!");
CalculatorTestUtils.assertEval("120", "(2+2+1)!");
CalculatorTestUtils.assertEval("24", "(2.0+2.0)!");
CalculatorTestUtils.assertEval("24", "4.0!");
CalculatorTestUtils.assertEval("720", "(3!)!");
CalculatorTestUtils.assertEval("36", Expression.valueOf("3!^2").numeric().toString());
CalculatorTestUtils.assertEval("3", Expression.valueOf("cubic(27)").numeric().toString());
CalculatorTestUtils.assertError("i!");
assertEval("24", "4!");
assertEval("24", "(2+2)!");
assertEval("120", "(2+2+1)!");
assertEval("24", "(2.0+2.0)!");
assertEval("24", "4.0!");
assertEval("720", "(3!)!");
assertEval("36", Expression.valueOf("3!^2").numeric().toString());
assertEval("3", Expression.valueOf("cubic(27)").numeric().toString());
assertError("i!");
CalculatorTestUtils.assertEval("1", cm.evaluate("(π/π)!"));
assertEval("1", cm.evaluate("(π/π)!"));
CalculatorTestUtils.assertError("(-1)i!");
CalculatorTestUtils.assertEval("24i", "4!i");
assertError("(-1)i!");
assertEval("24i", "4!i");
Locator.getInstance().getEngine().getVariablesRegistry().add(CppVariable.builder("si", 5d).build().toJsclBuilder());
engine.getVariablesRegistry().add(CppVariable.builder("si", 5d).build().toJsclBuilder());
try {
cm.setAngleUnits(AngleUnit.rad);
CalculatorTestUtils.assertEval("0.451", "acos(0.8999999999999811)");
CalculatorTestUtils.assertEval("-0.959", "sin(5)");
CalculatorTestUtils.assertEval("-4.795", "sin(5)si");
CalculatorTestUtils.assertEval("-23.973", "sisin(5)si");
CalculatorTestUtils.assertEval("-23.973", "si*sin(5)si");
CalculatorTestUtils.assertEval("-3.309", "sisin(5si)si");
assertEval("0.451", "acos(0.8999999999999811)");
assertEval("-0.959", "sin(5)");
assertEval("-4.795", "sin(5)si");
assertEval("-23.973", "sisin(5)si");
assertEval("-23.973", "si*sin(5)si");
assertEval("-3.309", "sisin(5si)si");
} finally {
cm.setAngleUnits(defaultAngleUnit);
}
Locator.getInstance().getEngine().getVariablesRegistry().add(CppVariable.builder("s", 1d).build().toJsclBuilder());
CalculatorTestUtils.assertEval("5", cm.evaluate("si"));
engine.getVariablesRegistry().add(CppVariable.builder("s", 1d).build().toJsclBuilder());
assertEval("5", cm.evaluate("si"));
Locator.getInstance().getEngine().getVariablesRegistry().add(CppVariable.builder("k", 3.5d).build().toJsclBuilder());
Locator.getInstance().getEngine().getVariablesRegistry().add(CppVariable.builder("k1", 4d).build().toJsclBuilder());
CalculatorTestUtils.assertEval("4", "k11");
engine.getVariablesRegistry().add(CppVariable.builder("k", 3.5d).build().toJsclBuilder());
engine.getVariablesRegistry().add(CppVariable.builder("k1", 4d).build().toJsclBuilder());
assertEval("4", "k11");
Locator.getInstance().getEngine().getVariablesRegistry().add(CppVariable.builder("t").build().toJsclBuilder());
CalculatorTestUtils.assertEval("11t", "t11");
CalculatorTestUtils.assertEval("11et", "t11e");
CalculatorTestUtils.assertEval("", "");
CalculatorTestUtils.assertEval("", "Infinity");
CalculatorTestUtils.assertEval("11∞t", "t11∞");
CalculatorTestUtils.assertEval("-t+t^3", "t(t-1)(t+1)");
engine.getVariablesRegistry().add(CppVariable.builder("t").build().toJsclBuilder());
assertEval("11t", "t11");
assertEval("11et", "t11e");
assertEval("", "");
assertEval("", "Infinity");
assertEval("11∞t", "t11∞");
assertEval("-t+t^3", "t(t-1)(t+1)");
CalculatorTestUtils.assertEval("100", "0.1E3");
CalculatorTestUtils.assertEval("3.957", "ln(8)lg(8)+ln(8)");
assertEval("100", "0.1E3");
assertEval("3.957", "ln(8)lg(8)+ln(8)");
CalculatorTestUtils.assertEval("0.933", "0x:E/0x:F");
assertEval("0.933", "0x:E/0x:F");
try {
cm.setNumeralBase(NumeralBase.hex);
CalculatorTestUtils.assertEval("0.EE E", "0x:E/0x:F");
CalculatorTestUtils.assertEval("0.EE E", cm.simplify("0x:E/0x:F"));
CalculatorTestUtils.assertEval("0.EE E", "E/F");
CalculatorTestUtils.assertEval("0.EE E", cm.simplify("E/F"));
assertEval("0.EE E", "0x:E/0x:F");
assertEval("0.EE E", cm.simplify("0x:E/0x:F"));
assertEval("0.EE E", "E/F");
assertEval("0.EE E", cm.simplify("E/F"));
} finally {
cm.setNumeralBase(NumeralBase.dec);
}
CalculatorTestUtils.assertEval("0", "((((((0))))))");
CalculatorTestUtils.assertEval("0", "((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((0))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))");
assertEval("0", "((((((0))))))");
assertEval("0", "((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((0))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))");
/* CalculatorTestUtils.assertEval("0.524", cm.evaluate( "30°").getResult());
CalculatorTestUtils.assertEval("0.524", cm.evaluate( "(10+20)°").getResult());
CalculatorTestUtils.assertEval("1.047", cm.evaluate( "(10+20)°*2").getResult());
/* assertEval("0.524", cm.evaluate( "30°").getResult());
assertEval("0.524", cm.evaluate( "(10+20)°").getResult());
assertEval("1.047", cm.evaluate( "(10+20)°*2").getResult());
try {
CalculatorTestUtils.assertEval("0.278", cm.evaluate( "30°^2").getResult());
assertEval("0.278", cm.evaluate( "30°^2").getResult());
fail();
} catch (ParseException e) {
if ( !e.getMessage().equals("Power operation after postfix function is currently unsupported!") ) {
@ -178,24 +169,24 @@ public class EvaluateTest extends AbstractCalculatorTest {
*//* try {
cm.setTimeout(5000);
CalculatorTestUtils.assertEval("2", cm.evaluate( "2!").getResult());
assertEval("2", cm.evaluate( "2!").getResult());
} finally {
cm.setTimeout(3000);
}*/
Locator.getInstance().getEngine().getVariablesRegistry().add(CppVariable.builder("t").build().toJsclBuilder());
CalculatorTestUtils.assertEval("2t", "∂(t^2,t)", JsclOperation.simplify);
CalculatorTestUtils.assertEval("2t", "∂(t^2,t)");
Locator.getInstance().getEngine().getVariablesRegistry().add(CppVariable.builder("t", 2d).build().toJsclBuilder());
CalculatorTestUtils.assertEval("2t", "∂(t^2,t)", JsclOperation.simplify);
CalculatorTestUtils.assertEval("4", "∂(t^2,t)");
engine.getVariablesRegistry().add(CppVariable.builder("t").build().toJsclBuilder());
assertEval("2t", "∂(t^2,t)", JsclOperation.simplify);
assertEval("2t", "∂(t^2,t)");
engine.getVariablesRegistry().add(CppVariable.builder("t", 2d).build().toJsclBuilder());
assertEval("2t", "∂(t^2,t)", JsclOperation.simplify);
assertEval("4", "∂(t^2,t)");
CalculatorTestUtils.assertEval("-x+xln(x)", "∫(ln(x), x)", JsclOperation.simplify);
CalculatorTestUtils.assertEval("-(x-xln(x))/(ln(2)+ln(5))", "∫(log(10, x), x)", JsclOperation.simplify);
assertEval("-x+xln(x)", "∫(ln(x), x)", JsclOperation.simplify);
assertEval("-(x-xln(x))/(ln(2)+ln(5))", "∫(log(10, x), x)", JsclOperation.simplify);
CalculatorTestUtils.assertEval("∫((ln(2)+ln(5))/ln(x), x)", "∫(ln(10)/ln(x), x)", JsclOperation.simplify);
//CalculatorTestUtils.assertEval("∫(ln(10)/ln(x), x)", Expression.valueOf("∫(log(x, 10), x)").expand().toString());
CalculatorTestUtils.assertEval("∫((ln(2)+ln(5))/ln(x), x)", "∫(log(x, 10), x)");
CalculatorTestUtils.assertEval("∫((ln(2)+ln(5))/ln(x), x)", "∫(log(x, 10), x)", JsclOperation.simplify);
assertEval("∫((ln(2)+ln(5))/ln(x), x)", "∫(ln(10)/ln(x), x)", JsclOperation.simplify);
//assertEval("∫(ln(10)/ln(x), x)", Expression.valueOf("∫(log(x, 10), x)").expand().toString());
assertEval("∫((ln(2)+ln(5))/ln(x), x)", "∫(log(x, 10), x)");
assertEval("∫((ln(2)+ln(5))/ln(x), x)", "∫(log(x, 10), x)", JsclOperation.simplify);
}
}

View File

@ -28,11 +28,9 @@ import jscl.MathEngine;
import jscl.math.Expression;
import jscl.util.ExpressionGeneratorWithInput;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Before;
import org.junit.Test;
import org.solovyev.android.calculator.AbstractCalculatorTest;
import org.solovyev.android.calculator.CalculatorTestUtils;
import org.solovyev.android.calculator.Locator;
import org.solovyev.android.calculator.BaseCalculatorTest;
import org.solovyev.android.calculator.ParseException;
import org.solovyev.common.Converter;
@ -41,30 +39,25 @@ import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
/**
* User: serso
* Date: 12/14/11
* Time: 4:16 PM
*/
public class NumeralBaseTest extends AbstractCalculatorTest {
public class NumeralBaseTest extends BaseCalculatorTest {
@BeforeClass
public static void staticSetUp() throws Exception {
CalculatorTestUtils.staticSetUp();
Locator.getInstance().getEngine().getMathEngine().setPrecision(3);
@Before
public void setUp() throws Exception {
super.setUp();
engine.getMathEngine().setPrecision(3);
}
public static void testExpression(@Nonnull String[] line, @Nonnull Converter<String, String> converter) throws jscl.text.ParseException, ParseException {
public void testExpression(@Nonnull String[] line, @Nonnull Converter<String, String> converter) throws jscl.text.ParseException, ParseException {
final String dec = line[0].toUpperCase();
final String hex = "0x:" + line[1].toUpperCase();
final String bin = "0b:" + line[2].toUpperCase();
final String decExpression = converter.convert(dec);
final String decResult = Locator.getInstance().getEngine().getMathEngine().evaluate(decExpression);
final String decResult = engine.getMathEngine().evaluate(decExpression);
final String hexExpression = converter.convert(hex);
final String hexResult = Locator.getInstance().getEngine().getMathEngine().evaluate(hexExpression);
final String hexResult = engine.getMathEngine().evaluate(hexExpression);
final String binExpression = converter.convert(bin);
final String binResult = Locator.getInstance().getEngine().getMathEngine().evaluate(binExpression);
final String binResult = engine.getMathEngine().evaluate(binExpression);
Assert.assertEquals("dec-hex: " + decExpression + " : " + hexExpression, decResult, hexResult);
Assert.assertEquals("dec-bin: " + decExpression + " : " + binExpression, decResult, binResult);

View File

@ -29,7 +29,6 @@ import org.junit.Before;
import org.junit.Test;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
import org.solovyev.android.calculator.CalculatorTestUtils;
import org.solovyev.android.calculator.functions.OldFunction;
import org.solovyev.android.calculator.functions.OldFunctions;
import org.solovyev.common.Objects;
@ -87,11 +86,6 @@ public class OldFunctionsTest {
" </functions>\n" +
"</functions>";
@Before
public void setUp() throws Exception {
CalculatorTestUtils.staticSetUp();
}
@Nonnull
private OldFunctions testXml(@Nonnull OldFunctions in, @Nullable String expectedXml) throws Exception {
final String actualXml = toXml(in);

View File

@ -27,7 +27,6 @@ import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.solovyev.android.calculator.CalculatorTestUtils.staticSetUp;
@Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.LOLLIPOP)
@RunWith(RobolectricGradleTestRunner.class)
@ -37,8 +36,6 @@ public class AngleUnitsButtonTest {
@Before
public void setUp() throws Exception {
staticSetUp();
final Activity context = Robolectric.buildActivity(Activity.class).create().get();
final ShadowActivity activity = Shadows.shadowOf(context);
button = new AngleUnitsButton(context, activity.createAttributeSet(new ArrayList<Attribute>(), AngleUnitsButton.class));

View File

@ -27,7 +27,6 @@ import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.solovyev.android.calculator.CalculatorTestUtils.staticSetUp;
@Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.LOLLIPOP)
@RunWith(RobolectricGradleTestRunner.class)
@ -37,8 +36,6 @@ public class NumeralBasesButtonTest {
@Before
public void setUp() throws Exception {
staticSetUp();
final Activity context = Robolectric.buildActivity(Activity.class).create().get();
final ShadowActivity activity = Shadows.shadowOf(context);
button = new NumeralBasesButton(context, activity.createAttributeSet(new ArrayList<Attribute>(), NumeralBasesButton.class));

View File

@ -41,7 +41,7 @@ public class JsclMathEngine implements MathEngine {
@Nonnull
private NumeralBase numeralBase = DEFAULT_NUMERAL_BASE;
@Nonnull
private ConstantsRegistry constantsRegistry;
private final ConstantsRegistry constantsRegistry = new ConstantsRegistry();
@Nonnull
private MessageRegistry messageRegistry = Messages.synchronizedMessageRegistry(new FixedCapacityListMessageRegistry(10));
@ -50,8 +50,7 @@ public class JsclMathEngine implements MathEngine {
decimalGroupSymbols.setGroupingSeparator(GROUPING_SEPARATOR_DEFAULT.charAt(0));
}
private JsclMathEngine() {
this.constantsRegistry = new ConstantsRegistry();
public JsclMathEngine() {
}
@Nonnull
@ -176,7 +175,7 @@ public class JsclMathEngine implements MathEngine {
if (name.equals(Constants.PI_INV.getName()) || name.equals(Constants.ANS)) {
return false;
}
return !name.equals(Constants.PI.getName()) || JsclMathEngine.getInstance().getAngleUnits() == AngleUnit.rad;
return !name.equals(Constants.PI.getName()) || getAngleUnits() == AngleUnit.rad;
}
});

View File

@ -4,57 +4,54 @@ import jscl.JsclMathEngine;
import jscl.MathEngine;
import jscl.text.ParseException;
import jscl.text.msg.Messages;
import junit.framework.Assert;
import org.junit.Test;
/**
* User: serso
* Date: 12/15/11
* Time: 10:41 PM
*/
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
public class DoubleFactorialTest {
@Test
public void testDoubleFactorial() throws Exception {
final MathEngine me = JsclMathEngine.getInstance();
Assert.assertEquals("1", me.evaluate("0!"));
Assert.assertEquals("1", me.evaluate("1!"));
Assert.assertEquals("2", me.evaluate("2!"));
Assert.assertEquals("6", me.evaluate("3!"));
Assert.assertEquals("24", me.evaluate("4!"));
assertEquals("1", me.evaluate("0!"));
assertEquals("1", me.evaluate("1!"));
assertEquals("2", me.evaluate("2!"));
assertEquals("6", me.evaluate("3!"));
assertEquals("24", me.evaluate("4!"));
try {
me.evaluate("(-1)!!");
Assert.fail();
fail();
} catch (ArithmeticException e) {
// ok
}
Assert.assertEquals("-1", me.evaluate("-1!!"));
Assert.assertEquals("1", me.evaluate("0!!"));
Assert.assertEquals("1", me.evaluate("1!!"));
Assert.assertEquals("2", me.evaluate("2!!"));
Assert.assertEquals("2", me.evaluate("(2!!)!"));
Assert.assertEquals("2", me.evaluate("(2!)!!"));
Assert.assertEquals("3", me.evaluate("3!!"));
Assert.assertEquals("48", me.evaluate("(3!)!!"));
Assert.assertEquals("6", me.evaluate("(3!!)!"));
Assert.assertEquals("8", me.evaluate("4!!"));
Assert.assertEquals("15", me.evaluate("5!!"));
Assert.assertEquals("48", me.evaluate("6!!"));
Assert.assertEquals("105", me.evaluate("7!!"));
Assert.assertEquals("384", me.evaluate("8!!"));
Assert.assertEquals("945", me.evaluate("9!!"));
assertEquals("-1", me.evaluate("-1!!"));
assertEquals("1", me.evaluate("0!!"));
assertEquals("1", me.evaluate("1!!"));
assertEquals("2", me.evaluate("2!!"));
assertEquals("2", me.evaluate("(2!!)!"));
assertEquals("2", me.evaluate("(2!)!!"));
assertEquals("3", me.evaluate("3!!"));
assertEquals("48", me.evaluate("(3!)!!"));
assertEquals("6", me.evaluate("(3!!)!"));
assertEquals("8", me.evaluate("4!!"));
assertEquals("15", me.evaluate("5!!"));
assertEquals("48", me.evaluate("6!!"));
assertEquals("105", me.evaluate("7!!"));
assertEquals("384", me.evaluate("8!!"));
assertEquals("945", me.evaluate("9!!"));
try {
me.evaluate("9!!!");
Assert.fail();
fail();
} catch (ParseException e) {
if (Messages.msg_18.equals(e.getMessageCode())) {
// ok
} else {
Assert.fail();
fail();
}
}