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.support.v4.app.FragmentTransaction;
import android.text.Spannable; import android.text.Spannable;
import android.text.SpannableString; import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan; import android.text.style.ForegroundColorSpan;
import android.util.Log; import android.util.Log;
import android.view.View; import android.view.View;
@ -60,9 +59,7 @@ import org.solovyev.android.wizard.Wizards;
import org.solovyev.common.JPredicate; import org.solovyev.common.JPredicate;
import java.util.Collection; import java.util.Collection;
import java.util.Formatter;
import java.util.List; import java.util.List;
import java.util.Locale;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
@ -79,16 +76,6 @@ public final class App {
public static final String TAG = "C++"; 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 @Nonnull
private static Languages languages; private static Languages languages;
@Nonnull @Nonnull

View File

@ -28,10 +28,7 @@ import android.text.TextUtils;
import android.util.Log; import android.util.Log;
import com.squareup.otto.Bus; import com.squareup.otto.Bus;
import com.squareup.otto.Subscribe; import com.squareup.otto.Subscribe;
import jscl.JsclArithmeticException; import jscl.*;
import jscl.JsclMathEngine;
import jscl.NumeralBase;
import jscl.NumeralBaseException;
import jscl.math.Generic; import jscl.math.Generic;
import jscl.math.function.Constants; import jscl.math.function.Constants;
import jscl.math.function.IConstant; import jscl.math.function.IConstant;
@ -65,16 +62,12 @@ public class Calculator implements SharedPreferences.OnSharedPreferenceChangeLis
public static final long NO_SEQUENCE = -1; public static final long NO_SEQUENCE = -1;
@Nonnull
private final CalculatorEventContainer calculatorEventContainer = new ListCalculatorEventContainer();
@Nonnull @Nonnull
private static final AtomicLong SEQUENCER = new AtomicLong(NO_SEQUENCE); private static final AtomicLong SEQUENCER = new AtomicLong(NO_SEQUENCE);
@Nonnull @Nonnull
private final SharedPreferences preferences; private final SharedPreferences preferences;
@Nonnull @Nonnull
private final Bus bus; final Bus bus;
@Nonnull
private final Executor ui;
@Nonnull @Nonnull
private final Executor background; private final Executor background;
@ -85,15 +78,14 @@ public class Calculator implements SharedPreferences.OnSharedPreferenceChangeLis
@Inject @Inject
Editor editor; Editor editor;
@Inject @Inject
JsclMathEngine mathEngine; Engine engine;
@Inject @Inject
ToJsclTextProcessor preprocessor; ToJsclTextProcessor preprocessor;
@Inject @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.preferences = preferences;
this.bus = bus; this.bus = bus;
this.ui = ui;
this.background = background; this.background = background;
bus.register(this); bus.register(this);
preferences.registerOnSharedPreferenceChangeListener(this); preferences.registerOnSharedPreferenceChangeListener(this);
@ -109,12 +101,6 @@ public class Calculator implements SharedPreferences.OnSharedPreferenceChangeLis
return to.toString(value); return to.toString(value);
} }
@Nonnull
private CalculatorEventData nextEventData() {
final long eventId = nextSequence();
return CalculatorEventDataImpl.newInstance(eventId, eventId);
}
public void evaluate() { public void evaluate() {
final EditorState state = editor.getState(); final EditorState state = editor.getState();
evaluate(JsclOperation.numeric, state.getTextString()); evaluate(JsclOperation.numeric, state.getTextString());
@ -143,7 +129,7 @@ public class Calculator implements SharedPreferences.OnSharedPreferenceChangeLis
} }
public void init(@Nonnull Executor init) { public void init(@Nonnull Executor init) {
Locator.getInstance().getEngine().init(init); engine.init(init);
setCalculateOnFly(Preferences.Calculations.calculateOnFly.getPreference(preferences)); setCalculateOnFly(Preferences.Calculations.calculateOnFly.getPreference(preferences));
} }
@ -180,6 +166,7 @@ public class Calculator implements SharedPreferences.OnSharedPreferenceChangeLis
pe = prepare(e); pe = prepare(e);
try { try {
final MathEngine mathEngine = engine.getMathEngine();
mathEngine.setMessageRegistry(mr); mathEngine.setMessageRegistry(mr);
final Generic result = o.evaluateGeneric(pe.value, mathEngine); final Generic result = o.evaluateGeneric(pe.value, mathEngine);
@ -188,7 +175,7 @@ public class Calculator implements SharedPreferences.OnSharedPreferenceChangeLis
//noinspection ResultOfMethodCallIgnored //noinspection ResultOfMethodCallIgnored
result.toString(); 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))); bus.post(new CalculationFinishedEvent(o, e, sequence, result, stringResult, collectMessages(mr)));
} catch (JsclArithmeticException exception) { } catch (JsclArithmeticException exception) {
@ -252,7 +239,7 @@ public class Calculator implements SharedPreferences.OnSharedPreferenceChangeLis
public void convert(@Nonnull final DisplayState state, @Nonnull final NumeralBase to) { public void convert(@Nonnull final DisplayState state, @Nonnull final NumeralBase to) {
final Generic value = state.getResult(); final Generic value = state.getResult();
Check.isNotNull(value); Check.isNotNull(value);
final NumeralBase from = mathEngine.getNumeralBase(); final NumeralBase from = engine.getMathEngine().getNumeralBase();
if (from == to) { if (from == to) {
return; 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 @Subscribe
public void onEditorChanged(@Nonnull Editor.ChangedEvent e) { public void onEditorChanged(@Nonnull Editor.ChangedEvent e) {
if (!calculateOnFly) { if (!calculateOnFly) {
@ -324,8 +293,8 @@ public class Calculator implements SharedPreferences.OnSharedPreferenceChangeLis
updateAnsVariable(text); updateAnsVariable(text);
} }
private void updateAnsVariable(@NonNull String value) { void updateAnsVariable(@NonNull String value) {
final VariablesRegistry variablesRegistry = Locator.getInstance().getEngine().getVariablesRegistry(); final VariablesRegistry variablesRegistry = engine.getVariablesRegistry();
final IConstant variable = variablesRegistry.get(Constants.ANS); final IConstant variable = variablesRegistry.get(Constants.ANS);
final CppVariable.Builder b = variable != null ? CppVariable.builder(variable) : CppVariable.builder(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); languages.updateContextLocale(this, true);
App.getGa().reportInitially(preferences); App.getGa().reportInitially(preferences);
Locator.getInstance().init(engine);
calculator.init(initThread); calculator.init(initThread);
initThread.execute(new Runnable() { 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; Plotter plotter;
@Inject @Inject
Calculator calculator; Calculator calculator;
@Inject
Engine engine;
public DisplayFragment() { public DisplayFragment() {
super(R.layout.cpp_app_display); super(R.layout.cpp_app_display);
@ -149,8 +151,7 @@ public class DisplayFragment extends BaseFragment implements View.OnClickListene
protected boolean isMenuItemVisible(@NonNull ConversionMenuItem menuItem, protected boolean isMenuItemVisible(@NonNull ConversionMenuItem menuItem,
@Nonnull Generic generic) { @Nonnull Generic generic) {
final NumeralBase fromNumeralBase = final NumeralBase fromNumeralBase = engine.getMathEngine().getNumeralBase();
Locator.getInstance().getEngine().getMathEngine().getNumeralBase();
if (fromNumeralBase != menuItem.toNumeralBase) { if (fromNumeralBase != menuItem.toNumeralBase) {
return calculator.canConvert(generic, 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; private final List<String> parameterNames;
@NonNull @NonNull
private final SimpleDragListener dragListener; private final SimpleDragListener dragListener;
@NonNull
private final String multiplicationSign = Locator.getInstance().getEngine().getMultiplicationSign();
public FloatingCalculatorKeyboard(@NonNull User user, @NonNull List<String> parameterNames) { public FloatingCalculatorKeyboard(@NonNull User user, @NonNull List<String> parameterNames) {
super(user); super(user);
@ -76,7 +74,7 @@ public class FloatingCalculatorKeyboard extends BaseFloatingKeyboard {
addButton(row, 0, "7"); addButton(row, 0, "7");
addButton(row, 0, "8"); addButton(row, 0, "8");
addButton(row, 0, "9").setText("π", up).setText("e", down); 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, "+"); addOperationButton(row, R.id.cpp_kb_button_plus, "+");
addButton(row, R.id.cpp_kb_button_clear, "C"); 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, "7");
addButton(row, 0, "8"); addButton(row, 0, "8");
addButton(row, 0, "9").setText("π", up).setText("e", down); 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"); addButton(row, R.id.cpp_kb_button_clear, "C");
row = makeRow(); row = makeRow();
@ -186,7 +184,7 @@ public class FloatingCalculatorKeyboard extends BaseFloatingKeyboard {
user.insertOperator('-'); user.insertOperator('-');
break; break;
case R.id.cpp_kb_button_multiply: case R.id.cpp_kb_button_multiply:
user.insertOperator(multiplicationSign); user.insertOperator("×");
break; break;
case R.id.cpp_kb_button_functions_constants: case R.id.cpp_kb_button_functions_constants:
user.showFunctionsConstants(v); user.showFunctionsConstants(v);

View File

@ -49,6 +49,8 @@ public class Keyboard implements SharedPreferences.OnSharedPreferenceChangeListe
@Inject @Inject
Calculator calculator; Calculator calculator;
@Inject @Inject
Engine engine;
@Inject
Lazy<Clipboard> clipboard; Lazy<Clipboard> clipboard;
@Inject @Inject
Lazy<Bus> bus; Lazy<Bus> bus;
@ -81,7 +83,7 @@ public class Keyboard implements SharedPreferences.OnSharedPreferenceChangeListe
int cursorPositionOffset = 0; int cursorPositionOffset = 0;
final StringBuilder textToBeInserted = new StringBuilder(text); final StringBuilder textToBeInserted = new StringBuilder(text);
MathType.getType(text, 0, false, mathType); MathType.getType(text, 0, false, mathType, engine);
switch (mathType.type) { switch (mathType.type) {
case function: case function:
textToBeInserted.append("()"); 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; package org.solovyev.android.calculator;
import android.text.SpannableStringBuilder; 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.MathContext;
import jscl.MathEngine; import jscl.MathEngine;
import jscl.NumeralBase; import jscl.NumeralBase;
@ -40,6 +31,12 @@ import jscl.text.DoubleParser;
import jscl.text.JsclIntegerParser; import jscl.text.JsclIntegerParser;
import jscl.text.ParseException; import jscl.text.ParseException;
import jscl.text.Parser; 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 { 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) // let's get rid of unnecessary characters (grouping separators, + after E)
final List<String> tokens = new ArrayList<String>(); 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 ) // + after E can be omitted: 10+E = 10E (NOTE: - cannot be omitted )
tokens.add("+"); tokens.add("+");
for (String groupingSeparator : tokens) { for (String groupingSeparator : tokens) {

View File

@ -22,11 +22,6 @@
package org.solovyev.android.calculator; 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.app.Application;
import android.content.ContentResolver; import android.content.ContentResolver;
import android.content.Context; import android.content.Context;
@ -39,7 +34,8 @@ import android.support.annotation.LayoutRes;
import android.support.annotation.StyleRes; import android.support.annotation.StyleRes;
import android.util.SparseArray; import android.util.SparseArray;
import android.view.ContextThemeWrapper; import android.view.ContextThemeWrapper;
import jscl.AngleUnit;
import jscl.NumeralBase;
import org.solovyev.android.Check; import org.solovyev.android.Check;
import org.solovyev.android.calculator.about.AboutActivity; import org.solovyev.android.calculator.about.AboutActivity;
import org.solovyev.android.calculator.functions.FunctionsActivity; 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.preferences.PreferencesActivity;
import org.solovyev.android.calculator.variables.VariablesActivity; import org.solovyev.android.calculator.variables.VariablesActivity;
import org.solovyev.android.calculator.wizard.WizardActivity; import org.solovyev.android.calculator.wizard.WizardActivity;
import org.solovyev.android.prefs.BooleanPreference; import org.solovyev.android.prefs.*;
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 javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.text.DecimalFormatSymbols; import java.text.DecimalFormatSymbols;
import java.util.EnumMap; import java.util.EnumMap;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import javax.annotation.Nonnull; import static org.solovyev.android.Android.isPhoneModel;
import javax.annotation.Nullable; 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 { 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

@ -40,30 +40,33 @@ public class ToJsclTextProcessor implements TextProcessor<PreparedExpression, St
@Nonnull @Nonnull
private static final Integer MAX_DEPTH = 20; private static final Integer MAX_DEPTH = 20;
@Inject
Engine engine;
@Inject @Inject
public ToJsclTextProcessor() { public ToJsclTextProcessor() {
} }
private static PreparedExpression processWithDepth(@Nonnull String s, int depth, @Nonnull List<IConstant> undefinedVars) throws ParseException { private static PreparedExpression processWithDepth(@Nonnull String s, int depth, @Nonnull List<IConstant> undefinedVars, @Nonnull Engine engine) throws ParseException {
return replaceVariables(processExpression(s).toString(), depth, undefinedVars); return replaceVariables(processExpression(s, engine).toString(), depth, undefinedVars, engine);
} }
@Nonnull @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 StringBuilder result = new StringBuilder();
final MathType.Results results = new MathType.Results(); final MathType.Results results = new MathType.Results();
MathType.Result mathTypeResult = null; MathType.Result mathTypeResult = null;
MathType.Result mathTypeBefore = 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++) { for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ' ') continue; if (s.charAt(i) == ' ') continue;
results.release(mathTypeBefore); results.release(mathTypeBefore);
mathTypeBefore = mathTypeResult == null ? null : mathTypeResult; 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); nb.process(mathTypeResult);
@ -80,7 +83,7 @@ public class ToJsclTextProcessor implements TextProcessor<PreparedExpression, St
(mathTypeBefore.type == MathType.function || mathTypeBefore.type == MathType.operator) && (mathTypeBefore.type == MathType.function || mathTypeBefore.type == MathType.operator) &&
App.find(MathType.groupSymbols, s, i) != null) { App.find(MathType.groupSymbols, s, i) != null) {
final String functionName = mathTypeBefore.match; 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) { if (function == null || function.getMinParameters() > 0) {
throw new ParseException(i, s, new CalculatorMessage(CalculatorMessages.msg_005, MessageType.error, mathTypeBefore.match)); 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 @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) { if (depth >= MAX_DEPTH) {
throw new ParseException(s, new CalculatorMessage(CalculatorMessages.msg_006, MessageType.error)); throw new ParseException(s, new CalculatorMessage(CalculatorMessages.msg_006, MessageType.error));
} else { } else {
@ -106,13 +109,13 @@ public class ToJsclTextProcessor implements TextProcessor<PreparedExpression, St
startsWithFinder.setI(i); startsWithFinder.setI(i);
int offset = 0; int offset = 0;
String functionName = App.find(MathType.function.getTokens(), startsWithFinder); String functionName = App.find(MathType.function.getTokens(engine), startsWithFinder);
if (functionName == null) { if (functionName == null) {
String operatorName = App.find(MathType.operator.getTokens(), startsWithFinder); String operatorName = App.find(MathType.operator.getTokens(engine), startsWithFinder);
if (operatorName == null) { if (operatorName == null) {
String varName = App.find(Locator.getInstance().getEngine().getVariablesRegistry().getNames(), startsWithFinder); String varName = App.find(engine.getVariablesRegistry().getNames(), startsWithFinder);
if (varName != null) { if (varName != null) {
final IConstant var = Locator.getInstance().getEngine().getVariablesRegistry().get(varName); final IConstant var = engine.getVariablesRegistry().get(varName);
if (var != null) { if (var != null) {
if (!var.isDefined()) { if (!var.isDefined()) {
undefinedVars.add(var); 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 // NOTE: append varName as JSCL engine will convert it to double if needed
result.append(varName); result.append(varName);
} else { } else {
result.append("(").append(processWithDepth(value, depth, undefinedVars)).append(")"); result.append("(").append(processWithDepth(value, depth, undefinedVars, engine)).append(")");
} }
offset = varName.length(); offset = varName.length();
} }
@ -156,6 +159,6 @@ public class ToJsclTextProcessor implements TextProcessor<PreparedExpression, St
@Override @Override
@Nonnull @Nonnull
public PreparedExpression process(@Nonnull String s) throws ParseException { 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; package org.solovyev.android.calculator.jscl;
import android.support.annotation.Nullable;
import jscl.MathEngine; import jscl.MathEngine;
import jscl.math.Generic; import jscl.math.Generic;
import jscl.text.ParseException; import jscl.text.ParseException;
import org.solovyev.android.calculator.Engine;
import org.solovyev.android.calculator.text.DummyTextProcessor; import org.solovyev.android.calculator.text.DummyTextProcessor;
import org.solovyev.android.calculator.text.FromJsclSimplifyTextProcessor; import org.solovyev.android.calculator.text.FromJsclSimplifyTextProcessor;
import org.solovyev.android.calculator.text.TextProcessor; import org.solovyev.android.calculator.text.TextProcessor;
@ -34,26 +36,44 @@ import javax.annotation.Nonnull;
public enum JsclOperation { public enum JsclOperation {
simplify, simplify {
elementary, @Nonnull
numeric; @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() { JsclOperation() {
} }
@Nonnull
abstract TextProcessor<String, Generic> makeFromProcessor(@Nonnull Engine engine);
@Nonnull @Nonnull
public TextProcessor<String, Generic> getFromProcessor() { public TextProcessor<String, Generic> getFromProcessor(@Nonnull Engine engine) {
switch (this) { if (fromProcessor == null) {
case simplify: fromProcessor = makeFromProcessor(engine);
return FromJsclSimplifyTextProcessor.instance;
case elementary:
return DummyTextProcessor.instance;
case numeric:
return FromJsclNumericTextProcessor.instance;
default:
throw new UnsupportedOperationException();
} }
return fromProcessor;
} }
@Nonnull @Nonnull

View File

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

View File

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

View File

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

View File

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

View File

@ -89,7 +89,7 @@ public class TextHighlighter implements TextProcessor<TextProcessorEditorResult,
int openGroupsCount = 0; int openGroupsCount = 0;
for (int i = 0; i < text.length(); i++) { 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); 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; package org.solovyev.android.calculator;
import android.os.Build; import android.os.Build;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.RobolectricGradleTestRunner;
@ -40,27 +37,10 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean; 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) @Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.LOLLIPOP)
@RunWith(value = RobolectricGradleTestRunner.class) @RunWith(value = RobolectricGradleTestRunner.class)
public class AndroidEditorViewTest { 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 @Test
public void testCreation() throws Exception { public void testCreation() throws Exception {
new EditorView(RuntimeEnvironment.application); 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.Before;
import org.junit.Test; import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.solovyev.android.calculator.calculations.CalculationFinishedEvent;
/** import static org.mockito.Mockito.doAnswer;
* User: Solovyev_S
* Date: 15.10.12
* Time: 12:30
*/
public class CalculatorTest extends AbstractCalculatorTest {
public class CalculatorTest extends BaseCalculatorTest {
@Override
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
super.setUp(); 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 @Test
public void testAnsVariable() throws Exception { public void testAnsVariable() throws Exception {
CalculatorTestUtils.assertEval("2", "2"); assertEval("2", "2");
CalculatorTestUtils.assertEval("2", "ans"); assertEval("2", "2");
CalculatorTestUtils.assertEval("4", "ans^2"); assertEval("2", "ans");
CalculatorTestUtils.assertEval("16", "ans^2"); assertEval("4", "ans^2");
CalculatorTestUtils.assertEval("0", "0"); assertEval("16", "ans^2");
CalculatorTestUtils.assertEval("0", "ans"); assertEval("0", "0");
CalculatorTestUtils.assertEval("3", "3"); assertEval("0", "ans");
CalculatorTestUtils.assertEval("9", "ans*ans"); assertEval("3", "3");
CalculatorTestUtils.assertError("ans*an"); assertEval("9", "ans*ans");
CalculatorTestUtils.assertEval("81", "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; package org.solovyev.android.calculator;
import android.preference.PreferenceManager; import android.content.SharedPreferences;
import jscl.JsclMathEngine;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; 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; private Editor editor;
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
super.setUp(); this.editor = new Editor(Mockito.mock(SharedPreferences.class), new Engine(new JsclMathEngine()));
this.editor = new Editor(PreferenceManager.getDefaultSharedPreferences(RuntimeEnvironment.application));
} }
@Test @Test
public void testInsert() throws Exception { public void testInsert() throws Exception {
EditorState viewState = this.editor.getState(); EditorState viewState = editor.getState();
Assert.assertEquals("", viewState.getTextString()); Assert.assertEquals("", viewState.getTextString());
Assert.assertEquals(0, viewState.selection); Assert.assertEquals(0, viewState.selection);
viewState = this.editor.insert(""); viewState = editor.insert("");
Assert.assertEquals("", viewState.getTextString()); Assert.assertEquals("", viewState.getTextString());
Assert.assertEquals(0, viewState.selection); Assert.assertEquals(0, viewState.selection);
viewState = this.editor.insert("test"); viewState = editor.insert("test");
Assert.assertEquals("test", viewState.getTextString()); Assert.assertEquals("test", viewState.getTextString());
Assert.assertEquals(4, viewState.selection); Assert.assertEquals(4, viewState.selection);
viewState = this.editor.insert("test"); viewState = editor.insert("test");
Assert.assertEquals("testtest", viewState.getTextString()); Assert.assertEquals("testtest", viewState.getTextString());
Assert.assertEquals(8, viewState.selection); Assert.assertEquals(8, viewState.selection);
viewState = this.editor.insert(""); viewState = editor.insert("");
Assert.assertEquals("testtest", viewState.getTextString()); Assert.assertEquals("testtest", viewState.getTextString());
Assert.assertEquals(8, viewState.selection); Assert.assertEquals(8, viewState.selection);
viewState = this.editor.insert("1234567890"); viewState = editor.insert("1234567890");
Assert.assertEquals("testtest1234567890", viewState.getTextString()); Assert.assertEquals("testtest1234567890", viewState.getTextString());
Assert.assertEquals(18, viewState.selection); Assert.assertEquals(18, viewState.selection);
viewState = this.editor.moveCursorLeft(); editor.moveCursorLeft();
viewState = this.editor.insert("9"); viewState = editor.insert("9");
Assert.assertEquals("testtest12345678990", viewState.getTextString()); Assert.assertEquals("testtest12345678990", viewState.getTextString());
Assert.assertEquals(18, viewState.selection); Assert.assertEquals(18, viewState.selection);
viewState = this.editor.setCursorOnStart(); editor.setCursorOnStart();
viewState = this.editor.insert("9"); viewState = editor.insert("9");
Assert.assertEquals("9testtest12345678990", viewState.getTextString()); Assert.assertEquals("9testtest12345678990", viewState.getTextString());
Assert.assertEquals(1, viewState.selection); Assert.assertEquals(1, viewState.selection);
viewState = this.editor.erase(); editor.erase();
viewState = this.editor.insert("9"); viewState = editor.insert("9");
Assert.assertEquals("9testtest12345678990", viewState.getTextString()); Assert.assertEquals("9testtest12345678990", viewState.getTextString());
Assert.assertEquals(1, viewState.selection); Assert.assertEquals(1, viewState.selection);
viewState = this.editor.insert("öäü"); viewState = editor.insert("öäü");
Assert.assertEquals("9öäütesttest12345678990", viewState.getTextString()); Assert.assertEquals("9öäütesttest12345678990", viewState.getTextString());
this.editor.setCursorOnEnd(); editor.setCursorOnEnd();
viewState = this.editor.insert("öäü"); viewState = editor.insert("öäü");
Assert.assertEquals("9öäütesttest12345678990öäü", viewState.getTextString()); Assert.assertEquals("9öäütesttest12345678990öäü", viewState.getTextString());
} }
@Test @Test
public void testErase() throws Exception { public void testErase() throws Exception {
this.editor.setText(""); editor.setText("");
this.editor.erase(); editor.erase();
Assert.assertEquals("", this.editor.getState().getTextString()); Assert.assertEquals("", editor.getState().getTextString());
this.editor.setText("test"); editor.setText("test");
this.editor.erase(); editor.erase();
Assert.assertEquals("tes", this.editor.getState().getTextString()); Assert.assertEquals("tes", editor.getState().getTextString());
this.editor.erase(); editor.erase();
Assert.assertEquals("te", this.editor.getState().getTextString()); Assert.assertEquals("te", editor.getState().getTextString());
this.editor.erase(); editor.erase();
Assert.assertEquals("t", this.editor.getState().getTextString()); Assert.assertEquals("t", editor.getState().getTextString());
this.editor.erase(); editor.erase();
Assert.assertEquals("", this.editor.getState().getTextString()); Assert.assertEquals("", editor.getState().getTextString());
this.editor.erase(); editor.erase();
Assert.assertEquals("", this.editor.getState().getTextString()); Assert.assertEquals("", editor.getState().getTextString());
this.editor.setText("1234"); editor.setText("1234");
this.editor.moveCursorLeft(); editor.moveCursorLeft();
this.editor.erase(); editor.erase();
Assert.assertEquals("124", this.editor.getState().getTextString()); Assert.assertEquals("124", editor.getState().getTextString());
this.editor.erase(); editor.erase();
Assert.assertEquals("14", this.editor.getState().getTextString()); Assert.assertEquals("14", editor.getState().getTextString());
this.editor.erase(); editor.erase();
Assert.assertEquals("4", this.editor.getState().getTextString()); Assert.assertEquals("4", editor.getState().getTextString());
this.editor.setText("1"); editor.setText("1");
this.editor.moveCursorLeft(); editor.moveCursorLeft();
this.editor.erase(); editor.erase();
Assert.assertEquals("1", this.editor.getState().getTextString()); Assert.assertEquals("1", editor.getState().getTextString());
} }
@Test @Test
public void testMoveSelection() throws Exception { 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); Assert.assertEquals(0, viewState.selection);
viewState = this.editor.moveSelection(2); viewState = editor.moveSelection(2);
Assert.assertEquals(0, viewState.selection); Assert.assertEquals(0, viewState.selection);
viewState = this.editor.moveSelection(100); viewState = editor.moveSelection(100);
Assert.assertEquals(0, viewState.selection); Assert.assertEquals(0, viewState.selection);
viewState = this.editor.moveSelection(-3); viewState = editor.moveSelection(-3);
Assert.assertEquals(0, viewState.selection); Assert.assertEquals(0, viewState.selection);
viewState = this.editor.moveSelection(-100); viewState = editor.moveSelection(-100);
Assert.assertEquals(0, viewState.selection); 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); Assert.assertEquals(10, viewState.selection);
viewState = this.editor.moveSelection(1); viewState = editor.moveSelection(1);
Assert.assertEquals(10, viewState.selection); Assert.assertEquals(10, viewState.selection);
viewState = this.editor.moveSelection(-2); viewState = editor.moveSelection(-2);
Assert.assertEquals(8, viewState.selection); Assert.assertEquals(8, viewState.selection);
viewState = this.editor.moveSelection(1); viewState = editor.moveSelection(1);
Assert.assertEquals(9, viewState.selection); Assert.assertEquals(9, viewState.selection);
viewState = this.editor.moveSelection(-9); viewState = editor.moveSelection(-9);
Assert.assertEquals(0, viewState.selection); Assert.assertEquals(0, viewState.selection);
viewState = this.editor.moveSelection(-10); viewState = editor.moveSelection(-10);
Assert.assertEquals(0, viewState.selection); Assert.assertEquals(0, viewState.selection);
viewState = this.editor.moveSelection(2); viewState = editor.moveSelection(2);
Assert.assertEquals(2, viewState.selection); Assert.assertEquals(2, viewState.selection);
viewState = this.editor.moveSelection(2); viewState = editor.moveSelection(2);
Assert.assertEquals(4, viewState.selection); Assert.assertEquals(4, viewState.selection);
viewState = this.editor.moveSelection(-6); viewState = editor.moveSelection(-6);
Assert.assertEquals(0, viewState.selection); Assert.assertEquals(0, viewState.selection);
} }
@Test @Test
public void testSetText() throws Exception { public void testSetText() throws Exception {
EditorState viewState = this.editor.setText("test"); EditorState viewState = editor.setText("test");
Assert.assertEquals("test", viewState.getTextString()); Assert.assertEquals("test", viewState.getTextString());
Assert.assertEquals(4, viewState.selection); Assert.assertEquals(4, viewState.selection);
viewState = this.editor.setText("testtest"); viewState = editor.setText("testtest");
Assert.assertEquals("testtest", viewState.getTextString()); Assert.assertEquals("testtest", viewState.getTextString());
Assert.assertEquals(8, viewState.selection); Assert.assertEquals(8, viewState.selection);
viewState = this.editor.setText(""); viewState = editor.setText("");
Assert.assertEquals("", viewState.getTextString()); Assert.assertEquals("", viewState.getTextString());
Assert.assertEquals(0, viewState.selection); Assert.assertEquals(0, viewState.selection);
viewState = this.editor.setText("testtest", 0); viewState = editor.setText("testtest", 0);
Assert.assertEquals("testtest", viewState.getTextString()); Assert.assertEquals("testtest", viewState.getTextString());
Assert.assertEquals(0, viewState.selection); Assert.assertEquals(0, viewState.selection);
viewState = this.editor.setText("testtest", 2); viewState = editor.setText("testtest", 2);
Assert.assertEquals("testtest", viewState.getTextString()); Assert.assertEquals("testtest", viewState.getTextString());
Assert.assertEquals(2, viewState.selection); Assert.assertEquals(2, viewState.selection);
viewState = this.editor.setText("", 0); viewState = editor.setText("", 0);
Assert.assertEquals("", viewState.getTextString()); Assert.assertEquals("", viewState.getTextString());
Assert.assertEquals(0, viewState.selection); Assert.assertEquals(0, viewState.selection);
viewState = this.editor.setText("", 3); viewState = editor.setText("", 3);
Assert.assertEquals("", viewState.getTextString()); Assert.assertEquals("", viewState.getTextString());
Assert.assertEquals(0, viewState.selection); Assert.assertEquals(0, viewState.selection);
viewState = this.editor.setText("", -3); viewState = editor.setText("", -3);
Assert.assertEquals("", viewState.getTextString()); Assert.assertEquals("", viewState.getTextString());
Assert.assertEquals(0, viewState.selection); Assert.assertEquals(0, viewState.selection);
viewState = this.editor.setText("test"); viewState = editor.setText("test");
Assert.assertEquals("test", viewState.getTextString()); Assert.assertEquals("test", viewState.getTextString());
Assert.assertEquals(4, viewState.selection); Assert.assertEquals(4, viewState.selection);
viewState = this.editor.setText("", 2); viewState = editor.setText("", 2);
Assert.assertEquals("", viewState.getTextString()); Assert.assertEquals("", viewState.getTextString());
Assert.assertEquals(0, viewState.selection); Assert.assertEquals(0, viewState.selection);
} }

View File

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

View File

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

View File

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

View File

@ -2,6 +2,7 @@ package org.solovyev.android.calculator;
import android.content.Intent; import android.content.Intent;
import android.os.Build; import android.os.Build;
import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mockito; import org.mockito.Mockito;
@ -18,26 +19,31 @@ import static org.solovyev.android.calculator.WidgetReceiver.*;
@RunWith(RobolectricGradleTestRunner.class) @RunWith(RobolectricGradleTestRunner.class)
public class WidgetReceiverTest { public class WidgetReceiverTest {
private WidgetReceiver widgetReceiver;
@Before
public void setUp() throws Exception {
widgetReceiver.keyboard = Mockito.mock(Keyboard.class);
}
@Test @Test
public void testShouldPressButtonOnIntent() throws Exception { public void testShouldPressButtonOnIntent() throws Exception {
//Locator.setKeyboard(mock(Keyboard.class));
final Intent intent = newButtonClickedIntent(application, four); 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(widgetReceiver.keyboard, times(1)).buttonPressed(Mockito.anyString());
verify(Locator.getInstance().getKeyboard(), times(1)).buttonPressed("4"); verify(widgetReceiver.keyboard, times(1)).buttonPressed("4");
} }
@Test @Test
public void testShouldDoNothingIfButtonInvalid() throws Exception { public void testShouldDoNothingIfButtonInvalid() throws Exception {
//Locator.setKeyboard(mock(Keyboard.class));
final Intent intent = new Intent(application, WidgetReceiver.class); final Intent intent = new Intent(application, WidgetReceiver.class);
intent.setAction(ACTION_BUTTON_PRESSED); intent.setAction(ACTION_BUTTON_PRESSED);
intent.putExtra(ACTION_BUTTON_ID_EXTRA, "test!@"); 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; 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.AngleUnit;
import jscl.JsclMathEngine; import jscl.JsclMathEngine;
import jscl.math.Expression; import jscl.math.Expression;
import jscl.math.Generic; import jscl.math.Generic;
import org.junit.Test;
/** import static org.junit.Assert.assertEquals;
* User: serso
* Date: 10/18/11
* Time: 10:42 PM
*/
public class FromJsclNumericTextProcessorTest extends AbstractCalculatorTest {
@BeforeClass public class FromJsclNumericTextProcessorTest {
public static void staticSetUp() throws Exception {
CalculatorTestUtils.staticSetUp();
}
@Test @Test
public void testCreateResultForComplexNumber() throws Exception { public void testCreateResultForComplexNumber() throws Exception {
@ -52,18 +39,18 @@ public class FromJsclNumericTextProcessorTest extends AbstractCalculatorTest {
final JsclMathEngine me = JsclMathEngine.getInstance(); final JsclMathEngine me = JsclMathEngine.getInstance();
final AngleUnit defaultAngleUnits = me.getAngleUnits(); final AngleUnit defaultAngleUnits = me.getAngleUnits();
Assert.assertEquals("1.22133+23 123i", cm.process(Expression.valueOf("1.22133232+23123*i").numeric())); 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())); 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+0i", cm.process(Expression.valueOf("1.22133232+0.000000001*i").numeric()));
try { try {
me.setAngleUnits(AngleUnit.rad); 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 { } finally {
me.setAngleUnits(defaultAngleUnits); me.setAngleUnits(defaultAngleUnits);
} }
Assert.assertEquals("1.22i", cm.process(Expression.valueOf("1.22*i").numeric())); assertEquals("1.22i", cm.process(Expression.valueOf("1.22*i").numeric()));
Assert.assertEquals("i", cm.process(Expression.valueOf("i").numeric())); assertEquals("i", cm.process(Expression.valueOf("i").numeric()));
Generic numeric = Expression.valueOf("e^(Π*i)+1").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; package org.solovyev.android.calculator.math;
import jscl.JsclMathEngine;
import org.junit.Assert; import org.junit.Assert;
import org.junit.BeforeClass; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.solovyev.android.calculator.AbstractCalculatorTest; import org.solovyev.android.calculator.Engine;
import org.solovyev.android.calculator.CalculatorTestUtils;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.solovyev.android.calculator.math.MathType.postfix_function; import static org.solovyev.android.calculator.math.MathType.postfix_function;
/** public class MathTypeTest {
* User: serso
* Date: 10/5/11
* Time: 1:25 AM
*/
public class MathTypeTest extends AbstractCalculatorTest {
@BeforeClass Engine engine;
public static void staticSetUp() throws Exception {
CalculatorTestUtils.staticSetUp(); @Before
public void setUp() throws Exception {
engine = new Engine(new JsclMathEngine());
} }
@Test @Test
public void testGetType() throws Exception { public void testGetType() throws Exception {
assertEquals(MathType.function, MathType.getType("sin", 0, false).type); assertEquals(MathType.function, MathType.getType("sin", 0, false, engine).type);
assertEquals(MathType.text, MathType.getType("sn", 0, false).type); assertEquals(MathType.text, MathType.getType("sn", 0, false, engine).type);
assertEquals(MathType.text, MathType.getType("s", 0, false).type); assertEquals(MathType.text, MathType.getType("s", 0, false, engine).type);
assertEquals(MathType.text, MathType.getType("", 0, false).type); assertEquals(MathType.text, MathType.getType("", 0, false, engine).type);
try { try {
assertEquals(MathType.text, MathType.getType("22", -1, false).type); assertEquals(MathType.text, MathType.getType("22", -1, false, engine).type);
Assert.fail(); Assert.fail();
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
} }
try { try {
assertEquals(MathType.text, MathType.getType("22", 2, false).type); assertEquals(MathType.text, MathType.getType("22", 2, false, engine).type);
Assert.fail(); Assert.fail();
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
} }
assertEquals("atanh", MathType.getType("atanh", 0, false).match); assertEquals("atanh", MathType.getType("atanh", 0, false, engine).match);
} }
@Test @Test
public void testPostfixFunctionsProcessing() throws Exception { public void testPostfixFunctionsProcessing() throws Exception {
assertEquals(postfix_function, MathType.getType("5!", 1, false).type); assertEquals(postfix_function, MathType.getType("5!", 1, false, engine).type);
assertEquals(postfix_function, MathType.getType("!", 0, false).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.math.function.CustomFunction;
import jscl.text.ParseException; import jscl.text.ParseException;
import junit.framework.Assert; import junit.framework.Assert;
import org.junit.BeforeClass; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.solovyev.android.calculator.AbstractCalculatorTest; import org.solovyev.android.calculator.BaseCalculatorTest;
import org.solovyev.android.calculator.CalculatorTestUtils;
import org.solovyev.android.calculator.Locator;
import org.solovyev.android.calculator.jscl.JsclOperation; import org.solovyev.android.calculator.jscl.JsclOperation;
import org.solovyev.android.calculator.variables.CppVariable; import org.solovyev.android.calculator.variables.CppVariable;
@ -43,57 +41,45 @@ import java.util.Locale;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
public class AndroidEngineTest extends BaseCalculatorTest {
/** @Before
* User: serso public void setUp() throws Exception {
* Date: 9/17/11 super.setUp();
* Time: 9:47 PM engine.getMathEngine().setPrecision(3);
*/
@SuppressWarnings("deprecation")
public class AndroidEngineTest extends AbstractCalculatorTest {
@BeforeClass
public static void staticSetUp() throws Exception {
CalculatorTestUtils.staticSetUp();
Locator.getInstance().getEngine().getMathEngine().setPrecision(3);
} }
@Test @Test
public void testDegrees() throws Exception { public void testDegrees() throws Exception {
final MathEngine cm = Locator.getInstance().getEngine().getMathEngine(); final MathEngine me = engine.getMathEngine();
final AngleUnit defaultAngleUnit = me.getAngleUnits();
final AngleUnit defaultAngleUnit = cm.getAngleUnits();
try { try {
cm.setAngleUnits(AngleUnit.rad); me.setAngleUnits(AngleUnit.rad);
cm.setPrecision(3); me.setPrecision(3);
CalculatorTestUtils.assertError("°"); assertError("°");
CalculatorTestUtils.assertEval("0.017", ""); assertEval("0.017", "");
CalculatorTestUtils.assertEval("0.349", "20.0°"); assertEval("0.349", "20.0°");
CalculatorTestUtils.assertEval("0.5", "sin(30°)"); assertEval("0.5", "sin(30°)");
CalculatorTestUtils.assertEval("0.524", "asin(sin(30°))"); assertEval("0.524", "asin(sin(30°))");
CalculatorTestUtils.assertEval("∂(cos(t), t, t, 1°)", "∂(cos(t),t,t,1°)"); 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 { } finally {
cm.setAngleUnits(defaultAngleUnit); me.setAngleUnits(defaultAngleUnit);
} }
} }
@Test @Test
public void testFormatting() throws Exception { public void testFormatting() throws Exception {
final MathEngine ce = Locator.getInstance().getEngine().getMathEngine(); final MathEngine me = engine.getMathEngine();
assertEval("12 345", me.simplify("12345"));
CalculatorTestUtils.assertEval("12 345", ce.simplify("12345"));
} }
@Test @Test
public void testI() throws ParseException { 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++) { for (int i = 0; i < 1000; i++) {
double real = (Math.random() - 0.5) * 1000; double real = (Math.random() - 0.5) * 1000;
double imag = (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(imag);
sb.append("^").append(exp); sb.append("^").append(exp);
try { try {
cm.evaluate(sb.toString()); me.evaluate(sb.toString());
} catch (Throwable e) { } catch (Throwable e) {
fail(sb.toString()); fail(sb.toString());
} }
@ -116,101 +102,101 @@ public class AndroidEngineTest extends AbstractCalculatorTest {
@Test @Test
public void testEmptyFunction() throws Exception { public void testEmptyFunction() throws Exception {
final MathEngine cm = Locator.getInstance().getEngine().getMathEngine(); final MathEngine me = engine.getMathEngine();
try { 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(); 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 { 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(); Assert.fail();
} catch (ParseException e) { } catch (ParseException ignored) {
} }
final AngleUnit defaultAngleUnit = cm.getAngleUnits(); final AngleUnit defaultAngleUnit = me.getAngleUnits();
try { try {
cm.setAngleUnits(AngleUnit.rad); me.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))))))))))))))))))))))))))))))))))))")); 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 { } finally {
cm.setAngleUnits(defaultAngleUnit); me.setAngleUnits(defaultAngleUnit);
} }
Locator.getInstance().getEngine().getVariablesRegistry().add(CppVariable.builder("si").withValue(5d).build().toJsclBuilder()); engine.getVariablesRegistry().add(CppVariable.builder("si").withValue(5d).build().toJsclBuilder());
CalculatorTestUtils.assertEval("5", cm.evaluate("si")); assertEval("5", me.evaluate("si"));
CalculatorTestUtils.assertError("sin"); assertError("sin");
} }
@Test @Test
public void testRounding() throws Exception { public void testRounding() throws Exception {
final MathEngine cm = Locator.getInstance().getEngine().getMathEngine(); final MathEngine me = engine.getMathEngine();
try { try {
DecimalFormatSymbols decimalGroupSymbols = new DecimalFormatSymbols(Locale.getDefault()); DecimalFormatSymbols decimalGroupSymbols = new DecimalFormatSymbols(Locale.getDefault());
decimalGroupSymbols.setDecimalSeparator('.'); decimalGroupSymbols.setDecimalSeparator('.');
decimalGroupSymbols.setGroupingSeparator('\''); decimalGroupSymbols.setGroupingSeparator('\'');
cm.setDecimalGroupSymbols(decimalGroupSymbols); me.setDecimalGroupSymbols(decimalGroupSymbols);
cm.setPrecision(2); me.setPrecision(2);
CalculatorTestUtils.assertEval("12'345'678.9", cm.evaluate("1.23456789E7")); assertEval("12'345'678.9", me.evaluate("1.23456789E7"));
cm.setPrecision(10); me.setPrecision(10);
CalculatorTestUtils.assertEval("12'345'678.9", cm.evaluate("1.23456789E7")); assertEval("12'345'678.9", me.evaluate("1.23456789E7"));
CalculatorTestUtils.assertEval("123'456'789", cm.evaluate("1.234567890E8")); assertEval("123'456'789", me.evaluate("1.234567890E8"));
CalculatorTestUtils.assertEval("1'234'567'890.1", cm.evaluate("1.2345678901E9")); assertEval("1'234'567'890.1", me.evaluate("1.2345678901E9"));
} finally { } finally {
cm.setPrecision(3); me.setPrecision(3);
DecimalFormatSymbols decimalGroupSymbols = new DecimalFormatSymbols(Locale.getDefault()); DecimalFormatSymbols decimalGroupSymbols = new DecimalFormatSymbols(Locale.getDefault());
decimalGroupSymbols.setDecimalSeparator('.'); decimalGroupSymbols.setDecimalSeparator('.');
decimalGroupSymbols.setGroupingSeparator(JsclMathEngine.GROUPING_SEPARATOR_DEFAULT.charAt(0)); decimalGroupSymbols.setGroupingSeparator(JsclMathEngine.GROUPING_SEPARATOR_DEFAULT.charAt(0));
cm.setDecimalGroupSymbols(decimalGroupSymbols); me.setDecimalGroupSymbols(decimalGroupSymbols);
} }
} }
@Test @Test
public void testNumeralSystems() throws Exception { public void testNumeralSystems() throws Exception {
final MathEngine cm = Locator.getInstance().getEngine().getMathEngine(); final MathEngine me = engine.getMathEngine();
CalculatorTestUtils.assertEval("11 259 375", "0x:ABCDEF"); assertEval("11 259 375", "0x:ABCDEF");
CalculatorTestUtils.assertEval("30 606 154.462", "0x:ABCDEF*e"); assertEval("30 606 154.462", "0x:ABCDEF*e");
CalculatorTestUtils.assertEval("30 606 154.462", "e*0x:ABCDEF"); assertEval("30 606 154.462", "e*0x:ABCDEF");
CalculatorTestUtils.assertEval("e", "e*0x:ABCDEF/0x:ABCDEF"); assertEval("e", "e*0x:ABCDEF/0x:ABCDEF");
CalculatorTestUtils.assertEval("30 606 154.462", "0x:ABCDEF*e*0x:ABCDEF/0x:ABCDEF"); 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"); 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) "); assertEval("1 446 257 064 651.832", "28*28 * sin(28) - 0b:1101 + √(28) + exp ( 28) ");
CalculatorTestUtils.assertEval("13", "0b:1101"); assertEval("13", "0b:1101");
CalculatorTestUtils.assertError("0b:π"); assertError("0b:π");
final NumeralBase defaultNumeralBase = cm.getNumeralBase(); final NumeralBase defaultNumeralBase = me.getNumeralBase();
try { try {
cm.setNumeralBase(NumeralBase.bin); me.setNumeralBase(NumeralBase.bin);
CalculatorTestUtils.assertEval("101", "10+11"); assertEval("101", "10+11");
CalculatorTestUtils.assertEval("0.101", "10/11"); assertEval("0.101", "10/11");
cm.setNumeralBase(NumeralBase.hex); me.setNumeralBase(NumeralBase.hex);
CalculatorTestUtils.assertEval("63 7B", "56CE+CAD"); assertEval("63 7B", "56CE+CAD");
CalculatorTestUtils.assertEval("E", "E"); assertEval("E", "E");
} finally { } finally {
cm.setNumeralBase(defaultNumeralBase); me.setNumeralBase(defaultNumeralBase);
} }
} }
@Test @Test
public void testLog() throws Exception { 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()); assertEval("", Expression.valueOf("1/0").numeric().toString());
CalculatorTestUtils.assertEval("", Expression.valueOf("ln(10)/ln(1)").numeric().toString()); assertEval("", Expression.valueOf("ln(10)/ln(1)").numeric().toString());
// logarithm // logarithm
CalculatorTestUtils.assertEval("ln(x)/ln(base)", ((CustomFunction) cm.getFunctionsRegistry().get("log")).getContent()); assertEval("ln(x)/ln(base)", ((CustomFunction) me.getFunctionsRegistry().get("log")).getContent());
CalculatorTestUtils.assertEval("", "log(1, 10)"); assertEval("", "log(1, 10)");
CalculatorTestUtils.assertEval("3.322", "log(2, 10)"); assertEval("3.322", "log(2, 10)");
CalculatorTestUtils.assertEval("1.431", "log(5, 10)"); assertEval("1.431", "log(5, 10)");
CalculatorTestUtils.assertEval("0.96", "log(11, 10)"); assertEval("0.96", "log(11, 10)");
CalculatorTestUtils.assertEval("1/(bln(a))", "∂(log(a, b), b)", JsclOperation.simplify); 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(b)/(aln(a)^2)", "∂(log(a, b), a)", JsclOperation.simplify);
} }
} }

View File

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

View File

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

View File

@ -29,7 +29,6 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.simpleframework.xml.Serializer; import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister; 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.OldFunction;
import org.solovyev.android.calculator.functions.OldFunctions; import org.solovyev.android.calculator.functions.OldFunctions;
import org.solovyev.common.Objects; import org.solovyev.common.Objects;
@ -87,11 +86,6 @@ public class OldFunctionsTest {
" </functions>\n" + " </functions>\n" +
"</functions>"; "</functions>";
@Before
public void setUp() throws Exception {
CalculatorTestUtils.staticSetUp();
}
@Nonnull @Nonnull
private OldFunctions testXml(@Nonnull OldFunctions in, @Nullable String expectedXml) throws Exception { private OldFunctions testXml(@Nonnull OldFunctions in, @Nullable String expectedXml) throws Exception {
final String actualXml = toXml(in); 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.junit.Assert.assertTrue;
import static org.mockito.Mockito.times; import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.solovyev.android.calculator.CalculatorTestUtils.staticSetUp;
@Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.LOLLIPOP) @Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.LOLLIPOP)
@RunWith(RobolectricGradleTestRunner.class) @RunWith(RobolectricGradleTestRunner.class)
@ -37,8 +36,6 @@ public class AngleUnitsButtonTest {
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
staticSetUp();
final Activity context = Robolectric.buildActivity(Activity.class).create().get(); final Activity context = Robolectric.buildActivity(Activity.class).create().get();
final ShadowActivity activity = Shadows.shadowOf(context); final ShadowActivity activity = Shadows.shadowOf(context);
button = new AngleUnitsButton(context, activity.createAttributeSet(new ArrayList<Attribute>(), AngleUnitsButton.class)); 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.junit.Assert.assertTrue;
import static org.mockito.Mockito.times; import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.solovyev.android.calculator.CalculatorTestUtils.staticSetUp;
@Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.LOLLIPOP) @Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.LOLLIPOP)
@RunWith(RobolectricGradleTestRunner.class) @RunWith(RobolectricGradleTestRunner.class)
@ -37,8 +36,6 @@ public class NumeralBasesButtonTest {
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
staticSetUp();
final Activity context = Robolectric.buildActivity(Activity.class).create().get(); final Activity context = Robolectric.buildActivity(Activity.class).create().get();
final ShadowActivity activity = Shadows.shadowOf(context); final ShadowActivity activity = Shadows.shadowOf(context);
button = new NumeralBasesButton(context, activity.createAttributeSet(new ArrayList<Attribute>(), NumeralBasesButton.class)); button = new NumeralBasesButton(context, activity.createAttributeSet(new ArrayList<Attribute>(), NumeralBasesButton.class));

View File

@ -41,7 +41,7 @@ public class JsclMathEngine implements MathEngine {
@Nonnull @Nonnull
private NumeralBase numeralBase = DEFAULT_NUMERAL_BASE; private NumeralBase numeralBase = DEFAULT_NUMERAL_BASE;
@Nonnull @Nonnull
private ConstantsRegistry constantsRegistry; private final ConstantsRegistry constantsRegistry = new ConstantsRegistry();
@Nonnull @Nonnull
private MessageRegistry messageRegistry = Messages.synchronizedMessageRegistry(new FixedCapacityListMessageRegistry(10)); private MessageRegistry messageRegistry = Messages.synchronizedMessageRegistry(new FixedCapacityListMessageRegistry(10));
@ -50,8 +50,7 @@ public class JsclMathEngine implements MathEngine {
decimalGroupSymbols.setGroupingSeparator(GROUPING_SEPARATOR_DEFAULT.charAt(0)); decimalGroupSymbols.setGroupingSeparator(GROUPING_SEPARATOR_DEFAULT.charAt(0));
} }
private JsclMathEngine() { public JsclMathEngine() {
this.constantsRegistry = new ConstantsRegistry();
} }
@Nonnull @Nonnull
@ -176,7 +175,7 @@ public class JsclMathEngine implements MathEngine {
if (name.equals(Constants.PI_INV.getName()) || name.equals(Constants.ANS)) { if (name.equals(Constants.PI_INV.getName()) || name.equals(Constants.ANS)) {
return false; 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.MathEngine;
import jscl.text.ParseException; import jscl.text.ParseException;
import jscl.text.msg.Messages; import jscl.text.msg.Messages;
import junit.framework.Assert;
import org.junit.Test; import org.junit.Test;
/** import static org.junit.Assert.assertEquals;
* User: serso import static org.junit.Assert.fail;
* Date: 12/15/11
* Time: 10:41 PM
*/
public class DoubleFactorialTest { public class DoubleFactorialTest {
@Test @Test
public void testDoubleFactorial() throws Exception { public void testDoubleFactorial() throws Exception {
final MathEngine me = JsclMathEngine.getInstance(); final MathEngine me = JsclMathEngine.getInstance();
Assert.assertEquals("1", me.evaluate("0!")); assertEquals("1", me.evaluate("0!"));
Assert.assertEquals("1", me.evaluate("1!")); assertEquals("1", me.evaluate("1!"));
Assert.assertEquals("2", me.evaluate("2!")); assertEquals("2", me.evaluate("2!"));
Assert.assertEquals("6", me.evaluate("3!")); assertEquals("6", me.evaluate("3!"));
Assert.assertEquals("24", me.evaluate("4!")); assertEquals("24", me.evaluate("4!"));
try { try {
me.evaluate("(-1)!!"); me.evaluate("(-1)!!");
Assert.fail(); fail();
} catch (ArithmeticException e) { } catch (ArithmeticException e) {
// ok // ok
} }
Assert.assertEquals("-1", me.evaluate("-1!!")); assertEquals("-1", me.evaluate("-1!!"));
Assert.assertEquals("1", me.evaluate("0!!")); assertEquals("1", me.evaluate("0!!"));
Assert.assertEquals("1", me.evaluate("1!!")); assertEquals("1", me.evaluate("1!!"));
Assert.assertEquals("2", me.evaluate("2!!")); assertEquals("2", me.evaluate("2!!"));
Assert.assertEquals("2", me.evaluate("(2!!)!")); assertEquals("2", me.evaluate("(2!!)!"));
Assert.assertEquals("2", me.evaluate("(2!)!!")); assertEquals("2", me.evaluate("(2!)!!"));
Assert.assertEquals("3", me.evaluate("3!!")); assertEquals("3", me.evaluate("3!!"));
Assert.assertEquals("48", me.evaluate("(3!)!!")); assertEquals("48", me.evaluate("(3!)!!"));
Assert.assertEquals("6", me.evaluate("(3!!)!")); assertEquals("6", me.evaluate("(3!!)!"));
Assert.assertEquals("8", me.evaluate("4!!")); assertEquals("8", me.evaluate("4!!"));
Assert.assertEquals("15", me.evaluate("5!!")); assertEquals("15", me.evaluate("5!!"));
Assert.assertEquals("48", me.evaluate("6!!")); assertEquals("48", me.evaluate("6!!"));
Assert.assertEquals("105", me.evaluate("7!!")); assertEquals("105", me.evaluate("7!!"));
Assert.assertEquals("384", me.evaluate("8!!")); assertEquals("384", me.evaluate("8!!"));
Assert.assertEquals("945", me.evaluate("9!!")); assertEquals("945", me.evaluate("9!!"));
try { try {
me.evaluate("9!!!"); me.evaluate("9!!!");
Assert.fail(); fail();
} catch (ParseException e) { } catch (ParseException e) {
if (Messages.msg_18.equals(e.getMessageCode())) { if (Messages.msg_18.equals(e.getMessageCode())) {
// ok // ok
} else { } else {
Assert.fail(); fail();
} }
} }