Revert recent changes, see dev branch

This commit is contained in:
serso 2012-09-21 10:38:07 +04:00
parent cca775c2ac
commit db9b676cfa
89 changed files with 2161 additions and 3776 deletions

View File

@ -1,46 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.solovyev.android</groupId>
<artifactId>calculatorpp-parent</artifactId>
<version>1.3.1</version>
</parent>
<groupId>org.solovyev.android</groupId>
<artifactId>calculatorpp-core</artifactId>
<version>1.3.1</version>
<name>Calculator++ Application Core</name>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.intellij</groupId>
<artifactId>annotations</artifactId>
</dependency>
<dependency>
<groupId>org.solovyev</groupId>
<artifactId>jscl</artifactId>
</dependency>
<dependency>
<groupId>org.simpleframework</groupId>
<artifactId>simple-xml</artifactId>
</dependency>
</dependencies>
</project>

View File

@ -1,25 +0,0 @@
package org.solovyev.android.calculator;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.jscl.JsclOperation;
import org.solovyev.common.msg.MessageRegistry;
/**
* User: Solovyev_S
* Date: 20.09.12
* Time: 16:38
*/
public interface Calculator extends CalculatorEventContainer {
@NotNull
CalculatorEventDataId createFirstEventDataId();
void evaluate(@NotNull JsclOperation operation,
@NotNull String expression);
@NotNull
CalculatorEventDataId evaluate(@NotNull JsclOperation operation,
@NotNull String expression,
@Nullable MessageRegistry mr);
}

View File

@ -1,28 +0,0 @@
/*
* Copyright (c) 2009-2011. Created by serso aka se.solovyev.
* For more information, please, contact se.solovyev@gmail.com
* or visit http://se.solovyev.org
*/
package org.solovyev.android.calculator;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* User: serso
* Date: 12/17/11
* Time: 9:45 PM
*/
public interface CalculatorDisplay extends CalculatorEventListener {
void setView(@Nullable CalculatorDisplayView view);
@NotNull
CalculatorDisplayViewState getViewState();
void setViewState(@NotNull CalculatorDisplayViewState viewState);
@NotNull
CalculatorEventData getLastEventData();
}

View File

@ -1,147 +0,0 @@
package org.solovyev.android.calculator;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import static org.solovyev.android.calculator.CalculatorEventType.*;
/**
* User: serso
* Date: 9/20/12
* Time: 8:24 PM
*/
public class CalculatorDisplayImpl implements CalculatorDisplay {
@NotNull
private CalculatorEventData lastCalculatorEventData = CalculatorEventDataImpl.newInstance(CalculatorLocatorImpl.getInstance().getCalculator().createFirstEventDataId());
@Nullable
private CalculatorDisplayView view;
@NotNull
private final Object viewLock = new Object();
@NotNull
private CalculatorDisplayViewState lastViewState = CalculatorDisplayViewStateImpl.newDefaultInstance();
@Override
public void setView(@Nullable CalculatorDisplayView view) {
synchronized (viewLock) {
this.view = view;
if (view != null) {
this.view.setState(lastViewState);
}
}
}
@NotNull
@Override
public CalculatorDisplayViewState getViewState() {
return this.lastViewState;
}
@Override
public void setViewState(@NotNull CalculatorDisplayViewState viewState) {
synchronized (viewLock) {
this.lastViewState = viewState;
if (this.view != null) {
this.view.setState(viewState);
}
}
}
/* @Override
@Nullable
public CharSequence getText() {
synchronized (viewLock) {
return view != null ? view.getText() : null;
}
}
@Override
public void setText(@Nullable CharSequence text) {
synchronized (viewLock) {
if (view != null) {
view.setText(text);
}
}
}
@Override
public int getSelection() {
synchronized (viewLock) {
return view != null ? view.getSelection() : 0;
}
}
@Override
public void setSelection(int selection) {
synchronized (viewLock) {
if (view != null) {
view.setSelection(selection);
}
}
}*/
@Override
@NotNull
public CalculatorEventData getLastEventData() {
return lastCalculatorEventData;
}
@Override
public void onCalculatorEvent(@NotNull CalculatorEventData calculatorEventData,
@NotNull CalculatorEventType calculatorEventType,
@Nullable Object data) {
if (calculatorEventType.isOfType(calculation_result, calculation_failed, calculation_cancelled)) {
if (calculatorEventData.isAfter(lastCalculatorEventData)) {
lastCalculatorEventData = calculatorEventData;
}
switch (calculatorEventType) {
case calculation_result:
processCalculationResult((CalculatorEvaluationEventData)calculatorEventData, (CalculatorOutput) data);
break;
case calculation_cancelled:
processCalculationCancelled((CalculatorEvaluationEventData)calculatorEventData);
break;
case calculation_failed:
processCalculationFailed((CalculatorEvaluationEventData)calculatorEventData, (CalculatorFailure) data);
break;
}
}
}
private void processCalculationFailed(@NotNull CalculatorEvaluationEventData calculatorEventData, @NotNull CalculatorFailure data) {
final CalculatorEvalException calculatorEvalException = data.getCalculationEvalException();
final String errorMessage;
if (calculatorEvalException != null) {
errorMessage = CalculatorMessages.getBundle().getString(CalculatorMessages.syntax_error);
} else {
final CalculatorParseException calculationParseException = data.getCalculationParseException();
if (calculationParseException != null) {
errorMessage = calculationParseException.getLocalizedMessage();
} else {
errorMessage = CalculatorMessages.getBundle().getString(CalculatorMessages.syntax_error);
}
}
this.setViewState(CalculatorDisplayViewStateImpl.newErrorState(calculatorEventData.getOperation(), errorMessage));
}
private void processCalculationCancelled(@NotNull CalculatorEvaluationEventData calculatorEventData) {
final String errorMessage = CalculatorMessages.getBundle().getString(CalculatorMessages.syntax_error);
this.setViewState(CalculatorDisplayViewStateImpl.newErrorState(calculatorEventData.getOperation(), errorMessage));
}
private void processCalculationResult(@NotNull CalculatorEvaluationEventData calculatorEventData, @NotNull CalculatorOutput data) {
final String stringResult = data.getStringResult();
this.setViewState(CalculatorDisplayViewStateImpl.newValidState(calculatorEventData.getOperation(), data.getResult(), stringResult, 0));
}
}

View File

@ -1,16 +0,0 @@
package org.solovyev.android.calculator;
import org.jetbrains.annotations.NotNull;
/**
* User: serso
* Date: 9/20/12
* Time: 8:25 PM
*/
public interface CalculatorDisplayView {
void setState(@NotNull CalculatorDisplayViewState state);
@NotNull
CalculatorDisplayViewState getState();
}

View File

@ -1,33 +0,0 @@
package org.solovyev.android.calculator;
import jscl.math.Generic;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.jscl.JsclOperation;
/**
* User: serso
* Date: 9/20/12
* Time: 9:50 PM
*/
public interface CalculatorDisplayViewState {
@NotNull
String getText();
int getSelection();
@Nullable
Generic getResult();
boolean isValid();
@Nullable
String getErrorMessage();
@NotNull
JsclOperation getOperation();
@Nullable
String getStringResult();
}

View File

@ -1,104 +0,0 @@
package org.solovyev.android.calculator;
import jscl.math.Generic;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.jscl.JsclOperation;
import org.solovyev.common.text.StringUtils;
/**
* User: serso
* Date: 9/20/12
* Time: 9:50 PM
*/
public class CalculatorDisplayViewStateImpl implements CalculatorDisplayViewState {
@NotNull
private JsclOperation operation = JsclOperation.numeric;
@Nullable
private Generic result;
@Nullable
private String stringResult = "";
private boolean valid = true;
@Nullable
private String errorMessage;
private int selection = 0;
private CalculatorDisplayViewStateImpl() {
}
@NotNull
public static CalculatorDisplayViewState newDefaultInstance() {
return new CalculatorDisplayViewStateImpl();
}
@NotNull
public static CalculatorDisplayViewState newErrorState(@NotNull JsclOperation operation,
@NotNull String errorMessage) {
final CalculatorDisplayViewStateImpl calculatorDisplayState = new CalculatorDisplayViewStateImpl();
calculatorDisplayState.valid = false;
calculatorDisplayState.errorMessage = errorMessage;
calculatorDisplayState.operation = operation;
return calculatorDisplayState;
}
@NotNull
public static CalculatorDisplayViewState newValidState(@NotNull JsclOperation operation,
@Nullable Generic result,
@NotNull String stringResult,
int selection) {
final CalculatorDisplayViewStateImpl calculatorDisplayState = new CalculatorDisplayViewStateImpl();
calculatorDisplayState.valid = true;
calculatorDisplayState.result = result;
calculatorDisplayState.stringResult = stringResult;
calculatorDisplayState.operation = operation;
calculatorDisplayState.selection = selection;
return calculatorDisplayState;
}
@NotNull
@Override
public String getText() {
return StringUtils.getNotEmpty(isValid() ? stringResult : errorMessage, "");
}
@Override
public int getSelection() {
return selection;
}
@Nullable
@Override
public Generic getResult() {
return this.result;
}
@Override
public boolean isValid() {
return this.valid;
}
@Nullable
@Override
public String getErrorMessage() {
return this.errorMessage;
}
@Override
@Nullable
public String getStringResult() {
return stringResult;
}
@NotNull
@Override
public JsclOperation getOperation() {
return this.operation;
}
}

View File

@ -1,18 +0,0 @@
package org.solovyev.android.calculator;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.jscl.JsclOperation;
/**
* User: serso
* Date: 9/20/12
* Time: 10:00 PM
*/
public interface CalculatorEvaluationEventData extends CalculatorEventData{
@NotNull
JsclOperation getOperation();
@NotNull
String getExpression();
}

View File

@ -1,58 +0,0 @@
package org.solovyev.android.calculator;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.jscl.JsclOperation;
/**
* User: serso
* Date: 9/20/12
* Time: 10:01 PM
*/
public class CalculatorEvaluationEventDataImpl implements CalculatorEvaluationEventData {
@NotNull
private final CalculatorEventData calculatorEventData;
@NotNull
private final JsclOperation operation;
@NotNull
private final String expression;
public CalculatorEvaluationEventDataImpl(@NotNull CalculatorEventData calculatorEventData,
@NotNull JsclOperation operation,
@NotNull String expression) {
this.calculatorEventData = calculatorEventData;
this.operation = operation;
this.expression = expression;
}
@NotNull
@Override
public JsclOperation getOperation() {
return this.operation;
}
@NotNull
@Override
public String getExpression() {
return this.expression;
}
@Override
public long getEventId() {
return calculatorEventData.getEventId();
}
@Override
@Nullable
public Long getCalculationId() {
return calculatorEventData.getCalculationId();
}
@Override
public boolean isAfter(@NotNull CalculatorEventDataId calculatorEventDataId) {
return calculatorEventData.isAfter(calculatorEventDataId);
}
}

View File

@ -1,57 +0,0 @@
package org.solovyev.android.calculator;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
/**
* User: Solovyev_S
* Date: 20.09.12
* Time: 16:39
*/
public interface CalculatorEventContainer {
void addCalculatorEventListener(@NotNull CalculatorEventListener calculatorEventListener);
void removeCalculatorEventListener(@NotNull CalculatorEventListener calculatorEventListener);
void fireCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable Object data);
void fireCalculatorEvents(@NotNull List<CalculatorEvent> calculatorEvents);
public static class CalculatorEvent {
@NotNull
private CalculatorEventData calculatorEventData;
@NotNull
private CalculatorEventType calculatorEventType;
@Nullable
private Object data;
public CalculatorEvent(@NotNull CalculatorEventData calculatorEventData,
@NotNull CalculatorEventType calculatorEventType,
@Nullable Object data) {
this.calculatorEventData = calculatorEventData;
this.calculatorEventType = calculatorEventType;
this.data = data;
}
@NotNull
public CalculatorEventData getCalculatorEventData() {
return calculatorEventData;
}
@NotNull
public CalculatorEventType getCalculatorEventType() {
return calculatorEventType;
}
@Nullable
public Object getData() {
return data;
}
}
}

View File

@ -1,10 +0,0 @@
package org.solovyev.android.calculator;
/**
* User: Solovyev_S
* Date: 20.09.12
* Time: 16:51
*/
public interface CalculatorEventData extends CalculatorEventDataId {
}

View File

@ -1,20 +0,0 @@
package org.solovyev.android.calculator;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* User: Solovyev_S
* Date: 20.09.12
* Time: 18:18
*/
public interface CalculatorEventDataId {
// the higher id => the later event
long getEventId();
@Nullable
Long getCalculationId();
boolean isAfter(@NotNull CalculatorEventDataId calculatorEventDataId);
}

View File

@ -1,66 +0,0 @@
package org.solovyev.android.calculator;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* User: Solovyev_S
* Date: 20.09.12
* Time: 18:18
*/
class CalculatorEventDataIdImpl implements CalculatorEventDataId {
private final long eventId;
@Nullable
private final Long calculationId;
private CalculatorEventDataIdImpl(long id,
@Nullable Long calculationId) {
this.eventId = id;
this.calculationId = calculationId;
}
@NotNull
static CalculatorEventDataId newInstance(long id,
@Nullable Long calculationId) {
return new CalculatorEventDataIdImpl(id, calculationId);
}
@Override
public long getEventId() {
return this.eventId;
}
@Nullable
@Override
public Long getCalculationId() {
return this.calculationId;
}
@Override
public boolean isAfter(@NotNull CalculatorEventDataId calculatorEventDataId) {
return this.eventId > calculatorEventDataId.getEventId();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof CalculatorEventDataIdImpl)) return false;
CalculatorEventDataIdImpl that = (CalculatorEventDataIdImpl) o;
if (eventId != that.eventId) return false;
if (calculationId != null ? !calculationId.equals(that.calculationId) : that.calculationId != null)
return false;
return true;
}
@Override
public int hashCode() {
int result = (int) (eventId ^ (eventId >>> 32));
result = 31 * result + (calculationId != null ? calculationId.hashCode() : 0);
return result;
}
}

View File

@ -1,57 +0,0 @@
package org.solovyev.android.calculator;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* User: Solovyev_S
* Date: 20.09.12
* Time: 16:54
*/
class CalculatorEventDataImpl implements CalculatorEventData {
@NotNull
private CalculatorEventDataId calculatorEventDataId;
private CalculatorEventDataImpl(@NotNull CalculatorEventDataId calculatorEventDataId) {
this.calculatorEventDataId = calculatorEventDataId;
}
@NotNull
public static CalculatorEventData newInstance(@NotNull CalculatorEventDataId calculatorEventDataId) {
return new CalculatorEventDataImpl(calculatorEventDataId);
}
@Override
public long getEventId() {
return calculatorEventDataId.getEventId();
}
@Override
@Nullable
public Long getCalculationId() {
return calculatorEventDataId.getCalculationId();
}
@Override
public boolean isAfter(@NotNull CalculatorEventDataId calculatorEventDataId) {
return this.calculatorEventDataId.isAfter(calculatorEventDataId);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof CalculatorEventDataImpl)) return false;
CalculatorEventDataImpl that = (CalculatorEventDataImpl) o;
if (!calculatorEventDataId.equals(that.calculatorEventDataId)) return false;
return true;
}
@Override
public int hashCode() {
return calculatorEventDataId.hashCode();
}
}

View File

@ -1,17 +0,0 @@
package org.solovyev.android.calculator;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.EventListener;
/**
* User: Solovyev_S
* Date: 20.09.12
* Time: 16:39
*/
public interface CalculatorEventListener extends EventListener {
void onCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable Object data);
}

View File

@ -1,43 +0,0 @@
package org.solovyev.android.calculator;
import org.jetbrains.annotations.NotNull;
/**
* User: Solovyev_S
* Date: 20.09.12
* Time: 16:40
*/
public enum CalculatorEventType {
/*
**********************************************************************
*
* org.solovyev.android.calculator.CalculatorEvaluationEventData
*
**********************************************************************
*/
// @NotNull org.solovyev.android.calculator.CalculatorInput
calculation_started,
// @NotNull org.solovyev.android.calculator.CalculatorOutput
calculation_result,
calculation_cancelled,
calculation_finished,
// @NotNull org.solovyev.android.calculator.CalculatorFailure
calculation_failed;
public boolean isOfType(@NotNull CalculatorEventType... types) {
for (CalculatorEventType type : types) {
if ( this == type ) {
return true;
}
}
return false;
}
}

View File

@ -1,21 +0,0 @@
package org.solovyev.android.calculator;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* User: serso
* Date: 9/20/12
* Time: 7:33 PM
*/
public interface CalculatorFailure {
@NotNull
Exception getException();
@Nullable
CalculatorParseException getCalculationParseException();
@Nullable
CalculatorEvalException getCalculationEvalException();
}

View File

@ -1,34 +0,0 @@
package org.solovyev.android.calculator;
import org.jetbrains.annotations.NotNull;
/**
* User: serso
* Date: 9/20/12
* Time: 7:34 PM
*/
public class CalculatorFailureImpl implements CalculatorFailure {
@NotNull
private Exception exception;
public CalculatorFailureImpl(@NotNull Exception exception) {
this.exception = exception;
}
@NotNull
@Override
public Exception getException() {
return this.exception;
}
@Override
public CalculatorParseException getCalculationParseException() {
return exception instanceof CalculatorParseException ? (CalculatorParseException)exception : null;
}
@Override
public CalculatorEvalException getCalculationEvalException() {
return exception instanceof CalculatorEvalException ? (CalculatorEvalException)exception : null;
}
}

View File

@ -1,209 +0,0 @@
package org.solovyev.android.calculator;
import jscl.AbstractJsclArithmeticException;
import jscl.NumeralBaseException;
import jscl.math.Generic;
import jscl.text.ParseInterruptedException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.jscl.JsclOperation;
import org.solovyev.android.calculator.text.TextProcessor;
import org.solovyev.common.msg.MessageRegistry;
import org.solovyev.common.msg.MessageType;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;
/**
* User: Solovyev_S
* Date: 20.09.12
* Time: 16:42
*/
public class CalculatorImpl implements Calculator {
private static final long FIRST_ID = 0;
@NotNull
private final CalculatorEventContainer calculatorEventContainer = new ListCalculatorEventContainer();
@NotNull
private final AtomicLong counter = new AtomicLong(FIRST_ID);
@NotNull
private final Object lock = new Object();
@NotNull
private final TextProcessor<PreparedExpression, String> preprocessor = ToJsclTextProcessor.getInstance();
@NotNull
private final Executor threadPoolExecutor = Executors.newFixedThreadPool(10);
public CalculatorImpl() {
}
@NotNull
private CalculatorEventDataId nextCalculatorEventDataId() {
long eventId = counter.incrementAndGet();
return CalculatorEventDataIdImpl.newInstance(eventId, eventId);
}
@NotNull
private CalculatorEventDataId nextEventDataId(@NotNull Long calculationId) {
long eventId = counter.incrementAndGet();
return CalculatorEventDataIdImpl.newInstance(eventId, calculationId);
}
/*
**********************************************************************
*
* CALCULATION
*
**********************************************************************
*/
@NotNull
@Override
public CalculatorEventDataId createFirstEventDataId() {
return CalculatorEventDataIdImpl.newInstance(FIRST_ID, FIRST_ID);
}
@Override
public void evaluate(@NotNull JsclOperation operation,
@NotNull String expression) {
evaluate(operation, expression, null);
}
@Override
@NotNull
public CalculatorEventDataId evaluate(@NotNull final JsclOperation operation,
@NotNull final String expression,
@Nullable final MessageRegistry mr) {
final CalculatorEventDataId eventDataId = nextCalculatorEventDataId();
threadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
CalculatorImpl.this.evaluate(eventDataId.getCalculationId(), operation, expression, mr);
}
});
return eventDataId;
}
private void evaluate(@NotNull Long calculationId,
@NotNull JsclOperation operation,
@NotNull String expression,
@Nullable MessageRegistry mr) {
synchronized (lock) {
PreparedExpression preparedExpression = null;
fireCalculatorEvent(newCalculationEventData(operation, expression, calculationId), CalculatorEventType.calculation_started, new CalculatorInputImpl(expression, operation));
try {
preparedExpression = preprocessor.process(expression);
final String jsclExpression = preparedExpression.toString();
try {
final Generic result = operation.evaluateGeneric(jsclExpression);
// NOTE: toString() method must be called here as ArithmeticOperationException may occur in it (just to avoid later check!)
result.toString();
final CalculatorOutputImpl data = new CalculatorOutputImpl(operation.getFromProcessor().process(result), operation, result);
fireCalculatorEvent(newCalculationEventData(operation, expression, calculationId), CalculatorEventType.calculation_result, data);
} catch (AbstractJsclArithmeticException e) {
handleException(calculationId, operation, expression, mr, new CalculatorEvalException(e, e, jsclExpression));
}
} catch (ArithmeticException e) {
handleException(calculationId, operation, expression, mr, preparedExpression, new CalculatorParseException(expression, new CalculatorMessage(CalculatorMessages.msg_001, MessageType.error, e.getMessage())));
} catch (StackOverflowError e) {
handleException(calculationId, operation, expression, mr, preparedExpression, new CalculatorParseException(expression, new CalculatorMessage(CalculatorMessages.msg_002, MessageType.error)));
} catch (jscl.text.ParseException e) {
handleException(calculationId, operation, expression, mr, preparedExpression, new CalculatorParseException(e));
} catch (ParseInterruptedException e) {
// do nothing - we ourselves interrupt the calculations
fireCalculatorEvent(newCalculationEventData(operation, expression, calculationId), CalculatorEventType.calculation_cancelled, null);
} catch (CalculatorParseException e) {
handleException(calculationId, operation, expression, mr, preparedExpression, e);
} finally {
fireCalculatorEvent(newCalculationEventData(operation, expression, calculationId), CalculatorEventType.calculation_finished, null);
}
}
}
@NotNull
private CalculatorEventData newCalculationEventData(@NotNull JsclOperation operation,
@NotNull String expression,
@NotNull Long calculationId) {
return new CalculatorEvaluationEventDataImpl(CalculatorEventDataImpl.newInstance(nextEventDataId(calculationId)), operation, expression);
}
private void handleException(@NotNull Long calculationId,
@NotNull JsclOperation operation,
@NotNull String expression,
@Nullable MessageRegistry mr,
@Nullable PreparedExpression preparedExpression,
@NotNull CalculatorParseException parseException) {
if (operation == JsclOperation.numeric
&& preparedExpression != null
&& preparedExpression.isExistsUndefinedVar()) {
evaluate(calculationId, JsclOperation.simplify, expression, mr);
}
fireCalculatorEvent(newCalculationEventData(operation, expression, calculationId), CalculatorEventType.calculation_failed, new CalculatorFailureImpl(parseException));
}
private void handleException(@NotNull Long calculationId,
@NotNull JsclOperation operation,
@NotNull String expression,
@Nullable MessageRegistry mr,
@NotNull CalculatorEvalException evalException) {
if (operation == JsclOperation.numeric && evalException.getCause() instanceof NumeralBaseException) {
evaluate(calculationId, JsclOperation.simplify, expression, mr);
}
fireCalculatorEvent(newCalculationEventData(operation, expression, calculationId), CalculatorEventType.calculation_failed, new CalculatorFailureImpl(evalException));
}
/*
**********************************************************************
*
* EVENTS
*
**********************************************************************
*/
@Override
public void addCalculatorEventListener(@NotNull CalculatorEventListener calculatorEventListener) {
calculatorEventContainer.addCalculatorEventListener(calculatorEventListener);
}
@Override
public void removeCalculatorEventListener(@NotNull CalculatorEventListener calculatorEventListener) {
calculatorEventContainer.removeCalculatorEventListener(calculatorEventListener);
}
@Override
public void fireCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
calculatorEventContainer.fireCalculatorEvent(calculatorEventData, calculatorEventType, data);
}
@Override
public void fireCalculatorEvents(@NotNull List<CalculatorEvent> calculatorEvents) {
calculatorEventContainer.fireCalculatorEvents(calculatorEvents);
}
}

View File

@ -1,18 +0,0 @@
package org.solovyev.android.calculator;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.jscl.JsclOperation;
/**
* User: serso
* Date: 9/20/12
* Time: 7:25 PM
*/
public interface CalculatorInput {
@NotNull
String getExpression();
@NotNull
JsclOperation getOperation();
}

View File

@ -1,35 +0,0 @@
package org.solovyev.android.calculator;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.jscl.JsclOperation;
/**
* User: serso
* Date: 9/20/12
* Time: 7:26 PM
*/
public class CalculatorInputImpl implements CalculatorInput {
@NotNull
private String expression;
@NotNull
private JsclOperation operation;
public CalculatorInputImpl(@NotNull String expression, @NotNull JsclOperation operation) {
this.expression = expression;
this.operation = operation;
}
@Override
@NotNull
public String getExpression() {
return expression;
}
@Override
@NotNull
public JsclOperation getOperation() {
return operation;
}
}

View File

@ -1,22 +0,0 @@
package org.solovyev.android.calculator;
import org.jetbrains.annotations.NotNull;
/**
* User: Solovyev_S
* Date: 20.09.12
* Time: 12:45
*/
public interface CalculatorLocator {
@NotNull
JCalculatorEngine getCalculatorEngine();
@NotNull
Calculator getCalculator();
@NotNull
CalculatorDisplay getCalculatorDisplay();
void setCalculatorEngine(@NotNull JCalculatorEngine calculatorEngine);
}

View File

@ -1,54 +0,0 @@
package org.solovyev.android.calculator;
import org.jetbrains.annotations.NotNull;
/**
* User: Solovyev_S
* Date: 20.09.12
* Time: 12:45
*/
public class CalculatorLocatorImpl implements CalculatorLocator {
@NotNull
private JCalculatorEngine calculatorEngine;
@NotNull
private CalculatorDisplay calculatorDisplay = new CalculatorDisplayImpl();
@NotNull
private Calculator calculator = new CalculatorImpl();
@NotNull
private static final CalculatorLocator instance = new CalculatorLocatorImpl();
private CalculatorLocatorImpl() {
}
@NotNull
public static CalculatorLocator getInstance() {
return instance;
}
@NotNull
@Override
public JCalculatorEngine getCalculatorEngine() {
return calculatorEngine;
}
@NotNull
@Override
public Calculator getCalculator() {
return this.calculator;
}
@Override
public void setCalculatorEngine(@NotNull JCalculatorEngine calculatorEngine) {
this.calculatorEngine = calculatorEngine;
}
@Override
@NotNull
public CalculatorDisplay getCalculatorDisplay() {
return calculatorDisplay;
}
}

View File

@ -1,31 +0,0 @@
package org.solovyev.android.calculator;
import org.jetbrains.annotations.NotNull;
import org.solovyev.common.msg.AbstractMessage;
import org.solovyev.common.msg.MessageType;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
/**
* User: serso
* Date: 9/20/12
* Time: 8:06 PM
*/
public class CalculatorMessage extends AbstractMessage {
protected CalculatorMessage(@NotNull String messageCode, @NotNull MessageType messageType, @org.jetbrains.annotations.Nullable Object... parameters) {
super(messageCode, messageType, parameters);
}
protected CalculatorMessage(@NotNull String messageCode, @NotNull MessageType messageType, @NotNull List<?> parameters) {
super(messageCode, messageType, parameters);
}
@Override
protected String getMessagePattern(@NotNull Locale locale) {
final ResourceBundle rb = CalculatorMessages.getBundle(locale);
return rb.getString(getMessageCode());
}
}

View File

@ -1,69 +0,0 @@
package org.solovyev.android.calculator;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
/**
* User: serso
* Date: 9/20/12
* Time: 8:10 PM
*/
public final class CalculatorMessages {
@NotNull
private static final Map<Locale, ResourceBundle> bundlesByLocale = new HashMap<Locale, ResourceBundle>();
private CalculatorMessages() {
throw new AssertionError();
}
@NotNull
public static ResourceBundle getBundle() {
return getBundle(Locale.getDefault());
}
@NotNull
public static ResourceBundle getBundle(@NotNull Locale locale) {
synchronized (bundlesByLocale) {
ResourceBundle result = bundlesByLocale.get(locale);
if (result == null) {
result = ResourceBundle.getBundle("org/solovyev/android/calculator/messages", locale);
bundlesByLocale.put(locale, result);
}
return result;
}
}
/* Arithmetic error occurred: {0} */
@NotNull
public static final String msg_001 = "msg_1";
/* Too complex expression*/
@NotNull
public static final String msg_002 = "msg_2";
/* Too long execution time - check the expression*/
@NotNull
public static final String msg_003 = "msg_3";
/* Evaluation was cancelled*/
@NotNull
public static final String msg_004 = "msg_4";
/* No parameters are specified for function: {0}*/
@NotNull
public static final String msg_005 = "msg_5";
/* Infinite loop is detected in expression*/
@NotNull
public static final String msg_006 = "msg_6";
/* Error */
@NotNull
public static final String syntax_error = "syntax_error";
}

View File

@ -1,22 +0,0 @@
package org.solovyev.android.calculator;
import jscl.math.Generic;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.jscl.JsclOperation;
/**
* User: serso
* Date: 9/20/12
* Time: 7:29 PM
*/
public interface CalculatorOutput {
@NotNull
String getStringResult();
@NotNull
JsclOperation getOperation();
@NotNull
Generic getResult();
}

View File

@ -1,46 +0,0 @@
package org.solovyev.android.calculator;
import jscl.math.Generic;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.jscl.JsclOperation;
/**
* User: serso
* Date: 9/20/12
* Time: 7:28 PM
*/
public class CalculatorOutputImpl implements CalculatorOutput {
@NotNull
private Generic result;
@NotNull
private String stringResult;
@NotNull
private JsclOperation operation;
public CalculatorOutputImpl(@NotNull String stringResult, @NotNull JsclOperation operation, @NotNull Generic result) {
this.stringResult = stringResult;
this.operation = operation;
this.result = result;
}
@Override
@NotNull
public String getStringResult() {
return stringResult;
}
@Override
@NotNull
public JsclOperation getOperation() {
return operation;
}
@Override
@NotNull
public Generic getResult() {
return result;
}
}

View File

@ -1,34 +0,0 @@
package org.solovyev.android.calculator;
import jscl.MathEngine;
import jscl.math.function.Function;
import jscl.math.function.IConstant;
import jscl.math.operator.Operator;
import org.jetbrains.annotations.NotNull;
import org.solovyev.common.math.MathRegistry;
/**
* User: Solovyev_S
* Date: 20.09.12
* Time: 12:43
*/
public interface JCalculatorEngine {
@NotNull
String getMultiplicationSign();
@NotNull
MathRegistry<IConstant> getVarsRegistry();
@NotNull
MathRegistry<Function> getFunctionsRegistry();
@NotNull
MathRegistry<Operator> getOperatorsRegistry();
@NotNull
MathRegistry<Operator> getPostfixFunctionsRegistry();
@NotNull
MathEngine getEngine();
}

View File

@ -1,50 +0,0 @@
package org.solovyev.android.calculator;
import android.util.Log;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.common.utils.ListListenersContainer;
import java.util.Arrays;
import java.util.List;
/**
* User: Solovyev_S
* Date: 20.09.12
* Time: 16:42
*/
public class ListCalculatorEventContainer implements CalculatorEventContainer {
@NotNull
private static final String TAG = "CalculatorEventData";
@NotNull
private final ListListenersContainer<CalculatorEventListener> listeners = new ListListenersContainer<CalculatorEventListener>();
@Override
public void addCalculatorEventListener(@NotNull CalculatorEventListener calculatorEventListener) {
listeners.addListener(calculatorEventListener);
}
@Override
public void removeCalculatorEventListener(@NotNull CalculatorEventListener calculatorEventListener) {
listeners.removeListener(calculatorEventListener);
}
@Override
public void fireCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
fireCalculatorEvents(Arrays.asList(new CalculatorEvent(calculatorEventData, calculatorEventType, data)));
}
@Override
public void fireCalculatorEvents(@NotNull List<CalculatorEvent> calculatorEvents) {
final List<CalculatorEventListener> listeners = this.listeners.getListeners();
for (CalculatorEvent e : calculatorEvents) {
Log.d(TAG, "Event: " + e.getCalculatorEventType() + " with data: " + e.getData());
for (CalculatorEventListener listener : listeners) {
listener.onCalculatorEvent(e.getCalculatorEventData(), e.getCalculatorEventType(), e.getData());
}
}
}
}

View File

@ -1,20 +0,0 @@
package org.solovyev.android.calculator.history;
import org.jetbrains.annotations.NotNull;
import org.solovyev.common.history.HistoryHelper;
/**
* User: Solovyev_S
* Date: 20.09.12
* Time: 16:11
*/
public interface CalculatorHistory extends HistoryHelper<CalculatorHistoryState> {
void fromXml(@NotNull String xml);
String toXml();
void clearSavedHistory();
void removeSavedHistory(@NotNull CalculatorHistoryState historyState);
}

View File

@ -1,131 +0,0 @@
package org.solovyev.android.calculator.history;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.common.history.HistoryAction;
import org.solovyev.common.history.HistoryHelper;
import org.solovyev.common.history.SimpleHistoryHelper;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/**
* User: Solovyev_S
* Date: 20.09.12
* Time: 16:12
*/
public class CalculatorHistoryImpl implements CalculatorHistory {
private final AtomicInteger counter = new AtomicInteger(0);
@NotNull
private final HistoryHelper<CalculatorHistoryState> history = new SimpleHistoryHelper<CalculatorHistoryState>();
@NotNull
private final List<CalculatorHistoryState> savedHistory = new ArrayList<CalculatorHistoryState>();
@Override
public boolean isEmpty() {
return this.history.isEmpty();
}
@Override
public CalculatorHistoryState getLastHistoryState() {
return this.history.getLastHistoryState();
}
@Override
public boolean isUndoAvailable() {
return history.isUndoAvailable();
}
@Override
public CalculatorHistoryState undo(@Nullable CalculatorHistoryState currentState) {
return history.undo(currentState);
}
@Override
public boolean isRedoAvailable() {
return history.isRedoAvailable();
}
@Override
public CalculatorHistoryState redo(@Nullable CalculatorHistoryState currentState) {
return history.redo(currentState);
}
@Override
public boolean isActionAvailable(@NotNull HistoryAction historyAction) {
return history.isActionAvailable(historyAction);
}
@Override
public CalculatorHistoryState doAction(@NotNull HistoryAction historyAction, @Nullable CalculatorHistoryState currentState) {
return history.doAction(historyAction, currentState);
}
@Override
public void addState(@Nullable CalculatorHistoryState currentState) {
history.addState(currentState);
}
@NotNull
@Override
public List<CalculatorHistoryState> getStates() {
return history.getStates();
}
@Override
public void clear() {
this.history.clear();
}
@NotNull
public List<CalculatorHistoryState> getSavedHistory() {
return Collections.unmodifiableList(savedHistory);
}
@NotNull
public CalculatorHistoryState addSavedState(@NotNull CalculatorHistoryState historyState) {
if (historyState.isSaved()) {
return historyState;
} else {
final CalculatorHistoryState savedState = historyState.clone();
savedState.setId(counter.incrementAndGet());
savedState.setSaved(true);
savedHistory.add(savedState);
return savedState;
}
}
@Override
public void fromXml(@NotNull String xml) {
clearSavedHistory();
HistoryUtils.fromXml(xml, this.savedHistory);
for (CalculatorHistoryState historyState : savedHistory) {
historyState.setSaved(true);
historyState.setId(counter.incrementAndGet());
}
}
@Override
public String toXml() {
return HistoryUtils.toXml(this.savedHistory);
}
@Override
public void clearSavedHistory() {
this.savedHistory.clear();
}
@Override
public void removeSavedHistory(@NotNull CalculatorHistoryState historyState) {
this.savedHistory.remove(historyState);
}
}

View File

@ -1,77 +0,0 @@
package org.solovyev.common.utils;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* User: Solovyev_S
* Date: 20.09.12
* Time: 16:43
*/
// todo serso: move to common
public class ListListenersContainer<T> {
@NotNull
private final List<WeakReference<T>> listeners = new ArrayList<WeakReference<T>>();
public void addListener(@NotNull final T listener) {
synchronized (listeners) {
boolean contains = Iterables.any(listeners, new WeakReferencePredicate<T>(listener));
if (!contains) {
listeners.add(new WeakReference<T>(listener));
}
}
}
public void removeListener(@NotNull T listener) {
synchronized (listeners) {
Iterables.removeIf(listeners, new WeakReferencePredicate<T>(listener));
}
}
@NotNull
public List<T> getListeners() {
final List<T> localListeners;
synchronized (listeners) {
localListeners = new ArrayList<T>(listeners.size());
// copy listeners and remove garbage collected references
for ( Iterator<WeakReference<T>> it = listeners.iterator(); it.hasNext(); ) {
final WeakReference<T> r = it.next();
final T t = r.get();
if ( t == null ) {
it.remove();
} else {
localListeners.add(t);
}
}
}
return localListeners;
}
private static class WeakReferencePredicate<T> implements Predicate<WeakReference<T>> {
@NotNull
private final T t;
public WeakReferencePredicate(T t) {
this.t = t;
}
@Override
public boolean apply(@Nullable WeakReference<T> r) {
final T t = r != null ? r.get() : null;
return this.t.equals(t);
}
}
}

View File

@ -1,8 +0,0 @@
msg_1=Arithmetic error occurred: {0}
msg_2=Too complex expression
msg_3=Too long execution time - check the expression
msg_4=Evaluation was cancelled
msg_5=No parameters are specified for function: {0}
msg_6=Infinite loop is detected in expression
syntax_error=Error

View File

@ -22,6 +22,7 @@
<dependency> <dependency>
<groupId>com.intellij</groupId> <groupId>com.intellij</groupId>
<artifactId>annotations</artifactId> <artifactId>annotations</artifactId>
<version>7.0.3</version>
</dependency> </dependency>
<dependency> <dependency>

View File

@ -19,13 +19,6 @@
<dependencies> <dependencies>
<!-- OWN --> <!-- OWN -->
<dependency>
<groupId>org.solovyev.android</groupId>
<artifactId>calculatorpp-core</artifactId>
<version>1.3.1</version>
</dependency>
<dependency> <dependency>
<groupId>org.solovyev</groupId> <groupId>org.solovyev</groupId>
<artifactId>common-core</artifactId> <artifactId>common-core</artifactId>
@ -82,6 +75,13 @@
<dependency> <dependency>
<groupId>org.solovyev</groupId> <groupId>org.solovyev</groupId>
<artifactId>jscl</artifactId> <artifactId>jscl</artifactId>
<version>0.0.2</version>
<exclusions>
<exclusion>
<artifactId>xercesImpl</artifactId>
<groupId>xerces</groupId>
</exclusion>
</exclusions>
</dependency> </dependency>
<!--OTHER--> <!--OTHER-->
@ -92,6 +92,13 @@
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>net.sf.opencsv</groupId> <groupId>net.sf.opencsv</groupId>
<artifactId>opencsv</artifactId> <artifactId>opencsv</artifactId>
@ -102,6 +109,17 @@
<dependency> <dependency>
<groupId>org.simpleframework</groupId> <groupId>org.simpleframework</groupId>
<artifactId>simple-xml</artifactId> <artifactId>simple-xml</artifactId>
<version>2.6.1</version>
<exclusions>
<exclusion>
<artifactId>stax-api</artifactId>
<groupId>stax</groupId>
</exclusion>
<exclusion>
<artifactId>xpp3</artifactId>
<groupId>xpp3</groupId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>
@ -129,15 +147,10 @@
<version>11.0.2</version> <version>11.0.2</version>
</dependency> </dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>com.intellij</groupId> <groupId>com.intellij</groupId>
<artifactId>annotations</artifactId> <artifactId>annotations</artifactId>
<version>7.0.3</version>
</dependency> </dependency>
</dependencies> </dependencies>

View File

@ -1,16 +1,16 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<!-- <!--
~ Copyright (c) 2009-2011. Created by serso aka se.solovyev. ~ Copyright (c) 2009-2011. Created by serso aka se.solovyev.
~ For more information, please, contact se.solovyev@gmail.com ~ For more information, please, contact se.solovyev@gmail.com
~ or visit http://se.solovyev.org ~ or visit http://se.solovyev.org
--> -->
<org.solovyev.android.calculator.AndroidCalculatorDisplayView <org.solovyev.android.calculator.CalculatorDisplay
xmlns:a="http://schemas.android.com/apk/res/android" xmlns:a="http://schemas.android.com/apk/res/android"
a:id="@+id/calculatorDisplay" a:id="@+id/calculatorDisplay"
style="@style/display_style" style="@style/display_style"
a:inputType="textMultiLine" a:inputType="textMultiLine"
a:maxLines="3" a:maxLines="3"
a:scrollHorizontally="false" a:scrollHorizontally="false"
a:scrollbars="none"/> a:scrollbars="none"/>

View File

@ -1,4 +1,4 @@
package org.solovyev.math.units; package org.solovyev.android;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;

View File

@ -1,4 +1,4 @@
package org.solovyev.math.units; package org.solovyev.android;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;

View File

@ -1,4 +1,4 @@
package org.solovyev.math.units; package org.solovyev.android;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;

View File

@ -1,4 +1,4 @@
package org.solovyev.math.units; package org.solovyev.android;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;

View File

@ -3,10 +3,10 @@ package org.solovyev.android.calculator;
import android.app.Activity; import android.app.Activity;
import jscl.NumeralBase; import jscl.NumeralBase;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.solovyev.math.units.Unit; import org.solovyev.android.Unit;
import org.solovyev.math.units.UnitConverter; import org.solovyev.android.UnitConverter;
import org.solovyev.math.units.UnitImpl; import org.solovyev.android.UnitImpl;
import org.solovyev.math.units.UnitType; import org.solovyev.android.UnitType;
import org.solovyev.android.view.drag.DirectionDragButton; import org.solovyev.android.view.drag.DirectionDragButton;
import org.solovyev.android.view.drag.DragDirection; import org.solovyev.android.view.drag.DragDirection;

View File

@ -32,7 +32,7 @@ import org.solovyev.android.AndroidUtils;
import org.solovyev.android.FontSizeAdjuster; import org.solovyev.android.FontSizeAdjuster;
import org.solovyev.android.LocalBinder; import org.solovyev.android.LocalBinder;
import org.solovyev.android.calculator.about.CalculatorReleaseNotesActivity; import org.solovyev.android.calculator.about.CalculatorReleaseNotesActivity;
import org.solovyev.android.calculator.history.AndroidCalculatorHistoryImpl; import org.solovyev.android.calculator.history.CalculatorHistory;
import org.solovyev.android.calculator.history.CalculatorHistoryState; import org.solovyev.android.calculator.history.CalculatorHistoryState;
import org.solovyev.android.calculator.model.CalculatorEngine; import org.solovyev.android.calculator.model.CalculatorEngine;
import org.solovyev.android.calculator.view.AngleUnitsButton; import org.solovyev.android.calculator.view.AngleUnitsButton;
@ -136,7 +136,7 @@ public class CalculatorActivity extends Activity implements FontSizeAdjuster, Sh
vibrator = (Vibrator) this.getSystemService(VIBRATOR_SERVICE); vibrator = (Vibrator) this.getSystemService(VIBRATOR_SERVICE);
AndroidCalculatorHistoryImpl.instance.load(this, preferences); CalculatorHistory.instance.load(this, preferences);
calculatorModel = CalculatorModel.instance.init(this, preferences, CalculatorEngine.instance); calculatorModel = CalculatorModel.instance.init(this, preferences, CalculatorEngine.instance);
dpclRegister.clear(); dpclRegister.clear();

View File

@ -46,8 +46,6 @@ public class CalculatorApplication extends android.app.Application {
public void onCreate() { public void onCreate() {
super.onCreate(); super.onCreate();
CalculatorLocatorImpl.getInstance().setCalculatorEngine(CalculatorEngine.instance);
AdsController.getInstance().init(ADMOB_USER_ID, AD_FREE_PRODUCT_ID, new BillingController.IConfiguration() { AdsController.getInstance().init(ADMOB_USER_ID, AD_FREE_PRODUCT_ID, new BillingController.IConfiguration() {
@Override @Override

View File

@ -15,9 +15,12 @@ import jscl.math.Generic;
import jscl.math.function.Constant; import jscl.math.function.Constant;
import jscl.math.function.IConstant; import jscl.math.function.IConstant;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.jscl.JsclOperation; import org.solovyev.android.calculator.jscl.JsclOperation;
import org.solovyev.android.calculator.model.CalculatorEngine; import org.solovyev.android.calculator.model.CalculatorEngine;
import org.solovyev.android.calculator.text.TextProcessor; import org.solovyev.android.calculator.model.CalculatorParseException;
import org.solovyev.android.calculator.model.TextProcessor;
import org.solovyev.android.calculator.model.ToJsclTextProcessor;
import org.solovyev.android.calculator.view.NumeralBaseConverterDialog; import org.solovyev.android.calculator.view.NumeralBaseConverterDialog;
import org.solovyev.android.calculator.view.TextHighlighter; import org.solovyev.android.calculator.view.TextHighlighter;
import org.solovyev.android.calculator.view.UnitConverterViewBuilder; import org.solovyev.android.calculator.view.UnitConverterViewBuilder;
@ -35,9 +38,9 @@ import java.util.Set;
* Date: 9/17/11 * Date: 9/17/11
* Time: 10:58 PM * Time: 10:58 PM
*/ */
public class AndroidCalculatorDisplayView extends AutoResizeTextView implements CalculatorDisplayView { public class CalculatorDisplay extends AutoResizeTextView implements ICalculatorDisplay{
private static enum ConversionMenuItem implements AMenuItem<CalculatorDisplayView> { private static enum ConversionMenuItem implements AMenuItem<CalculatorDisplay> {
convert_to_bin(NumeralBase.bin), convert_to_bin(NumeralBase.bin),
convert_to_dec(NumeralBase.dec), convert_to_dec(NumeralBase.dec),
convert_to_hex(NumeralBase.hex); convert_to_hex(NumeralBase.hex);
@ -70,27 +73,23 @@ public class AndroidCalculatorDisplayView extends AutoResizeTextView implements
} }
@Override @Override
public void onClick(@NotNull CalculatorDisplayView data, @NotNull Context context) { public void onClick(@NotNull CalculatorDisplay data, @NotNull Context context) {
final NumeralBase fromNumeralBase = CalculatorEngine.instance.getEngine().getNumeralBase(); final NumeralBase fromNumeralBase = CalculatorEngine.instance.getEngine().getNumeralBase();
final Generic lastResult = CalculatorLocatorImpl.getInstance().getCalculatorDisplay().getViewState().getResult(); String to;
try {
to = convert(data.getGenericResult());
if (lastResult != null) { // add prefix
String to; if (fromNumeralBase != toNumeralBase) {
try { to = toNumeralBase.getJsclPrefix() + to;
to = convert(lastResult);
// add prefix
if (fromNumeralBase != toNumeralBase) {
to = toNumeralBase.getJsclPrefix() + to;
}
} catch (UnitConverterViewBuilder.ConversionException e) {
to = context.getString(R.string.c_error);
} }
} catch (UnitConverterViewBuilder.ConversionException e) {
data.setText(to); to = context.getString(R.string.c_error);
//data.redraw();
} }
data.setText(to);
data.redraw();
} }
@NotNull @NotNull
@ -114,18 +113,18 @@ public class AndroidCalculatorDisplayView extends AutoResizeTextView implements
} }
} }
public static enum MenuItem implements LabeledMenuItem<CalculatorDisplayView> { public static enum MenuItem implements LabeledMenuItem<CalculatorDisplay> {
copy(R.string.c_copy) { copy(R.string.c_copy) {
@Override @Override
public void onClick(@NotNull CalculatorDisplayView data, @NotNull Context context) { public void onClick(@NotNull CalculatorDisplay data, @NotNull Context context) {
CalculatorModel.copyResult(context, data); CalculatorModel.copyResult(context, data);
} }
}, },
convert_to_bin(R.string.convert_to_bin) { convert_to_bin(R.string.convert_to_bin) {
@Override @Override
public void onClick(@NotNull CalculatorDisplayView data, @NotNull Context context) { public void onClick(@NotNull CalculatorDisplay data, @NotNull Context context) {
ConversionMenuItem.convert_to_bin.onClick(data, context); ConversionMenuItem.convert_to_bin.onClick(data, context);
} }
@ -137,7 +136,7 @@ public class AndroidCalculatorDisplayView extends AutoResizeTextView implements
convert_to_dec(R.string.convert_to_dec) { convert_to_dec(R.string.convert_to_dec) {
@Override @Override
public void onClick(@NotNull CalculatorDisplayView data, @NotNull Context context) { public void onClick(@NotNull CalculatorDisplay data, @NotNull Context context) {
ConversionMenuItem.convert_to_dec.onClick(data, context); ConversionMenuItem.convert_to_dec.onClick(data, context);
} }
@ -149,7 +148,7 @@ public class AndroidCalculatorDisplayView extends AutoResizeTextView implements
convert_to_hex(R.string.convert_to_hex) { convert_to_hex(R.string.convert_to_hex) {
@Override @Override
public void onClick(@NotNull CalculatorDisplayView data, @NotNull Context context) { public void onClick(@NotNull CalculatorDisplay data, @NotNull Context context) {
ConversionMenuItem.convert_to_hex.onClick(data, context); ConversionMenuItem.convert_to_hex.onClick(data, context);
} }
@ -161,11 +160,8 @@ public class AndroidCalculatorDisplayView extends AutoResizeTextView implements
convert(R.string.c_convert) { convert(R.string.c_convert) {
@Override @Override
public void onClick(@NotNull CalculatorDisplayView data, @NotNull Context context) { public void onClick(@NotNull CalculatorDisplay data, @NotNull Context context) {
final Generic result = data.getState().getResult(); new NumeralBaseConverterDialog(data.getGenericResult().toString()).show(context);
if (result != null) {
new NumeralBaseConverterDialog(result.toString()).show(context);
}
} }
@Override @Override
@ -174,10 +170,10 @@ public class AndroidCalculatorDisplayView extends AutoResizeTextView implements
} }
}, },
plot(R.string.c_plot) { plot(R.string.c_plot) {
@Override @Override
public void onClick(@NotNull CalculatorDisplayView data, @NotNull Context context) { public void onClick(@NotNull CalculatorDisplay data, @NotNull Context context) {
final Generic generic = data.getState().getResult(); final Generic generic = data.getGenericResult();
assert generic != null; assert generic != null;
final Constant constant = CollectionsUtils.getFirstCollectionElement(getNotSystemConstants(generic)); final Constant constant = CollectionsUtils.getFirstCollectionElement(getNotSystemConstants(generic));
@ -185,18 +181,18 @@ public class AndroidCalculatorDisplayView extends AutoResizeTextView implements
CalculatorActivityLauncher.plotGraph(context, generic, constant); CalculatorActivityLauncher.plotGraph(context, generic, constant);
} }
@Override @Override
protected boolean isItemVisibleFor(@NotNull Generic generic, @NotNull JsclOperation operation) { protected boolean isItemVisibleFor(@NotNull Generic generic, @NotNull JsclOperation operation) {
boolean result = false; boolean result = false;
if (operation == JsclOperation.simplify) { if (operation == JsclOperation.simplify) {
if (getNotSystemConstants(generic).size() == 1) { if (getNotSystemConstants(generic).size() == 1) {
result = true; result = true;
} }
} }
return result; return result;
} }
@NotNull @NotNull
private Set<Constant> getNotSystemConstants(@NotNull Generic generic) { private Set<Constant> getNotSystemConstants(@NotNull Generic generic) {
@ -213,104 +209,140 @@ public class AndroidCalculatorDisplayView extends AutoResizeTextView implements
} }
}; };
private final int captionId; private final int captionId;
MenuItem(int captionId) { MenuItem(int captionId) {
this.captionId = captionId; this.captionId = captionId;
} }
public final boolean isItemVisible(@NotNull CalculatorDisplayViewState displayViewState) { public final boolean isItemVisible(@NotNull CalculatorDisplay display) {
//noinspection ConstantConditions //noinspection ConstantConditions
return displayViewState.isValid() && displayViewState.getResult() != null && isItemVisibleFor(displayViewState.getResult(), displayViewState.getOperation()); return display.isValid() && display.getGenericResult() != null && isItemVisibleFor(display.getGenericResult(), display.getJsclOperation());
} }
protected boolean isItemVisibleFor(@NotNull Generic generic, @NotNull JsclOperation operation) { protected boolean isItemVisibleFor(@NotNull Generic generic, @NotNull JsclOperation operation) {
return true; return true;
} }
@NotNull @NotNull
@Override @Override
public String getCaption(@NotNull Context context) { public String getCaption(@NotNull Context context) {
return context.getString(captionId); return context.getString(captionId);
} }
} }
@NotNull private boolean valid = true;
private CalculatorDisplayViewState state = CalculatorDisplayViewStateImpl.newDefaultInstance();
@NotNull @Nullable
private final static TextProcessor<TextHighlighter.Result, String> textHighlighter = new TextHighlighter(Color.WHITE, false, CalculatorEngine.instance.getEngine()); private String errorMessage;
public AndroidCalculatorDisplayView(Context context) { @NotNull
super(context); private JsclOperation jsclOperation = JsclOperation.numeric;
}
public AndroidCalculatorDisplayView(Context context, AttributeSet attrs) { @NotNull
super(context, attrs); private final static TextProcessor<TextHighlighter.Result, String> textHighlighter = new TextHighlighter(Color.WHITE, false, CalculatorEngine.instance.getEngine());
}
public AndroidCalculatorDisplayView(Context context, AttributeSet attrs, int defStyle) { @Nullable
super(context, attrs, defStyle); private Generic genericResult;
}
public boolean isValid() { public CalculatorDisplay(Context context) {
return this.state.isValid(); super(context);
} }
public CalculatorDisplay(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override public CalculatorDisplay(Context context, AttributeSet attrs, int defStyle) {
public void setState(@NotNull CalculatorDisplayViewState state) { super(context, attrs, defStyle);
this.state = state; }
if ( state.isValid() ) {
setTextColor(getResources().getColor(R.color.default_text_color));
setText(state.getStringResult());
} else {
setTextColor(getResources().getColor(R.color.display_error_text_color));
setText(state.getErrorMessage());
}
}
@NotNull @Override
@Override public boolean isValid() {
public CalculatorDisplayViewState getState() { return valid;
return this.state; }
}
@Override @Override
public void setText(CharSequence text, BufferType type) { public void setValid(boolean valid) {
super.setText(text, type); this.valid = valid;
} if (valid) {
errorMessage = null;
setTextColor(getResources().getColor(R.color.default_text_color));
} else {
setTextColor(getResources().getColor(R.color.display_error_text_color));
}
}
public synchronized void redraw() { @Override
if (isValid()) { @Nullable
String text = getText().toString(); public String getErrorMessage() {
return errorMessage;
}
Log.d(this.getClass().getName(), text); @Override
public void setErrorMessage(@Nullable String errorMessage) {
this.errorMessage = errorMessage;
}
try { @Override
TextHighlighter.Result result = textHighlighter.process(text); public void setJsclOperation(@NotNull JsclOperation jsclOperation) {
text = result.toString(); this.jsclOperation = jsclOperation;
} catch (CalculatorParseException e) { }
Log.e(this.getClass().getName(), e.getMessage(), e);
}
Log.d(this.getClass().getName(), text); @Override
super.setText(Html.fromHtml(text), BufferType.EDITABLE); @NotNull
} public JsclOperation getJsclOperation() {
return jsclOperation;
}
// todo serso: think where to move it (keep in mind org.solovyev.android.view.AutoResizeTextView.resetTextSize()) @Override
setAddEllipsis(false); public void setText(CharSequence text, BufferType type) {
setMinTextSize(10); super.setText(text, type);
resizeText();
}
@Override setValid(true);
public int getSelection() { }
return this.getSelectionStart();
}
@Override public synchronized void redraw() {
public void setSelection(int selection) { if (isValid()) {
// not supported by TextView String text = getText().toString();
}
Log.d(this.getClass().getName(), text);
try {
TextHighlighter.Result result = textHighlighter.process(text);
text = result.toString();
} catch (CalculatorParseException e) {
Log.e(this.getClass().getName(), e.getMessage(), e);
}
Log.d(this.getClass().getName(), text);
super.setText(Html.fromHtml(text), BufferType.EDITABLE);
}
// todo serso: think where to move it (keep in mind org.solovyev.android.view.AutoResizeTextView.resetTextSize())
setAddEllipsis(false);
setMinTextSize(10);
resizeText();
}
@Override
public void setGenericResult(@Nullable Generic genericResult) {
this.genericResult = genericResult;
}
@Override
@Nullable
public Generic getGenericResult() {
return genericResult;
}
@Override
public int getSelection() {
return this.getSelectionStart();
}
@Override
public void setSelection(int selection) {
// not supported by TextView
}
} }

View File

@ -16,7 +16,8 @@ import android.view.ContextMenu;
import android.widget.EditText; import android.widget.EditText;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.model.CalculatorEngine; import org.solovyev.android.calculator.model.CalculatorEngine;
import org.solovyev.android.calculator.text.TextProcessor; import org.solovyev.android.calculator.model.CalculatorParseException;
import org.solovyev.android.calculator.model.TextProcessor;
import org.solovyev.android.calculator.view.TextHighlighter; import org.solovyev.android.calculator.view.TextHighlighter;
import org.solovyev.common.collections.CollectionsUtils; import org.solovyev.common.collections.CollectionsUtils;

View File

@ -20,12 +20,14 @@ import android.widget.Toast;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.solovyev.android.CursorControl; import org.solovyev.android.CursorControl;
import org.solovyev.android.calculator.history.AndroidCalculatorHistoryImpl; import org.solovyev.android.calculator.history.CalculatorHistory;
import org.solovyev.android.calculator.history.CalculatorHistoryState; import org.solovyev.android.calculator.history.CalculatorHistoryState;
import org.solovyev.android.calculator.history.TextViewEditorAdapter; import org.solovyev.android.calculator.history.TextViewEditorAdapter;
import org.solovyev.android.calculator.jscl.JsclOperation; import org.solovyev.android.calculator.jscl.JsclOperation;
import org.solovyev.android.calculator.math.MathType; import org.solovyev.android.calculator.math.MathType;
import org.solovyev.android.calculator.model.CalculatorEngine; import org.solovyev.android.calculator.model.CalculatorEngine;
import org.solovyev.android.calculator.model.CalculatorEvalException;
import org.solovyev.android.calculator.model.CalculatorParseException;
import org.solovyev.android.history.HistoryControl; import org.solovyev.android.history.HistoryControl;
import org.solovyev.android.menu.AMenuBuilder; import org.solovyev.android.menu.AMenuBuilder;
import org.solovyev.android.menu.MenuImpl; import org.solovyev.android.menu.MenuImpl;
@ -53,7 +55,7 @@ public enum CalculatorModel implements CursorControl, HistoryControl<CalculatorH
private CalculatorEditor editor; private CalculatorEditor editor;
@NotNull @NotNull
private AndroidCalculatorDisplayView display; private CalculatorDisplay display;
@NotNull @NotNull
private CalculatorEngine calculatorEngine; private CalculatorEngine calculatorEngine;
@ -66,10 +68,10 @@ public enum CalculatorModel implements CursorControl, HistoryControl<CalculatorH
this.editor.init(preferences); this.editor.init(preferences);
preferences.registerOnSharedPreferenceChangeListener(editor); preferences.registerOnSharedPreferenceChangeListener(editor);
this.display = (AndroidCalculatorDisplayView) activity.findViewById(R.id.calculatorDisplay); this.display = (CalculatorDisplay) activity.findViewById(R.id.calculatorDisplay);
this.display.setOnClickListener(new CalculatorDisplayOnClickListener(activity)); this.display.setOnClickListener(new CalculatorDisplayOnClickListener(activity));
final CalculatorHistoryState lastState = AndroidCalculatorHistoryImpl.instance.getLastHistoryState(); final CalculatorHistoryState lastState = CalculatorHistory.instance.getLastHistoryState();
if (lastState == null) { if (lastState == null) {
saveHistoryState(); saveHistoryState();
} else { } else {
@ -97,9 +99,8 @@ public enum CalculatorModel implements CursorControl, HistoryControl<CalculatorH
copyResult(context, display); copyResult(context, display);
} }
public static void copyResult(@NotNull Context context, @NotNull final CalculatorDisplayView display) { public static void copyResult(@NotNull Context context, @NotNull final CalculatorDisplay display) {
final CalculatorDisplayViewState displayViewState = display.getState(); if (display.isValid()) {
if (displayViewState.isValid()) {
final CharSequence text = display.getText(); final CharSequence text = display.getText();
if (!StringUtils.isEmpty(text)) { if (!StringUtils.isEmpty(text)) {
final ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Activity.CLIPBOARD_SERVICE); final ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Activity.CLIPBOARD_SERVICE);
@ -110,7 +111,7 @@ public enum CalculatorModel implements CursorControl, HistoryControl<CalculatorH
} }
private void saveHistoryState() { private void saveHistoryState() {
AndroidCalculatorHistoryImpl.instance.addState(getCurrentHistoryState()); CalculatorHistory.instance.addState(getCurrentHistoryState());
} }
public void setCursorOnStart() { public void setCursorOnStart() {
@ -196,14 +197,14 @@ public enum CalculatorModel implements CursorControl, HistoryControl<CalculatorH
if (delayEvaluate) { if (delayEvaluate) {
if (historyState == null) { if (historyState == null) {
AndroidCalculatorHistoryImpl.instance.addState(localHistoryState); CalculatorHistory.instance.addState(localHistoryState);
} }
// todo serso: this is not correct - operation is processing still in the same thread // todo serso: this is not correct - operation is processing still in the same thread
new Handler().postDelayed(pendingOperation.getObject(), EVAL_DELAY_MILLIS); new Handler().postDelayed(pendingOperation.getObject(), EVAL_DELAY_MILLIS);
} else { } else {
pendingOperation.getObject().run(); pendingOperation.getObject().run();
if (historyState == null) { if (historyState == null) {
AndroidCalculatorHistoryImpl.instance.addState(localHistoryState); CalculatorHistory.instance.addState(localHistoryState);
} }
} }
} }
@ -229,16 +230,16 @@ public enum CalculatorModel implements CursorControl, HistoryControl<CalculatorH
if (!StringUtils.isEmpty(expression)) { if (!StringUtils.isEmpty(expression)) {
try { try {
Log.d(CalculatorModel.class.getName(), "Trying to evaluate '" + operation + "': " + expression /*+ StringUtils.fromStackTrace(Thread.currentThread().getStackTrace())*/); Log.d(CalculatorModel.class.getName(), "Trying to evaluate '" + operation + "': " + expression /*+ StringUtils.fromStackTrace(Thread.currentThread().getStackTrace())*/);
final CalculatorOutput result = calculatorEngine.evaluate(operation, expression); final CalculatorEngine.Result result = calculatorEngine.evaluate(operation, expression);
// todo serso: second condition might replaced with expression.equals(this.editor.getText().toString()) ONLY if expression will be formatted with text highlighter // todo serso: second condition might replaced with expression.equals(this.editor.getText().toString()) ONLY if expression will be formatted with text highlighter
if (currentRunner == pendingOperation.getObject() && this.editor.getText().length() > 0) { if (currentRunner == pendingOperation.getObject() && this.editor.getText().length() > 0) {
display.setText(result.getStringResult()); display.setText(result.getResult());
} else { } else {
display.setText(""); display.setText("");
} }
display.setJsclOperation(result.getOperation()); display.setJsclOperation(result.getUserOperation());
display.setGenericResult(result.getResult()); display.setGenericResult(result.getGenericResult());
} catch (CalculatorParseException e) { } catch (CalculatorParseException e) {
handleEvaluationException(expression, display, operation, e); handleEvaluationException(expression, display, operation, e);
} catch (CalculatorEvalException e) { } catch (CalculatorEvalException e) {
@ -256,7 +257,7 @@ public enum CalculatorModel implements CursorControl, HistoryControl<CalculatorH
} }
private void handleEvaluationException(@NotNull String expression, private void handleEvaluationException(@NotNull String expression,
@NotNull AndroidCalculatorDisplayView localDisplay, @NotNull CalculatorDisplay localDisplay,
@NotNull JsclOperation operation, @NotNull JsclOperation operation,
@NotNull Message e) { @NotNull Message e) {
Log.d(CalculatorModel.class.getName(), "Evaluation failed for : " + expression + ". Error message: " + e); Log.d(CalculatorModel.class.getName(), "Evaluation failed for : " + expression + ". Error message: " + e);
@ -330,9 +331,9 @@ public enum CalculatorModel implements CursorControl, HistoryControl<CalculatorH
@Override @Override
public void doHistoryAction(@NotNull HistoryAction historyAction) { public void doHistoryAction(@NotNull HistoryAction historyAction) {
synchronized (AndroidCalculatorHistoryImpl.instance) { synchronized (CalculatorHistory.instance) {
if (AndroidCalculatorHistoryImpl.instance.isActionAvailable(historyAction)) { if (CalculatorHistory.instance.isActionAvailable(historyAction)) {
final CalculatorHistoryState newState = AndroidCalculatorHistoryImpl.instance.doAction(historyAction, getCurrentHistoryState()); final CalculatorHistoryState newState = CalculatorHistory.instance.doAction(historyAction, getCurrentHistoryState());
if (newState != null) { if (newState != null) {
setCurrentHistoryState(newState); setCurrentHistoryState(newState);
} }
@ -342,7 +343,7 @@ public enum CalculatorModel implements CursorControl, HistoryControl<CalculatorH
@Override @Override
public void setCurrentHistoryState(@NotNull CalculatorHistoryState editorHistoryState) { public void setCurrentHistoryState(@NotNull CalculatorHistoryState editorHistoryState) {
synchronized (AndroidCalculatorHistoryImpl.instance) { synchronized (CalculatorHistory.instance) {
Log.d(this.getClass().getName(), "Saved history found: " + editorHistoryState); Log.d(this.getClass().getName(), "Saved history found: " + editorHistoryState);
editorHistoryState.setValuesFromHistory(new TextViewEditorAdapter(this.editor), this.display); editorHistoryState.setValuesFromHistory(new TextViewEditorAdapter(this.editor), this.display);
@ -362,13 +363,13 @@ public enum CalculatorModel implements CursorControl, HistoryControl<CalculatorH
@Override @Override
@NotNull @NotNull
public CalculatorHistoryState getCurrentHistoryState() { public CalculatorHistoryState getCurrentHistoryState() {
synchronized (AndroidCalculatorHistoryImpl.instance) { synchronized (CalculatorHistory.instance) {
return CalculatorHistoryState.newInstance(new TextViewEditorAdapter(this.editor), this.display); return CalculatorHistoryState.newInstance(new TextViewEditorAdapter(this.editor), this.display);
} }
} }
@NotNull @NotNull
public AndroidCalculatorDisplayView getDisplay() { public CalculatorDisplay getDisplay() {
return display; return display;
} }
@ -383,15 +384,13 @@ public enum CalculatorModel implements CursorControl, HistoryControl<CalculatorH
@Override @Override
public void onClick(View v) { public void onClick(View v) {
if (v instanceof CalculatorDisplayView) { if (v instanceof CalculatorDisplay) {
final CalculatorDisplay cd = CalculatorLocatorImpl.getInstance().getCalculatorDisplay(); final CalculatorDisplay cd = (CalculatorDisplay) v;
final CalculatorDisplayViewState displayViewState = cd.getViewState(); if (cd.isValid()) {
final List<CalculatorDisplay.MenuItem> filteredMenuItems = new ArrayList<CalculatorDisplay.MenuItem>(CalculatorDisplay.MenuItem.values().length);
if (displayViewState.isValid()) { for (CalculatorDisplay.MenuItem menuItem : CalculatorDisplay.MenuItem.values()) {
final List<AndroidCalculatorDisplayView.MenuItem> filteredMenuItems = new ArrayList<AndroidCalculatorDisplayView.MenuItem>(AndroidCalculatorDisplayView.MenuItem.values().length); if (menuItem.isItemVisible(cd)) {
for (AndroidCalculatorDisplayView.MenuItem menuItem : AndroidCalculatorDisplayView.MenuItem.values()) {
if (menuItem.isItemVisible(displayViewState)) {
filteredMenuItems.add(menuItem); filteredMenuItems.add(menuItem);
} }
} }
@ -401,7 +400,7 @@ public enum CalculatorModel implements CursorControl, HistoryControl<CalculatorH
} }
} else { } else {
final String errorMessage = displayViewState.getErrorMessage(); final String errorMessage = cd.getErrorMessage();
if (errorMessage != null) { if (errorMessage != null) {
showEvaluationError(activity, errorMessage); showEvaluationError(activity, errorMessage);
} }

View File

@ -0,0 +1,40 @@
/*
* Copyright (c) 2009-2011. Created by serso aka se.solovyev.
* For more information, please, contact se.solovyev@gmail.com
* or visit http://se.solovyev.org
*/
package org.solovyev.android.calculator;
import jscl.math.Generic;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.history.Editor;
import org.solovyev.android.calculator.jscl.JsclOperation;
/**
* User: serso
* Date: 12/17/11
* Time: 9:45 PM
*/
public interface ICalculatorDisplay extends Editor{
boolean isValid();
void setValid(boolean valid);
@Nullable
String getErrorMessage();
void setErrorMessage(@Nullable String errorMessage);
void setJsclOperation(@NotNull JsclOperation jsclOperation);
@NotNull
JsclOperation getJsclOperation();
void setGenericResult(@Nullable Generic genericResult);
@Nullable
Generic getGenericResult();
}

View File

@ -157,7 +157,7 @@ public abstract class AbstractHistoryActivity extends ListActivity {
boolean result = false; boolean result = false;
try { try {
historyState.setSaved(true); historyState.setSaved(true);
if ( CollectionsUtils.contains(historyState, AndroidCalculatorHistoryImpl.instance.getSavedHistory(), new Equalizer<CalculatorHistoryState>() { if ( CollectionsUtils.contains(historyState, CalculatorHistory.instance.getSavedHistory(), new Equalizer<CalculatorHistoryState>() {
@Override @Override
public boolean equals(@Nullable CalculatorHistoryState first, @Nullable CalculatorHistoryState second) { public boolean equals(@Nullable CalculatorHistoryState first, @Nullable CalculatorHistoryState second) {
return first != null && second != null && return first != null && second != null &&

View File

@ -6,6 +6,7 @@
package org.solovyev.android.calculator.history; package org.solovyev.android.calculator.history;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.simpleframework.xml.Element; import org.simpleframework.xml.Element;
import org.simpleframework.xml.Transient; import org.simpleframework.xml.Transient;

View File

@ -1,18 +0,0 @@
package org.solovyev.android.calculator.history;
import android.content.Context;
import android.content.SharedPreferences;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* User: Solovyev_S
* Date: 20.09.12
* Time: 16:07
*/
public interface AndroidCalculatorHistory extends CalculatorHistory {
void load(@Nullable Context context, @Nullable SharedPreferences preferences);
void save(@NotNull Context context);
}

View File

@ -1,145 +0,0 @@
/*
* Copyright (c) 2009-2011. Created by serso aka se.solovyev.
* For more information, please, contact se.solovyev@gmail.com
* or visit http://se.solovyev.org
*/
package org.solovyev.android.calculator.history;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.R;
import org.solovyev.common.history.HistoryAction;
import java.util.List;
/**
* User: serso
* Date: 10/9/11
* Time: 6:35 PM
*/
public enum AndroidCalculatorHistoryImpl implements AndroidCalculatorHistory {
instance;
@NotNull
private final CalculatorHistoryImpl calculatorHistory = new CalculatorHistoryImpl();
@Override
public void load(@Nullable Context context, @Nullable SharedPreferences preferences) {
if (context != null && preferences != null) {
final String value = preferences.getString(context.getString(R.string.p_calc_history), null);
calculatorHistory.fromXml(value);
}
}
@Override
public void save(@NotNull Context context) {
final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
final SharedPreferences.Editor editor = settings.edit();
editor.putString(context.getString(R.string.p_calc_history), calculatorHistory.toXml());
editor.commit();
}
public void clearSavedHistory(@NotNull Context context) {
calculatorHistory.clearSavedHistory();
save(context);
}
public void removeSavedHistory(@NotNull CalculatorHistoryState historyState, @NotNull Context context) {
historyState.setSaved(false);
calculatorHistory.removeSavedHistory(historyState);
save(context);
}
@Override
public boolean isEmpty() {
return calculatorHistory.isEmpty();
}
@Override
public CalculatorHistoryState getLastHistoryState() {
return calculatorHistory.getLastHistoryState();
}
@Override
public boolean isUndoAvailable() {
return calculatorHistory.isUndoAvailable();
}
@Override
public CalculatorHistoryState undo(@Nullable CalculatorHistoryState currentState) {
return calculatorHistory.undo(currentState);
}
@Override
public boolean isRedoAvailable() {
return calculatorHistory.isRedoAvailable();
}
@Override
public CalculatorHistoryState redo(@Nullable CalculatorHistoryState currentState) {
return calculatorHistory.redo(currentState);
}
@Override
public boolean isActionAvailable(@NotNull HistoryAction historyAction) {
return calculatorHistory.isActionAvailable(historyAction);
}
@Override
public CalculatorHistoryState doAction(@NotNull HistoryAction historyAction, @Nullable CalculatorHistoryState currentState) {
return calculatorHistory.doAction(historyAction, currentState);
}
@Override
public void addState(@Nullable CalculatorHistoryState currentState) {
calculatorHistory.addState(currentState);
}
@NotNull
@Override
public List<CalculatorHistoryState> getStates() {
return calculatorHistory.getStates();
}
@Override
public void clear() {
calculatorHistory.clear();
}
@NotNull
public List<CalculatorHistoryState> getSavedHistory() {
return calculatorHistory.getSavedHistory();
}
@NotNull
public CalculatorHistoryState addSavedState(@NotNull CalculatorHistoryState historyState) {
return calculatorHistory.addSavedState(historyState);
}
@Override
public void fromXml(@NotNull String xml) {
calculatorHistory.fromXml(xml);
}
@Override
public String toXml() {
return calculatorHistory.toXml();
}
@Override
public void clearSavedHistory() {
calculatorHistory.clearSavedHistory();
}
@Override
public void removeSavedHistory(@NotNull CalculatorHistoryState historyState) {
calculatorHistory.removeSavedHistory(historyState);
}
}

View File

@ -1,144 +1,138 @@
/* /*
* Copyright (c) 2009-2011. Created by serso aka se.solovyev. * Copyright (c) 2009-2011. Created by serso aka se.solovyev.
* For more information, please, contact se.solovyev@gmail.com * For more information, please, contact se.solovyev@gmail.com
*/ */
package org.solovyev.android.calculator.history; package org.solovyev.android.calculator.history;
import jscl.math.Generic; import jscl.math.Generic;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.simpleframework.xml.Element; import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root; import org.simpleframework.xml.Root;
import org.simpleframework.xml.Transient; import org.simpleframework.xml.Transient;
import org.solovyev.android.calculator.CalculatorDisplay; import org.solovyev.android.calculator.ICalculatorDisplay;
import org.solovyev.android.calculator.CalculatorDisplayViewState; import org.solovyev.android.calculator.jscl.JsclOperation;
import org.solovyev.android.calculator.CalculatorDisplayViewStateImpl;
import org.solovyev.android.calculator.jscl.JsclOperation; /**
import org.solovyev.common.text.StringUtils; * User: serso
* Date: 9/17/11
/** * Time: 11:05 PM
* User: serso */
* Date: 9/17/11
* Time: 11:05 PM @Root
*/ public class CalculatorDisplayHistoryState implements Cloneable {
@Root @Transient
public class CalculatorDisplayHistoryState implements Cloneable { private boolean valid = true;
@Transient @Transient
private boolean valid = true; @Nullable
private String errorMessage = null;
@Transient
@Nullable @Element
private String errorMessage = null; @NotNull
private EditorHistoryState editorState;
@Element
@NotNull @Element
private EditorHistoryState editorState; @NotNull
private JsclOperation jsclOperation;
@Element
@NotNull @Transient
private JsclOperation jsclOperation; @Nullable
private Generic genericResult;
@Transient
@Nullable private CalculatorDisplayHistoryState() {
private Generic genericResult; // for xml
}
private CalculatorDisplayHistoryState() {
// for xml @NotNull
} public static CalculatorDisplayHistoryState newInstance(@NotNull ICalculatorDisplay display) {
final CalculatorDisplayHistoryState result = new CalculatorDisplayHistoryState();
@NotNull
public static CalculatorDisplayHistoryState newInstance(@NotNull CalculatorDisplay display) { result.editorState = EditorHistoryState.newInstance(display);
final CalculatorDisplayHistoryState result = new CalculatorDisplayHistoryState(); result.valid = display.isValid();
result.jsclOperation = display.getJsclOperation();
result.editorState = EditorHistoryState.newInstance(display.getViewState()); result.genericResult = display.getGenericResult();
result.errorMessage = display.getErrorMessage();
final CalculatorDisplayViewState displayViewState = display.getViewState();
return result;
result.valid = displayViewState.isValid(); }
result.jsclOperation = displayViewState.getOperation();
result.genericResult = displayViewState.getResult(); public void setValuesFromHistory(@NotNull ICalculatorDisplay display) {
result.errorMessage = displayViewState.getErrorMessage(); this.getEditorState().setValuesFromHistory(display);
display.setValid(this.isValid());
return result; display.setErrorMessage(this.getErrorMessage());
} display.setJsclOperation(this.getJsclOperation());
display.setGenericResult(this.getGenericResult());
public void setValuesFromHistory(@NotNull CalculatorDisplay display) { }
if ( this.isValid() ) {
display.setViewState(CalculatorDisplayViewStateImpl.newValidState(this.getJsclOperation(), this.getGenericResult(), StringUtils.getNotEmpty(this.getEditorState().getText(), ""), this.getEditorState().getCursorPosition()));
} else { public boolean isValid() {
display.setViewState(CalculatorDisplayViewStateImpl.newErrorState(this.getJsclOperation(), StringUtils.getNotEmpty(this.getErrorMessage(), ""))); return valid;
} }
}
@NotNull
public EditorHistoryState getEditorState() {
public boolean isValid() { return editorState;
return valid; }
}
@NotNull
@NotNull public JsclOperation getJsclOperation() {
public EditorHistoryState getEditorState() { return jsclOperation;
return editorState; }
}
@Nullable
@NotNull public String getErrorMessage() {
public JsclOperation getJsclOperation() { return errorMessage;
return jsclOperation; }
}
@Nullable
@Nullable public Generic getGenericResult() {
public String getErrorMessage() { return genericResult;
return errorMessage; }
}
@Nullable @Override
public Generic getGenericResult() { public boolean equals(Object o) {
return genericResult; if (this == o) return true;
} if (o == null || getClass() != o.getClass()) return false;
CalculatorDisplayHistoryState that = (CalculatorDisplayHistoryState) o;
@Override
public boolean equals(Object o) { if (!editorState.equals(that.editorState)) return false;
if (this == o) return true; if (jsclOperation != that.jsclOperation) return false;
if (o == null || getClass() != o.getClass()) return false;
return true;
CalculatorDisplayHistoryState that = (CalculatorDisplayHistoryState) o; }
if (!editorState.equals(that.editorState)) return false; @Override
if (jsclOperation != that.jsclOperation) return false; public int hashCode() {
int result = editorState.hashCode();
return true; result = 31 * result + jsclOperation.hashCode();
} return result;
}
@Override
public int hashCode() { @Override
int result = editorState.hashCode(); public String toString() {
result = 31 * result + jsclOperation.hashCode(); return "CalculatorDisplayHistoryState{" +
return result; "valid=" + valid +
} ", errorMessage='" + errorMessage + '\'' +
", editorHistoryState=" + editorState +
@Override ", jsclOperation=" + jsclOperation +
public String toString() { '}';
return "CalculatorDisplayHistoryState{" + }
"valid=" + valid +
", errorMessage='" + errorMessage + '\'' + @Override
", editorHistoryState=" + editorState + protected CalculatorDisplayHistoryState clone() {
", jsclOperation=" + jsclOperation + try {
'}'; final CalculatorDisplayHistoryState clone = (CalculatorDisplayHistoryState) super.clone();
}
clone.editorState = this.editorState.clone();
@Override
protected CalculatorDisplayHistoryState clone() { return clone;
try { } catch (CloneNotSupportedException e) {
final CalculatorDisplayHistoryState clone = (CalculatorDisplayHistoryState) super.clone(); throw new RuntimeException(e);
}
clone.editorState = this.editorState.clone(); }
}
return clone;
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
}

View File

@ -0,0 +1,149 @@
/*
* Copyright (c) 2009-2011. Created by serso aka se.solovyev.
* For more information, please, contact se.solovyev@gmail.com
* or visit http://se.solovyev.org
*/
package org.solovyev.android.calculator.history;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.R;
import org.solovyev.common.history.HistoryAction;
import org.solovyev.common.history.HistoryHelper;
import org.solovyev.common.history.SimpleHistoryHelper;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* User: serso
* Date: 10/9/11
* Time: 6:35 PM
*/
public enum CalculatorHistory implements HistoryHelper<CalculatorHistoryState> {
instance;
// todo serso: not synchronized
private int counter = 0;
@NotNull
private final HistoryHelper<CalculatorHistoryState> history = new SimpleHistoryHelper<CalculatorHistoryState>();
@NotNull
private final List<CalculatorHistoryState> savedHistory = new ArrayList<CalculatorHistoryState> ();
@Override
public boolean isEmpty() {
return this.history.isEmpty();
}
@Override
public CalculatorHistoryState getLastHistoryState() {
return this.history.getLastHistoryState();
}
@Override
public boolean isUndoAvailable() {
return history.isUndoAvailable();
}
@Override
public CalculatorHistoryState undo(@Nullable CalculatorHistoryState currentState) {
return history.undo(currentState);
}
@Override
public boolean isRedoAvailable() {
return history.isRedoAvailable();
}
@Override
public CalculatorHistoryState redo(@Nullable CalculatorHistoryState currentState) {
return history.redo(currentState);
}
@Override
public boolean isActionAvailable(@NotNull HistoryAction historyAction) {
return history.isActionAvailable(historyAction);
}
@Override
public CalculatorHistoryState doAction(@NotNull HistoryAction historyAction, @Nullable CalculatorHistoryState currentState) {
return history.doAction(historyAction, currentState);
}
@Override
public void addState(@Nullable CalculatorHistoryState currentState) {
history.addState(currentState);
}
@NotNull
@Override
public List<CalculatorHistoryState> getStates() {
return history.getStates();
}
@Override
public void clear() {
this.history.clear();
}
public void load(@Nullable Context context, @Nullable SharedPreferences preferences) {
if (context != null && preferences != null) {
final String value = preferences.getString(context.getString(R.string.p_calc_history), null);
this.savedHistory.clear();
HistoryUtils.fromXml(value, this.savedHistory);
for (CalculatorHistoryState historyState : savedHistory) {
historyState.setSaved(true);
historyState.setId(counter++);
}
}
}
public void save(@NotNull Context context) {
final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
final SharedPreferences.Editor editor = settings.edit();
editor.putString(context.getString(R.string.p_calc_history), HistoryUtils.toXml(this.savedHistory));
editor.commit();
}
@NotNull
public List<CalculatorHistoryState> getSavedHistory() {
return Collections.unmodifiableList(savedHistory);
}
@NotNull
public CalculatorHistoryState addSavedState(@NotNull CalculatorHistoryState historyState) {
if (historyState.isSaved()) {
return historyState;
} else {
final CalculatorHistoryState savedState = historyState.clone();
savedState.setId(counter++);
savedState.setSaved(true);
savedHistory.add(savedState);
return savedState;
}
}
public void clearSavedHistory(@NotNull Context context) {
this.savedHistory.clear();
save(context);
}
public void removeSavedHistory(@NotNull CalculatorHistoryState historyState, @NotNull Context context) {
historyState.setSaved(false);
this.savedHistory.remove(historyState);
save(context);
}
}

View File

@ -1,111 +1,110 @@
/* /*
* Copyright (c) 2009-2011. Created by serso aka se.solovyev. * Copyright (c) 2009-2011. Created by serso aka se.solovyev.
* For more information, please, contact se.solovyev@gmail.com * For more information, please, contact se.solovyev@gmail.com
*/ */
package org.solovyev.android.calculator.history; package org.solovyev.android.calculator.history;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.simpleframework.xml.Element; import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root; import org.simpleframework.xml.Root;
import org.solovyev.android.calculator.CalculatorDisplay; import org.solovyev.android.calculator.ICalculatorDisplay;
import org.solovyev.android.calculator.Editor;
/**
/** * User: serso
* User: serso * Date: 9/11/11
* Date: 9/11/11 * Time: 12:16 AM
* Time: 12:16 AM */
*/
@Root
@Root public class CalculatorHistoryState extends AbstractHistoryState {
public class CalculatorHistoryState extends AbstractHistoryState {
@Element
@Element @NotNull
@NotNull private EditorHistoryState editorState;
private EditorHistoryState editorState;
@Element
@Element @NotNull
@NotNull private CalculatorDisplayHistoryState displayState;
private CalculatorDisplayHistoryState displayState;
private CalculatorHistoryState() {
private CalculatorHistoryState() { // for xml
// for xml }
}
private CalculatorHistoryState(@NotNull EditorHistoryState editorState,
private CalculatorHistoryState(@NotNull EditorHistoryState editorState, @NotNull CalculatorDisplayHistoryState displayState) {
@NotNull CalculatorDisplayHistoryState displayState) { this.editorState = editorState;
this.editorState = editorState; this.displayState = displayState;
this.displayState = displayState; }
}
public static CalculatorHistoryState newInstance(@NotNull Editor editor, @NotNull ICalculatorDisplay display) {
public static CalculatorHistoryState newInstance(@NotNull Editor editor, @NotNull CalculatorDisplay display) { final EditorHistoryState editorHistoryState = EditorHistoryState.newInstance(editor);
final EditorHistoryState editorHistoryState = EditorHistoryState.newInstance(editor); final CalculatorDisplayHistoryState displayHistoryState = CalculatorDisplayHistoryState.newInstance(display);
final CalculatorDisplayHistoryState displayHistoryState = CalculatorDisplayHistoryState.newInstance(display); return new CalculatorHistoryState(editorHistoryState, displayHistoryState);
return new CalculatorHistoryState(editorHistoryState, displayHistoryState); }
}
@NotNull
@NotNull public EditorHistoryState getEditorState() {
public EditorHistoryState getEditorState() { return editorState;
return editorState; }
}
public void setEditorState(@NotNull EditorHistoryState editorState) {
public void setEditorState(@NotNull EditorHistoryState editorState) { this.editorState = editorState;
this.editorState = editorState; }
}
@NotNull
@NotNull public CalculatorDisplayHistoryState getDisplayState() {
public CalculatorDisplayHistoryState getDisplayState() { return displayState;
return displayState; }
}
public void setDisplayState(@NotNull CalculatorDisplayHistoryState displayState) {
public void setDisplayState(@NotNull CalculatorDisplayHistoryState displayState) { this.displayState = displayState;
this.displayState = displayState; }
}
@Override
@Override public String toString() {
public String toString() { return "CalculatorHistoryState{" +
return "CalculatorHistoryState{" + "editorState=" + editorState +
"editorState=" + editorState + ", displayState=" + displayState +
", displayState=" + displayState + '}';
'}'; }
}
@Override
@Override public boolean equals(Object o) {
public boolean equals(Object o) { if (this == o) return true;
if (this == o) return true; if (o == null || getClass() != o.getClass()) return false;
if (o == null || getClass() != o.getClass()) return false;
CalculatorHistoryState that = (CalculatorHistoryState) o;
CalculatorHistoryState that = (CalculatorHistoryState) o;
if (this.isSaved() != that.isSaved()) return false;
if (this.isSaved() != that.isSaved()) return false; if (this.getId() != that.getId()) return false;
if (this.getId() != that.getId()) return false; if (!displayState.equals(that.displayState)) return false;
if (!displayState.equals(that.displayState)) return false; if (!editorState.equals(that.editorState)) return false;
if (!editorState.equals(that.editorState)) return false;
return true;
return true; }
}
@Override
@Override public int hashCode() {
public int hashCode() { int result = Boolean.valueOf(isSaved()).hashCode();
int result = Boolean.valueOf(isSaved()).hashCode(); result = 31 * result + getId();
result = 31 * result + getId(); result = 31 * result + editorState.hashCode();
result = 31 * result + editorState.hashCode(); result = 31 * result + displayState.hashCode();
result = 31 * result + displayState.hashCode(); return result;
return result; }
}
public void setValuesFromHistory(@NotNull Editor editor, @NotNull ICalculatorDisplay display) {
public void setValuesFromHistory(@NotNull Editor editor, @NotNull CalculatorDisplay display) { this.getEditorState().setValuesFromHistory(editor);
this.getEditorState().setValuesFromHistory(editor); this.getDisplayState().setValuesFromHistory(display);
this.getDisplayState().setValuesFromHistory(display); }
}
@Override
@Override protected CalculatorHistoryState clone() {
protected CalculatorHistoryState clone() { final CalculatorHistoryState clone = (CalculatorHistoryState)super.clone();
final CalculatorHistoryState clone = (CalculatorHistoryState)super.clone();
clone.editorState = this.editorState.clone();
clone.editorState = this.editorState.clone(); clone.displayState = this.displayState.clone();
clone.displayState = this.displayState.clone();
return clone;
return clone; }
} }
}

View File

@ -4,7 +4,7 @@
* or visit http://se.solovyev.org * or visit http://se.solovyev.org
*/ */
package org.solovyev.android.calculator; package org.solovyev.android.calculator.history;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;

View File

@ -1,99 +1,87 @@
/* /*
* Copyright (c) 2009-2011. Created by serso aka se.solovyev. * Copyright (c) 2009-2011. Created by serso aka se.solovyev.
* For more information, please, contact se.solovyev@gmail.com * For more information, please, contact se.solovyev@gmail.com
*/ */
package org.solovyev.android.calculator.history; package org.solovyev.android.calculator.history;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.simpleframework.xml.Element; import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root; import org.simpleframework.xml.Root;
import org.solovyev.android.calculator.CalculatorDisplayViewState;
import org.solovyev.android.calculator.Editor; @Root
public class EditorHistoryState implements Cloneable{
@Root
public class EditorHistoryState implements Cloneable{ @Element
private int cursorPosition;
@Element
private int cursorPosition; @Element(required = false)
@Nullable
@Element(required = false) private String text;
@Nullable
private String text; private EditorHistoryState() {
// for xml
private EditorHistoryState() { }
// for xml
} @NotNull
public static EditorHistoryState newInstance(@NotNull Editor editor) {
@NotNull final EditorHistoryState result = new EditorHistoryState();
public static EditorHistoryState newInstance(@NotNull Editor editor) {
final EditorHistoryState result = new EditorHistoryState(); result.text = String.valueOf(editor.getText());
result.cursorPosition = editor.getSelection();
result.text = String.valueOf(editor.getText());
result.cursorPosition = editor.getSelection(); return result;
}
return result;
} public void setValuesFromHistory(@NotNull Editor editor) {
editor.setText(this.getText());
@NotNull editor.setSelection(this.getCursorPosition());
public static EditorHistoryState newInstance(@NotNull CalculatorDisplayViewState viewState) { }
final EditorHistoryState result = new EditorHistoryState();
@Nullable
result.text = viewState.getText(); public String getText() {
result.cursorPosition = viewState.getSelection(); return text;
}
return result;
} public int getCursorPosition() {
return cursorPosition;
public void setValuesFromHistory(@NotNull Editor editor) { }
editor.setText(this.getText());
editor.setSelection(this.getCursorPosition()); @Override
} public boolean equals(Object o) {
if (this == o) return true;
@Nullable if (!(o instanceof EditorHistoryState)) return false;
public String getText() {
return text; EditorHistoryState that = (EditorHistoryState) o;
}
if (cursorPosition != that.cursorPosition) return false;
public int getCursorPosition() { if (text != null ? !text.equals(that.text) : that.text != null) return false;
return cursorPosition;
} return true;
}
@Override
public boolean equals(Object o) { @Override
if (this == o) return true; public int hashCode() {
if (!(o instanceof EditorHistoryState)) return false; int result = cursorPosition;
result = 31 * result + (text != null ? text.hashCode() : 0);
EditorHistoryState that = (EditorHistoryState) o; return result;
}
if (cursorPosition != that.cursorPosition) return false;
if (text != null ? !text.equals(that.text) : that.text != null) return false; @Override
public String toString() {
return true; return "EditorHistoryState{" +
} "cursorPosition=" + cursorPosition +
", text='" + text + '\'' +
@Override '}';
public int hashCode() { }
int result = cursorPosition;
result = 31 * result + (text != null ? text.hashCode() : 0); @Override
return result; protected EditorHistoryState clone() {
} try {
return (EditorHistoryState)super.clone();
@Override } catch (CloneNotSupportedException e) {
public String toString() { throw new UnsupportedOperationException(e);
return "EditorHistoryState{" + }
"cursorPosition=" + cursorPosition + }
", text='" + text + '\'' + }
'}';
}
@Override
protected EditorHistoryState clone() {
try {
return (EditorHistoryState)super.clone();
} catch (CloneNotSupportedException e) {
throw new UnsupportedOperationException(e);
}
}
}

View File

@ -26,12 +26,12 @@ public class HistoryActivityTab extends AbstractHistoryActivity {
@NotNull @NotNull
@Override @Override
protected List<CalculatorHistoryState> getHistoryItems() { protected List<CalculatorHistoryState> getHistoryItems() {
return new ArrayList<CalculatorHistoryState>(AndroidCalculatorHistoryImpl.instance.getStates()); return new ArrayList<CalculatorHistoryState>(CalculatorHistory.instance.getStates());
} }
@Override @Override
protected void clearHistory() { protected void clearHistory() {
AndroidCalculatorHistoryImpl.instance.clear(); CalculatorHistory.instance.clear();
getAdapter().clear(); getAdapter().clear();
} }
} }

View File

@ -96,7 +96,7 @@ public enum HistoryItemMenuItem implements LabeledMenuItem<HistoryItemMenuData>
final CalculatorHistoryState historyState = data.getHistoryState(); final CalculatorHistoryState historyState = data.getHistoryState();
if (historyState.isSaved()) { if (historyState.isSaved()) {
data.getAdapter().remove(historyState); data.getAdapter().remove(historyState);
AndroidCalculatorHistoryImpl.instance.removeSavedHistory(historyState, context); CalculatorHistory.instance.removeSavedHistory(historyState, context);
Toast.makeText(context, context.getText(R.string.c_history_was_removed), Toast.LENGTH_LONG).show(); Toast.makeText(context, context.getText(R.string.c_history_was_removed), Toast.LENGTH_LONG).show();
data.getAdapter().notifyDataSetChanged(); data.getAdapter().notifyDataSetChanged();
} }
@ -122,14 +122,14 @@ public enum HistoryItemMenuItem implements LabeledMenuItem<HistoryItemMenuData>
@Override @Override
public void onClick(DialogInterface dialog, int which) { public void onClick(DialogInterface dialog, int which) {
if (save) { if (save) {
final CalculatorHistoryState savedHistoryItem = AndroidCalculatorHistoryImpl.instance.addSavedState(historyState); final CalculatorHistoryState savedHistoryItem = CalculatorHistory.instance.addSavedState(historyState);
savedHistoryItem.setComment(comment.getText().toString()); savedHistoryItem.setComment(comment.getText().toString());
AndroidCalculatorHistoryImpl.instance.save(context); CalculatorHistory.instance.save(context);
// we don't need to add element to the adapter as adapter of another activity must be updated and not this // we don't need to add element to the adapter as adapter of another activity must be updated and not this
//data.getAdapter().add(savedHistoryItem); //data.getAdapter().add(savedHistoryItem);
} else { } else {
historyState.setComment(comment.getText().toString()); historyState.setComment(comment.getText().toString());
AndroidCalculatorHistoryImpl.instance.save(context); CalculatorHistory.instance.save(context);
} }
data.getAdapter().notifyDataSetChanged(); data.getAdapter().notifyDataSetChanged();
Toast.makeText(context, context.getText(R.string.c_history_saved), Toast.LENGTH_LONG).show(); Toast.makeText(context, context.getText(R.string.c_history_saved), Toast.LENGTH_LONG).show();

View File

@ -26,12 +26,12 @@ public class SavedHistoryActivityTab extends AbstractHistoryActivity {
@NotNull @NotNull
@Override @Override
protected List<CalculatorHistoryState> getHistoryItems() { protected List<CalculatorHistoryState> getHistoryItems() {
return new ArrayList<CalculatorHistoryState>(AndroidCalculatorHistoryImpl.instance.getSavedHistory()); return new ArrayList<CalculatorHistoryState>(CalculatorHistory.instance.getSavedHistory());
} }
@Override @Override
protected void clearHistory() { protected void clearHistory() {
AndroidCalculatorHistoryImpl.instance.clearSavedHistory(this); CalculatorHistory.instance.clearSavedHistory(this);
getAdapter().clear(); getAdapter().clear();
} }
} }

View File

@ -10,7 +10,6 @@ import android.widget.EditText;
import android.widget.TextView; import android.widget.TextView;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.Editor;
/** /**
* User: serso * User: serso

View File

@ -8,8 +8,8 @@ package org.solovyev.android.calculator.jscl;
import jscl.math.Generic; import jscl.math.Generic;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.CalculatorParseException; import org.solovyev.android.calculator.model.CalculatorParseException;
import org.solovyev.android.calculator.text.TextProcessor; import org.solovyev.android.calculator.model.TextProcessor;
/** /**
* User: serso * User: serso

View File

@ -9,10 +9,10 @@ package org.solovyev.android.calculator.jscl;
import jscl.math.Generic; import jscl.math.Generic;
import jscl.text.ParseException; import jscl.text.ParseException;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.CalculatorLocatorImpl; import org.solovyev.android.calculator.model.CalculatorEngine;
import org.solovyev.android.calculator.text.DummyTextProcessor; import org.solovyev.android.calculator.model.DummyTextProcessor;
import org.solovyev.android.calculator.text.FromJsclSimplifyTextProcessor; import org.solovyev.android.calculator.model.FromJsclSimplifyTextProcessor;
import org.solovyev.android.calculator.text.TextProcessor; import org.solovyev.android.calculator.model.TextProcessor;
public enum JsclOperation { public enum JsclOperation {
@ -42,11 +42,11 @@ public enum JsclOperation {
public final String evaluate(@NotNull String expression) throws ParseException { public final String evaluate(@NotNull String expression) throws ParseException {
switch (this) { switch (this) {
case simplify: case simplify:
return CalculatorLocatorImpl.getInstance().getCalculatorEngine().getEngine().simplify(expression); return CalculatorEngine.instance.getEngine().simplify(expression);
case elementary: case elementary:
return CalculatorLocatorImpl.getInstance().getCalculatorEngine().getEngine().elementary(expression); return CalculatorEngine.instance.getEngine().elementary(expression);
case numeric: case numeric:
return CalculatorLocatorImpl.getInstance().getCalculatorEngine().getEngine().evaluate(expression); return CalculatorEngine.instance.getEngine().evaluate(expression);
default: default:
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
@ -56,11 +56,11 @@ public enum JsclOperation {
public final Generic evaluateGeneric(@NotNull String expression) throws ParseException { public final Generic evaluateGeneric(@NotNull String expression) throws ParseException {
switch (this) { switch (this) {
case simplify: case simplify:
return CalculatorLocatorImpl.getInstance().getCalculatorEngine().getEngine().simplifyGeneric(expression); return CalculatorEngine.instance.getEngine().simplifyGeneric(expression);
case elementary: case elementary:
return CalculatorLocatorImpl.getInstance().getCalculatorEngine().getEngine().elementaryGeneric(expression); return CalculatorEngine.instance.getEngine().elementaryGeneric(expression);
case numeric: case numeric:
return CalculatorLocatorImpl.getInstance().getCalculatorEngine().getEngine().evaluateGeneric(expression); return CalculatorEngine.instance.getEngine().evaluateGeneric(expression);
default: default:
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }

View File

@ -10,10 +10,10 @@ import jscl.NumeralBase;
import jscl.math.function.Constants; import jscl.math.function.Constants;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.CalculatorLocatorImpl;
import org.solovyev.common.JPredicate; import org.solovyev.common.JPredicate;
import org.solovyev.common.StartsWithFinder; import org.solovyev.common.StartsWithFinder;
import org.solovyev.android.calculator.CalculatorParseException; import org.solovyev.android.calculator.model.CalculatorEngine;
import org.solovyev.android.calculator.model.CalculatorParseException;
import org.solovyev.common.collections.CollectionsUtils; import org.solovyev.common.collections.CollectionsUtils;
import java.util.*; import java.util.*;
@ -26,8 +26,11 @@ public enum MathType {
private final List<String> tokens = new ArrayList<String>(10); private final List<String> tokens = new ArrayList<String>(10);
{ {
for (NumeralBase numeralBase : NumeralBase.values()) { for (NumeralBase numeralBase : NumeralBase.values()) {
tokens.add(numeralBase.getJsclPrefix()); final String jsclPrefix = numeralBase.getJsclPrefix();
} if (jsclPrefix != null) {
tokens.add(jsclPrefix);
}
}
} }
@NotNull @NotNull
@ -57,7 +60,7 @@ public enum MathType {
@NotNull @NotNull
@Override @Override
public List<String> getTokens() { public List<String> getTokens() {
return CalculatorLocatorImpl.getInstance().getCalculatorEngine().getPostfixFunctionsRegistry().getNames(); return CalculatorEngine.instance.getPostfixFunctionsRegistry().getNames();
} }
}, },
@ -101,7 +104,7 @@ public enum MathType {
@NotNull @NotNull
@Override @Override
public List<String> getTokens() { public List<String> getTokens() {
return CalculatorLocatorImpl.getInstance().getCalculatorEngine().getFunctionsRegistry().getNames(); return CalculatorEngine.instance.getFunctionsRegistry().getNames();
} }
}, },
@ -109,7 +112,7 @@ public enum MathType {
@NotNull @NotNull
@Override @Override
public List<String> getTokens() { public List<String> getTokens() {
return CalculatorLocatorImpl.getInstance().getCalculatorEngine().getOperatorsRegistry().getNames(); return CalculatorEngine.instance.getOperatorsRegistry().getNames();
} }
}, },
@ -117,7 +120,7 @@ public enum MathType {
@NotNull @NotNull
@Override @Override
public List<String> getTokens() { public List<String> getTokens() {
return CalculatorLocatorImpl.getInstance().getCalculatorEngine().getVarsRegistry().getNames(); return CalculatorEngine.instance.getVarsRegistry().getNames();
} }
@Override @Override

View File

@ -4,7 +4,7 @@
* or visit http://se.solovyev.org * or visit http://se.solovyev.org
*/ */
package org.solovyev.android.calculator; package org.solovyev.android.calculator.model;
import jscl.MathEngine; import jscl.MathEngine;
import jscl.NumeralBase; import jscl.NumeralBase;

View File

@ -1,404 +1,425 @@
/* /*
* Copyright (c) 2009-2011. Created by serso aka se.solovyev. * Copyright (c) 2009-2011. Created by serso aka se.solovyev.
* For more information, please, contact se.solovyev@gmail.com * For more information, please, contact se.solovyev@gmail.com
*/ */
package org.solovyev.android.calculator.model; package org.solovyev.android.calculator.model;
import android.content.Context; import android.content.Context;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import jscl.*; import jscl.*;
import jscl.math.Generic; import jscl.math.Generic;
import jscl.math.function.Function; import jscl.math.function.Function;
import jscl.math.function.IConstant; import jscl.math.function.IConstant;
import jscl.math.operator.Operator; import jscl.math.operator.Operator;
import jscl.text.ParseInterruptedException; import jscl.text.ParseInterruptedException;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.*; import org.solovyev.android.calculator.CalculatorApplication;
import org.solovyev.android.calculator.jscl.JsclOperation; import org.solovyev.android.calculator.R;
import org.solovyev.android.calculator.text.TextProcessor; import org.solovyev.android.calculator.jscl.JsclOperation;
import org.solovyev.android.msg.AndroidMessage; import org.solovyev.android.prefs.BooleanPreference;
import org.solovyev.android.prefs.BooleanPreference; import org.solovyev.android.prefs.Preference;
import org.solovyev.android.prefs.Preference; import org.solovyev.android.prefs.StringPreference;
import org.solovyev.android.prefs.StringPreference; import org.solovyev.common.MutableObject;
import org.solovyev.common.MutableObject; import org.solovyev.common.msg.MessageRegistry;
import org.solovyev.common.msg.MessageRegistry; import org.solovyev.common.text.EnumMapper;
import org.solovyev.common.msg.MessageType; import org.solovyev.common.text.NumberMapper;
import org.solovyev.common.text.EnumMapper; import org.solovyev.common.text.StringUtils;
import org.solovyev.common.text.NumberMapper;
import org.solovyev.common.text.StringUtils; import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.text.DecimalFormatSymbols; import java.util.Collections;
import java.util.ArrayList; import java.util.List;
import java.util.Collections; import java.util.concurrent.CountDownLatch;
import java.util.List; import java.util.concurrent.TimeUnit;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit; /**
* User: serso
/** * Date: 9/12/11
* User: serso * Time: 11:38 PM
* Date: 9/12/11 */
* Time: 11:38 PM
*/ public enum CalculatorEngine {
public enum CalculatorEngine implements JCalculatorEngine { instance;
instance; private static final String GROUPING_SEPARATOR_P_KEY = "org.solovyev.android.calculator.CalculatorActivity_calc_grouping_separator";
private static final String GROUPING_SEPARATOR_P_KEY = "org.solovyev.android.calculator.CalculatorActivity_calc_grouping_separator"; private static final String MULTIPLICATION_SIGN_P_KEY = "org.solovyev.android.calculator.CalculatorActivity_calc_multiplication_sign";
private static final String MULTIPLICATION_SIGN_DEFAULT = "×";
private static final String MULTIPLICATION_SIGN_P_KEY = "org.solovyev.android.calculator.CalculatorActivity_calc_multiplication_sign";
private static final String MULTIPLICATION_SIGN_DEFAULT = "×"; private static final String MAX_CALCULATION_TIME_P_KEY = "calculation.max_calculation_time";
private static final String MAX_CALCULATION_TIME_DEFAULT = "5";
private static final String MAX_CALCULATION_TIME_P_KEY = "calculation.max_calculation_time";
private static final String MAX_CALCULATION_TIME_DEFAULT = "5"; private static final String SCIENCE_NOTATION_P_KEY = "calculation.output.science_notation";
private static final boolean SCIENCE_NOTATION_DEFAULT = false;
private static final String SCIENCE_NOTATION_P_KEY = "calculation.output.science_notation";
private static final boolean SCIENCE_NOTATION_DEFAULT = false; private static final String ROUND_RESULT_P_KEY = "org.solovyev.android.calculator.CalculatorModel_round_result";
private static final boolean ROUND_RESULT_DEFAULT = true;
private static final String ROUND_RESULT_P_KEY = "org.solovyev.android.calculator.CalculatorModel_round_result";
private static final boolean ROUND_RESULT_DEFAULT = true; private static final String RESULT_PRECISION_P_KEY = "org.solovyev.android.calculator.CalculatorModel_result_precision";
private static final String RESULT_PRECISION_DEFAULT = "5";
private static final String RESULT_PRECISION_P_KEY = "org.solovyev.android.calculator.CalculatorModel_result_precision";
private static final String RESULT_PRECISION_DEFAULT = "5"; private static final String NUMERAL_BASES_P_KEY = "org.solovyev.android.calculator.CalculatorActivity_numeral_bases";
private static final String NUMERAL_BASES_DEFAULT = "dec";
private static final String NUMERAL_BASES_P_KEY = "org.solovyev.android.calculator.CalculatorActivity_numeral_bases";
private static final String NUMERAL_BASES_DEFAULT = "dec"; private static final String ANGLE_UNITS_P_KEY = "org.solovyev.android.calculator.CalculatorActivity_angle_units";
private static final String ANGLE_UNITS_DEFAULT = "deg";
private static final String ANGLE_UNITS_P_KEY = "org.solovyev.android.calculator.CalculatorActivity_angle_units";
private static final String ANGLE_UNITS_DEFAULT = "deg"; public static class Preferences {
public static final Preference<String> groupingSeparator = StringPreference.newInstance(GROUPING_SEPARATOR_P_KEY, JsclMathEngine.GROUPING_SEPARATOR_DEFAULT);
public static class Preferences { public static final Preference<String> multiplicationSign = StringPreference.newInstance(MULTIPLICATION_SIGN_P_KEY, MULTIPLICATION_SIGN_DEFAULT);
public static final Preference<String> groupingSeparator = StringPreference.newInstance(GROUPING_SEPARATOR_P_KEY, JsclMathEngine.GROUPING_SEPARATOR_DEFAULT); public static final Preference<Integer> precision = StringPreference.newInstance(RESULT_PRECISION_P_KEY, RESULT_PRECISION_DEFAULT, new NumberMapper<Integer>(Integer.class));
public static final Preference<String> multiplicationSign = StringPreference.newInstance(MULTIPLICATION_SIGN_P_KEY, MULTIPLICATION_SIGN_DEFAULT); public static final Preference<Boolean> roundResult = new BooleanPreference(ROUND_RESULT_P_KEY, ROUND_RESULT_DEFAULT);
public static final Preference<Integer> precision = StringPreference.newInstance(RESULT_PRECISION_P_KEY, RESULT_PRECISION_DEFAULT, new NumberMapper<Integer>(Integer.class)); public static final Preference<NumeralBase> numeralBase = StringPreference.newInstance(NUMERAL_BASES_P_KEY, NUMERAL_BASES_DEFAULT, EnumMapper.newInstance(NumeralBase.class));
public static final Preference<Boolean> roundResult = new BooleanPreference(ROUND_RESULT_P_KEY, ROUND_RESULT_DEFAULT); public static final Preference<AngleUnit> angleUnit = StringPreference.newInstance(ANGLE_UNITS_P_KEY, ANGLE_UNITS_DEFAULT, EnumMapper.newInstance(AngleUnit.class));
public static final Preference<NumeralBase> numeralBase = StringPreference.newInstance(NUMERAL_BASES_P_KEY, NUMERAL_BASES_DEFAULT, EnumMapper.newInstance(NumeralBase.class)); public static final Preference<Boolean> scienceNotation = new BooleanPreference(SCIENCE_NOTATION_P_KEY, SCIENCE_NOTATION_DEFAULT);
public static final Preference<AngleUnit> angleUnit = StringPreference.newInstance(ANGLE_UNITS_P_KEY, ANGLE_UNITS_DEFAULT, EnumMapper.newInstance(AngleUnit.class)); public static final Preference<Integer> maxCalculationTime = StringPreference.newInstance(MAX_CALCULATION_TIME_P_KEY, MAX_CALCULATION_TIME_DEFAULT, new NumberMapper<Integer>(Integer.class));
public static final Preference<Boolean> scienceNotation = new BooleanPreference(SCIENCE_NOTATION_P_KEY, SCIENCE_NOTATION_DEFAULT);
public static final Preference<Integer> maxCalculationTime = StringPreference.newInstance(MAX_CALCULATION_TIME_P_KEY, MAX_CALCULATION_TIME_DEFAULT, new NumberMapper<Integer>(Integer.class)); private static final List<String> preferenceKeys = new ArrayList<String>();
private static final List<String> preferenceKeys = new ArrayList<String>(); static {
preferenceKeys.add(groupingSeparator.getKey());
static { preferenceKeys.add(multiplicationSign.getKey());
preferenceKeys.add(groupingSeparator.getKey()); preferenceKeys.add(precision.getKey());
preferenceKeys.add(multiplicationSign.getKey()); preferenceKeys.add(roundResult.getKey());
preferenceKeys.add(precision.getKey()); preferenceKeys.add(numeralBase.getKey());
preferenceKeys.add(roundResult.getKey()); preferenceKeys.add(angleUnit.getKey());
preferenceKeys.add(numeralBase.getKey()); preferenceKeys.add(scienceNotation.getKey());
preferenceKeys.add(angleUnit.getKey()); preferenceKeys.add(maxCalculationTime.getKey());
preferenceKeys.add(scienceNotation.getKey()); }
preferenceKeys.add(maxCalculationTime.getKey());
} @NotNull
public static List<String> getPreferenceKeys() {
@NotNull return Collections.unmodifiableList(preferenceKeys);
public static List<String> getPreferenceKeys() { }
return Collections.unmodifiableList(preferenceKeys); }
}
} @NotNull
private final Object lock = new Object();
@NotNull
private final Object lock = new Object(); @NotNull
private MathEngine engine = JsclMathEngine.instance;
@NotNull
private MathEngine engine = JsclMathEngine.instance; @NotNull
public final TextProcessor<PreparedExpression, String> preprocessor = ToJsclTextProcessor.getInstance();
@NotNull
public final TextProcessor<PreparedExpression, String> preprocessor = ToJsclTextProcessor.getInstance(); @NotNull
private final AndroidMathRegistry<IConstant> varsRegistry = new AndroidVarsRegistryImpl(engine.getConstantsRegistry());
@NotNull
private final AndroidMathRegistry<IConstant> varsRegistry = new AndroidVarsRegistryImpl(engine.getConstantsRegistry()); @NotNull
private final AndroidMathRegistry<jscl.math.function.Function> functionsRegistry = new AndroidFunctionsMathRegistry(engine.getFunctionsRegistry());
@NotNull
private final AndroidMathRegistry<jscl.math.function.Function> functionsRegistry = new AndroidFunctionsMathRegistry(engine.getFunctionsRegistry()); @NotNull
private final AndroidMathRegistry<Operator> operatorsRegistry = new AndroidOperatorsMathRegistry(engine.getOperatorsRegistry());
@NotNull
private final AndroidMathRegistry<Operator> operatorsRegistry = new AndroidOperatorsMathRegistry(engine.getOperatorsRegistry()); private final AndroidMathRegistry<Operator> postfixFunctionsRegistry = new AndroidPostfixFunctionsRegistry(engine.getPostfixFunctionsRegistry());
private final AndroidMathRegistry<Operator> postfixFunctionsRegistry = new AndroidPostfixFunctionsRegistry(engine.getPostfixFunctionsRegistry()); @Nullable
private ThreadKiller threadKiller = new AndroidThreadKiller();
@Nullable
private ThreadKiller threadKiller = new AndroidThreadKiller(); // calculation thread timeout in seconds, after timeout thread would be interrupted
private int timeout = Integer.valueOf(MAX_CALCULATION_TIME_DEFAULT);
// calculation thread timeout in seconds, after timeout thread would be interrupted
private int timeout = Integer.valueOf(MAX_CALCULATION_TIME_DEFAULT); @NotNull
private String multiplicationSign = MULTIPLICATION_SIGN_DEFAULT;
@NotNull
private String multiplicationSign = MULTIPLICATION_SIGN_DEFAULT; CalculatorEngine() {
this.engine.setRoundResult(true);
CalculatorEngine() { this.engine.setUseGroupingSeparator(true);
this.engine.setRoundResult(true); }
this.engine.setUseGroupingSeparator(true);
} @NotNull
public String getMultiplicationSign() {
@Override return multiplicationSign;
@NotNull }
public String getMultiplicationSign() {
return multiplicationSign; public void setMultiplicationSign(@NotNull String multiplicationSign) {
} this.multiplicationSign = multiplicationSign;
}
public void setMultiplicationSign(@NotNull String multiplicationSign) {
this.multiplicationSign = multiplicationSign; public static class Result {
}
@NotNull
public CalculatorOutput evaluate(@NotNull JsclOperation operation, private Generic genericResult;
@NotNull String expression) throws CalculatorParseException, CalculatorEvalException {
return evaluate(operation, expression, null); @NotNull
} private String result;
public CalculatorOutput evaluate(@NotNull final JsclOperation operation, @NotNull
@NotNull String expression, private JsclOperation userOperation;
@Nullable MessageRegistry mr) throws CalculatorParseException, CalculatorEvalException {
synchronized (lock) { public Result(@NotNull String result, @NotNull JsclOperation userOperation, @NotNull Generic genericResult) {
final StringBuilder sb = new StringBuilder(); this.result = result;
this.userOperation = userOperation;
final PreparedExpression preparedExpression = preprocessor.process(expression); this.genericResult = genericResult;
sb.append(preparedExpression); }
//Log.d(CalculatorEngine.class.getName(), "Preprocessed expression: " + preparedExpression); @NotNull
/*if (operation == JsclOperation.numeric && preparedExpression.isExistsUndefinedVar()) { public String getResult() {
operation = JsclOperation.simplify; return result;
}
if (mr != null) {
final String undefinedVars = CollectionsUtils.formatValue(preparedExpression.getUndefinedVars(), ", ", new Formatter<Var>() { @NotNull
@Override public JsclOperation getUserOperation() {
public String formatValue(@Nullable Var var) throws IllegalArgumentException { return userOperation;
return var != null ? var.getName() : ""; }
}
}); @NotNull
public Generic getGenericResult() {
mr.addMessage(new AndroidMessage(R.string.c_simplify_instead_of_numeric, MessageType.info, undefinedVars)); return genericResult;
} }
}*/ }
final String jsclExpression = sb.toString(); public Result evaluate(@NotNull JsclOperation operation,
@NotNull String expression) throws CalculatorParseException, CalculatorEvalException {
final MutableObject<Generic> calculationResult = new MutableObject<Generic>(null); return evaluate(operation, expression, null);
final MutableObject<CalculatorParseException> parseException = new MutableObject<CalculatorParseException>(null); }
final MutableObject<CalculatorEvalException> evalException = new MutableObject<CalculatorEvalException>(null);
final MutableObject<Thread> calculationThread = new MutableObject<Thread>(null); public Result evaluate(@NotNull final JsclOperation operation,
@NotNull String expression,
final CountDownLatch latch = new CountDownLatch(1); @Nullable MessageRegistry mr) throws CalculatorParseException, CalculatorEvalException {
synchronized (lock) {
new Thread(new Runnable() { final StringBuilder sb = new StringBuilder();
@Override
public void run() { final PreparedExpression preparedExpression = preprocessor.process(expression);
final Thread thread = Thread.currentThread(); sb.append(preparedExpression);
try {
//Log.d(CalculatorEngine.class.getName(), "Calculation thread started work: " + thread.getName()); //Log.d(CalculatorEngine.class.getName(), "Preprocessed expression: " + preparedExpression);
//System.out.println(jsclExpression); /*if (operation == JsclOperation.numeric && preparedExpression.isExistsUndefinedVar()) {
calculationThread.setObject(thread); operation = JsclOperation.simplify;
final Generic genericResult = operation.evaluateGeneric(jsclExpression);
if (mr != null) {
// NOTE: toString() method must be called here as ArithmeticOperationException may occur in it (just to avoid later check!) final String undefinedVars = CollectionsUtils.formatValue(preparedExpression.getUndefinedVars(), ", ", new Formatter<Var>() {
genericResult.toString(); @Override
public String formatValue(@Nullable Var var) throws IllegalArgumentException {
calculationResult.setObject(genericResult); return var != null ? var.getName() : "";
} catch (AbstractJsclArithmeticException e) { }
evalException.setObject(new CalculatorEvalException(e, e, jsclExpression)); });
} catch (ArithmeticException e) {
//System.out.println(e.getMessage()); mr.addMessage(new AndroidMessage(R.string.c_simplify_instead_of_numeric, MessageType.info, undefinedVars));
final AndroidMessage androidMessage = new AndroidMessage(R.string.msg_1, MessageType.error, CalculatorApplication.getInstance(), e.getMessage()); }
parseException.setObject(new CalculatorParseException(jsclExpression, androidMessage)); }*/
} catch (StackOverflowError e) {
//System.out.println(StringUtils.fromStackTrace(e.getStackTrace())); final String jsclExpression = sb.toString();
final AndroidMessage androidMessage = new AndroidMessage(R.string.msg_2, MessageType.error, CalculatorApplication.getInstance());
parseException.setObject(new CalculatorParseException(jsclExpression, androidMessage)); final MutableObject<Generic> calculationResult = new MutableObject<Generic>(null);
} catch (jscl.text.ParseException e) { final MutableObject<CalculatorParseException> parseException = new MutableObject<CalculatorParseException>(null);
//System.out.println(e.getMessage()); final MutableObject<CalculatorEvalException> evalException = new MutableObject<CalculatorEvalException>(null);
parseException.setObject(new CalculatorParseException(e)); final MutableObject<Thread> calculationThread = new MutableObject<Thread>(null);
} catch (ParseInterruptedException e) {
//System.out.println(e.getMessage()); final CountDownLatch latch = new CountDownLatch(1);
// do nothing - we ourselves interrupt the calculations
} finally { new Thread(new Runnable() {
//Log.d(CalculatorEngine.class.getName(), "Calculation thread ended work: " + thread.getName()); @Override
calculationThread.setObject(null); public void run() {
latch.countDown(); final Thread thread = Thread.currentThread();
} try {
} //Log.d(CalculatorEngine.class.getName(), "Calculation thread started work: " + thread.getName());
}).start(); //System.out.println(jsclExpression);
calculationThread.setObject(thread);
try { final Generic genericResult = operation.evaluateGeneric(jsclExpression);
//Log.d(CalculatorEngine.class.getName(), "Main thread is waiting: " + Thread.currentThread().getName());
latch.await(timeout, TimeUnit.SECONDS); // NOTE: toString() method must be called here as ArithmeticOperationException may occur in it (just to avoid later check!)
//Log.d(CalculatorEngine.class.getName(), "Main thread got up: " + Thread.currentThread().getName()); genericResult.toString();
final CalculatorParseException parseExceptionObject = parseException.getObject(); calculationResult.setObject(genericResult);
final CalculatorEvalException evalExceptionObject = evalException.getObject(); } catch (AbstractJsclArithmeticException e) {
final Object calculationResultLocal = calculationResult.getObject(); evalException.setObject(new CalculatorEvalException(e, e, jsclExpression));
final Thread calculationThreadLocal = calculationThread.getObject(); } catch (ArithmeticException e) {
//System.out.println(e.getMessage());
if (calculationThreadLocal != null) { parseException.setObject(new CalculatorParseException(R.string.msg_1, CalculatorApplication.getInstance(), jsclExpression, e.getMessage()));
if (threadKiller != null) { } catch (StackOverflowError e) {
threadKiller.killThread(calculationThreadLocal); //System.out.println(StringUtils.fromStackTrace(e.getStackTrace()));
} parseException.setObject(new CalculatorParseException(R.string.msg_2, CalculatorApplication.getInstance(), jsclExpression));
//calculationThreadLocal.stop(); } catch (jscl.text.ParseException e) {
} //System.out.println(e.getMessage());
parseException.setObject(new CalculatorParseException(e));
if (parseExceptionObject != null || evalExceptionObject != null) { } catch (ParseInterruptedException e) {
if (operation == JsclOperation.numeric && //System.out.println(e.getMessage());
(preparedExpression.isExistsUndefinedVar() || (evalExceptionObject != null && evalExceptionObject.getCause() instanceof NumeralBaseException))) { // do nothing - we ourselves interrupt the calculations
return evaluate(JsclOperation.simplify, expression, mr); } finally {
} //Log.d(CalculatorEngine.class.getName(), "Calculation thread ended work: " + thread.getName());
calculationThread.setObject(null);
if (parseExceptionObject != null) { latch.countDown();
throw parseExceptionObject; }
} else { }
throw evalExceptionObject; }).start();
}
} try {
//Log.d(CalculatorEngine.class.getName(), "Main thread is waiting: " + Thread.currentThread().getName());
if (calculationResultLocal == null) { latch.await(timeout, TimeUnit.SECONDS);
final AndroidMessage androidMessage = new AndroidMessage(R.string.msg_3, MessageType.error, CalculatorApplication.getInstance()); //Log.d(CalculatorEngine.class.getName(), "Main thread got up: " + Thread.currentThread().getName());
throw new CalculatorParseException(jsclExpression, androidMessage);
} final CalculatorParseException parseExceptionObject = parseException.getObject();
final CalculatorEvalException evalExceptionObject = evalException.getObject();
} catch (InterruptedException e) { final Object calculationResultLocal = calculationResult.getObject();
final AndroidMessage androidMessage = new AndroidMessage(R.string.msg_4, MessageType.error, CalculatorApplication.getInstance()); final Thread calculationThreadLocal = calculationThread.getObject();
throw new CalculatorParseException(jsclExpression, androidMessage);
} if (calculationThreadLocal != null) {
if (threadKiller != null) {
final Generic genericResult = calculationResult.getObject(); threadKiller.killThread(calculationThreadLocal);
}
return new CalculatorOutputImpl(operation.getFromProcessor().process(genericResult), operation, genericResult); //calculationThreadLocal.stop();
} }
}
if (parseExceptionObject != null || evalExceptionObject != null) {
public void setPrecision(int precision) { if (operation == JsclOperation.numeric &&
this.getEngine().setPrecision(precision); (preparedExpression.isExistsUndefinedVar() || (evalExceptionObject != null && evalExceptionObject.getCause() instanceof NumeralBaseException))) {
} return evaluate(JsclOperation.simplify, expression, mr);
}
public void setRoundResult(boolean roundResult) {
this.getEngine().setRoundResult(roundResult); if (parseExceptionObject != null) {
} throw parseExceptionObject;
} else {
public void init(@Nullable Context context, @Nullable SharedPreferences preferences) { throw evalExceptionObject;
synchronized (lock) { }
reset(context, preferences); }
}
} if (calculationResultLocal == null) {
throw new CalculatorParseException(R.string.msg_3, CalculatorApplication.getInstance(), jsclExpression);
public void reset(@Nullable Context context, @Nullable SharedPreferences preferences) { }
synchronized (lock) {
softReset(context, preferences); } catch (InterruptedException e) {
throw new CalculatorParseException(R.string.msg_4, CalculatorApplication.getInstance(), jsclExpression);
varsRegistry.load(context, preferences); }
functionsRegistry.load(context, preferences);
operatorsRegistry.load(context, preferences); final Generic genericResult = calculationResult.getObject();
postfixFunctionsRegistry.load(context, preferences);
} return new Result(operation.getFromProcessor().process(genericResult), operation, genericResult);
} }
}
public void softReset(@Nullable Context context, @Nullable SharedPreferences preferences) {
synchronized (lock) { public void setPrecision(int precision) {
if (preferences != null) { this.getEngine().setPrecision(precision);
this.setPrecision(Preferences.precision.getPreference(preferences)); }
this.setRoundResult(Preferences.roundResult.getPreference(preferences));
this.setAngleUnits(getAngleUnitsFromPrefs(preferences)); public void setRoundResult(boolean roundResult) {
this.setNumeralBase(getNumeralBaseFromPrefs(preferences)); this.getEngine().setRoundResult(roundResult);
this.setMultiplicationSign(Preferences.multiplicationSign.getPreference(preferences)); }
this.setScienceNotation(Preferences.scienceNotation.getPreference(preferences));
this.setTimeout(Preferences.maxCalculationTime.getPreference(preferences)); public void init(@Nullable Context context, @Nullable SharedPreferences preferences) {
synchronized (lock) {
final String groupingSeparator = Preferences.groupingSeparator.getPreference(preferences); reset(context, preferences);
if (StringUtils.isEmpty(groupingSeparator)) { }
this.getEngine().setUseGroupingSeparator(false); }
} else {
this.getEngine().setUseGroupingSeparator(true); public void reset(@Nullable Context context, @Nullable SharedPreferences preferences) {
this.getEngine().setGroupingSeparator(groupingSeparator.charAt(0)); synchronized (lock) {
} softReset(context, preferences);
}
} varsRegistry.load(context, preferences);
} functionsRegistry.load(context, preferences);
operatorsRegistry.load(context, preferences);
postfixFunctionsRegistry.load(context, preferences);
@NotNull }
public NumeralBase getNumeralBaseFromPrefs(@NotNull SharedPreferences preferences) { }
return Preferences.numeralBase.getPreference(preferences);
} public void softReset(@Nullable Context context, @Nullable SharedPreferences preferences) {
synchronized (lock) {
@NotNull if (preferences != null) {
public AngleUnit getAngleUnitsFromPrefs(@NotNull SharedPreferences preferences) { this.setPrecision(Preferences.precision.getPreference(preferences));
return Preferences.angleUnit.getPreference(preferences); this.setRoundResult(Preferences.roundResult.getPreference(preferences));
} this.setAngleUnits(getAngleUnitsFromPrefs(preferences));
this.setNumeralBase(getNumeralBaseFromPrefs(preferences));
//for tests only this.setMultiplicationSign(Preferences.multiplicationSign.getPreference(preferences));
void setDecimalGroupSymbols(@NotNull DecimalFormatSymbols decimalGroupSymbols) { this.setScienceNotation(Preferences.scienceNotation.getPreference(preferences));
synchronized (lock) { this.setTimeout(Preferences.maxCalculationTime.getPreference(preferences));
this.getEngine().setDecimalGroupSymbols(decimalGroupSymbols);
} final String groupingSeparator = Preferences.groupingSeparator.getPreference(preferences);
} if (StringUtils.isEmpty(groupingSeparator)) {
this.getEngine().setUseGroupingSeparator(false);
@Override } else {
@NotNull this.getEngine().setUseGroupingSeparator(true);
public AndroidMathRegistry<IConstant> getVarsRegistry() { this.getEngine().setGroupingSeparator(groupingSeparator.charAt(0));
return varsRegistry; }
} }
}
@Override }
@NotNull
public AndroidMathRegistry<Function> getFunctionsRegistry() {
return functionsRegistry; @NotNull
} public NumeralBase getNumeralBaseFromPrefs(@NotNull SharedPreferences preferences) {
return Preferences.numeralBase.getPreference(preferences);
@Override }
@NotNull
public AndroidMathRegistry<Operator> getOperatorsRegistry() { @NotNull
return operatorsRegistry; public AngleUnit getAngleUnitsFromPrefs(@NotNull SharedPreferences preferences) {
} return Preferences.angleUnit.getPreference(preferences);
}
@Override
@NotNull //for tests only
public AndroidMathRegistry<Operator> getPostfixFunctionsRegistry() { void setDecimalGroupSymbols(@NotNull DecimalFormatSymbols decimalGroupSymbols) {
return postfixFunctionsRegistry; synchronized (lock) {
} this.getEngine().setDecimalGroupSymbols(decimalGroupSymbols);
}
@Override }
@NotNull
public MathEngine getEngine() { @NotNull
return engine; public AndroidMathRegistry<IConstant> getVarsRegistry() {
} return varsRegistry;
}
// package protected for tests
void setTimeout(int timeout) { @NotNull
this.timeout = timeout; public AndroidMathRegistry<Function> getFunctionsRegistry() {
} return functionsRegistry;
}
public void setAngleUnits(@NotNull AngleUnit angleUnits) {
getEngine().setAngleUnits(angleUnits); @NotNull
} public AndroidMathRegistry<Operator> getOperatorsRegistry() {
return operatorsRegistry;
public void setScienceNotation(boolean scienceNotation) { }
getEngine().setScienceNotation(scienceNotation);
} @NotNull
public AndroidMathRegistry<Operator> getPostfixFunctionsRegistry() {
public void setNumeralBase(@NotNull NumeralBase numeralBase) { return postfixFunctionsRegistry;
getEngine().setNumeralBase(numeralBase); }
}
@NotNull
// for tests only public MathEngine getEngine() {
void setThreadKiller(@Nullable ThreadKiller threadKiller) { return engine;
this.threadKiller = threadKiller; }
}
// package protected for tests
private static interface ThreadKiller { void setTimeout(int timeout) {
void killThread(@NotNull Thread thread); this.timeout = timeout;
} }
private static class AndroidThreadKiller implements ThreadKiller { public void setAngleUnits(@NotNull AngleUnit angleUnits) {
@Override getEngine().setAngleUnits(angleUnits);
public void killThread(@NotNull Thread thread) { }
thread.setPriority(Thread.MIN_PRIORITY);
thread.interrupt(); public void setScienceNotation(boolean scienceNotation) {
} getEngine().setScienceNotation(scienceNotation);
} }
public static class ThreadKillerImpl implements ThreadKiller { public void setNumeralBase(@NotNull NumeralBase numeralBase) {
@Override getEngine().setNumeralBase(numeralBase);
public void killThread(@NotNull Thread thread) { }
thread.setPriority(Thread.MIN_PRIORITY);
thread.stop(); // for tests only
} void setThreadKiller(@Nullable ThreadKiller threadKiller) {
} this.threadKiller = threadKiller;
} }
private static interface ThreadKiller {
void killThread(@NotNull Thread thread);
}
private static class AndroidThreadKiller implements ThreadKiller {
@Override
public void killThread(@NotNull Thread thread) {
thread.setPriority(Thread.MIN_PRIORITY);
thread.interrupt();
}
}
public static class ThreadKillerImpl implements ThreadKiller {
@Override
public void killThread(@NotNull Thread thread) {
thread.setPriority(Thread.MIN_PRIORITY);
thread.stop();
}
}
}

View File

@ -4,8 +4,9 @@
* or visit http://se.solovyev.org * or visit http://se.solovyev.org
*/ */
package org.solovyev.android.calculator; package org.solovyev.android.calculator.model;
import jscl.AbstractJsclArithmeticException;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.solovyev.common.exceptions.SersoException; import org.solovyev.common.exceptions.SersoException;
import org.solovyev.common.msg.Message; import org.solovyev.common.msg.Message;

View File

@ -4,10 +4,12 @@
* or visit http://se.solovyev.org * or visit http://se.solovyev.org
*/ */
package org.solovyev.android.calculator; package org.solovyev.android.calculator.model;
import android.app.Application;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.solovyev.android.msg.AndroidMessage;
import org.solovyev.common.exceptions.SersoException; import org.solovyev.common.exceptions.SersoException;
import org.solovyev.common.msg.Message; import org.solovyev.common.msg.Message;
import org.solovyev.common.msg.MessageType; import org.solovyev.common.msg.MessageType;
@ -37,17 +39,14 @@ public class CalculatorParseException extends SersoException implements Message
this.position = jsclParseException.getPosition(); this.position = jsclParseException.getPosition();
} }
public CalculatorParseException(@Nullable Integer position, public CalculatorParseException(@NotNull Integer messageId, @NotNull Application application, @Nullable Integer position, @NotNull String expression, Object... parameters) {
@NotNull String expression, this.message = new AndroidMessage(messageId, MessageType.error, application, parameters);
@NotNull Message message) {
this.message = message;
this.expression = expression; this.expression = expression;
this.position = position; this.position = position;
} }
public CalculatorParseException(@NotNull String expression, public CalculatorParseException(@NotNull Integer messageId, @NotNull Application application, @NotNull String expression, Object... parameters) {
@NotNull Message message) { this(messageId, application, null, expression, parameters);
this(null, expression, message);
} }
@NotNull @NotNull

View File

@ -4,11 +4,10 @@
* or visit http://se.solovyev.org * or visit http://se.solovyev.org
*/ */
package org.solovyev.android.calculator.text; package org.solovyev.android.calculator.model;
import jscl.math.Generic; import jscl.math.Generic;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.CalculatorParseException;
/** /**
* User: serso * User: serso

View File

@ -1,11 +1,9 @@
package org.solovyev.android.calculator.text; package org.solovyev.android.calculator.model;
import jscl.math.Generic; import jscl.math.Generic;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.CalculatorLocatorImpl;
import org.solovyev.android.calculator.math.MathType; import org.solovyev.android.calculator.math.MathType;
import org.solovyev.android.calculator.CalculatorParseException;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
@ -57,7 +55,7 @@ public class FromJsclSimplifyTextProcessor implements TextProcessor<String, Gene
} }
if (needMultiplicationSign(mathTypeBefore == null ? null : mathTypeBefore.getMathType(), mathTypeAfter == null ? null : mathTypeAfter.getMathType())) { if (needMultiplicationSign(mathTypeBefore == null ? null : mathTypeBefore.getMathType(), mathTypeAfter == null ? null : mathTypeAfter.getMathType())) {
sb.append(CalculatorLocatorImpl.getInstance().getCalculatorEngine().getMultiplicationSign()); sb.append(CalculatorEngine.instance.getMultiplicationSign());
} }
} else { } else {

View File

@ -4,7 +4,7 @@
* or visit http://se.solovyev.org * or visit http://se.solovyev.org
*/ */
package org.solovyev.android.calculator; package org.solovyev.android.calculator.model;
import jscl.MathEngine; import jscl.MathEngine;
import jscl.NumeralBase; import jscl.NumeralBase;

View File

@ -4,7 +4,7 @@
* or visit http://se.solovyev.org * or visit http://se.solovyev.org
*/ */
package org.solovyev.android.calculator; package org.solovyev.android.calculator.model;
import jscl.MathContext; import jscl.MathContext;
import jscl.MathEngine; import jscl.MathEngine;
@ -13,7 +13,6 @@ import jscl.math.numeric.Real;
import jscl.text.*; import jscl.text.*;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.AbstractNumberBuilder;
import org.solovyev.android.calculator.math.MathType; import org.solovyev.android.calculator.math.MathType;
import org.solovyev.common.MutableObject; import org.solovyev.common.MutableObject;
@ -83,7 +82,7 @@ public class NumberBuilder extends AbstractNumberBuilder {
String number = null; String number = null;
// toXml numeral base (as later it might be replaced) // save numeral base (as later it might be replaced)
final NumeralBase localNb = getNumeralBase(); final NumeralBase localNb = getNumeralBase();
if (numberBuilder != null) { if (numberBuilder != null) {

View File

@ -4,7 +4,7 @@
* or visit http://se.solovyev.org * or visit http://se.solovyev.org
*/ */
package org.solovyev.android.calculator; package org.solovyev.android.calculator.model;
import jscl.math.function.IConstant; import jscl.math.function.IConstant;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;

View File

@ -1,7 +1,6 @@
package org.solovyev.android.calculator.text; package org.solovyev.android.calculator.model;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.CalculatorParseException;
/** /**
* User: serso * User: serso

View File

@ -4,20 +4,15 @@
* or visit http://se.solovyev.org * or visit http://se.solovyev.org
*/ */
package org.solovyev.android.calculator; package org.solovyev.android.calculator.model;
import jscl.math.function.IConstant; import jscl.math.function.IConstant;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.CalculatorApplication; import org.solovyev.android.calculator.CalculatorApplication;
import org.solovyev.android.calculator.CalculatorParseException;
import org.solovyev.android.calculator.PreparedExpression;
import org.solovyev.android.calculator.R; import org.solovyev.android.calculator.R;
import org.solovyev.android.calculator.text.TextProcessor;
import org.solovyev.android.msg.AndroidMessage;
import org.solovyev.common.StartsWithFinder; import org.solovyev.common.StartsWithFinder;
import org.solovyev.android.calculator.math.MathType; import org.solovyev.android.calculator.math.MathType;
import org.solovyev.common.collections.CollectionsUtils; import org.solovyev.common.collections.CollectionsUtils;
import org.solovyev.common.msg.MessageType;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -80,8 +75,7 @@ public class ToJsclTextProcessor implements TextProcessor<PreparedExpression, St
if (mathTypeBefore != null && if (mathTypeBefore != null &&
(mathTypeBefore.getMathType() == MathType.function || mathTypeBefore.getMathType() == MathType.operator) && (mathTypeBefore.getMathType() == MathType.function || mathTypeBefore.getMathType() == MathType.operator) &&
CollectionsUtils.find(MathType.openGroupSymbols, startsWithFinder) != null) { CollectionsUtils.find(MathType.openGroupSymbols, startsWithFinder) != null) {
final AndroidMessage androidMessage = new AndroidMessage(R.string.msg_5, MessageType.error, CalculatorApplication.getInstance(), mathTypeBefore.getMatch()); throw new CalculatorParseException(R.string.msg_5, CalculatorApplication.getInstance(), i, s, mathTypeBefore.getMatch());
throw new CalculatorParseException(i, s, androidMessage);
} }
i = mathTypeResult.processToJscl(result, i); i = mathTypeResult.processToJscl(result, i);
@ -92,8 +86,7 @@ public class ToJsclTextProcessor implements TextProcessor<PreparedExpression, St
@NotNull @NotNull
private static PreparedExpression replaceVariables(@NotNull final String s, int depth, @NotNull List<IConstant> undefinedVars) throws CalculatorParseException { private static PreparedExpression replaceVariables(@NotNull final String s, int depth, @NotNull List<IConstant> undefinedVars) throws CalculatorParseException {
if (depth >= MAX_DEPTH) { if (depth >= MAX_DEPTH) {
final AndroidMessage androidMessage = new AndroidMessage(R.string.msg_6, MessageType.error, CalculatorApplication.getInstance()); throw new CalculatorParseException(R.string.msg_6, CalculatorApplication.getInstance(), s);
throw new CalculatorParseException(s, androidMessage);
} else { } else {
depth++; depth++;
} }

View File

@ -35,9 +35,9 @@ import org.achartengine.tools.ZoomListener;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.R; import org.solovyev.android.calculator.R;
import org.solovyev.android.calculator.CalculatorParseException; import org.solovyev.android.calculator.model.CalculatorParseException;
import org.solovyev.android.calculator.PreparedExpression; import org.solovyev.android.calculator.model.PreparedExpression;
import org.solovyev.android.calculator.ToJsclTextProcessor; import org.solovyev.android.calculator.model.ToJsclTextProcessor;
import org.solovyev.common.MutableObject; import org.solovyev.common.MutableObject;
import java.io.Serializable; import java.io.Serializable;

View File

@ -6,14 +6,14 @@ import android.view.View;
import android.view.WindowManager; import android.view.WindowManager;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.solovyev.math.units.Unit; import org.solovyev.android.Unit;
import org.solovyev.math.units.UnitImpl; import org.solovyev.android.UnitImpl;
import org.solovyev.android.calculator.AndroidNumeralBase; import org.solovyev.android.calculator.AndroidNumeralBase;
import org.solovyev.android.calculator.CalculatorModel; import org.solovyev.android.calculator.CalculatorModel;
import org.solovyev.android.calculator.R; import org.solovyev.android.calculator.R;
import org.solovyev.android.calculator.model.CalculatorEngine; import org.solovyev.android.calculator.model.CalculatorEngine;
import org.solovyev.android.calculator.CalculatorParseException; import org.solovyev.android.calculator.model.CalculatorParseException;
import org.solovyev.android.calculator.ToJsclTextProcessor; import org.solovyev.android.calculator.model.ToJsclTextProcessor;
import org.solovyev.common.MutableObject; import org.solovyev.common.MutableObject;
import org.solovyev.common.text.StringUtils; import org.solovyev.common.text.StringUtils;

View File

@ -9,13 +9,8 @@ package org.solovyev.android.calculator.view;
import jscl.MathContext; import jscl.MathContext;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.AbstractNumberBuilder;
import org.solovyev.android.calculator.CalculatorParseException;
import org.solovyev.android.calculator.LiteNumberBuilder;
import org.solovyev.android.calculator.NumberBuilder;
import org.solovyev.android.calculator.math.MathType; import org.solovyev.android.calculator.math.MathType;
import org.solovyev.android.calculator.model.*; import org.solovyev.android.calculator.model.*;
import org.solovyev.android.calculator.text.TextProcessor;
import org.solovyev.common.MutableObject; import org.solovyev.common.MutableObject;
import java.util.HashMap; import java.util.HashMap;

View File

@ -10,10 +10,10 @@ import android.view.ViewGroup;
import android.widget.*; import android.widget.*;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.solovyev.math.units.Unit; import org.solovyev.android.Unit;
import org.solovyev.math.units.UnitConverter; import org.solovyev.android.UnitConverter;
import org.solovyev.math.units.UnitImpl; import org.solovyev.android.UnitImpl;
import org.solovyev.math.units.UnitType; import org.solovyev.android.UnitType;
import org.solovyev.android.calculator.R; import org.solovyev.android.calculator.R;
import org.solovyev.android.view.ViewBuilder; import org.solovyev.android.view.ViewBuilder;
import org.solovyev.android.view.ViewFromLayoutBuilder; import org.solovyev.android.view.ViewFromLayoutBuilder;

View File

@ -4,8 +4,6 @@ import junit.framework.Assert;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.junit.Test; import org.junit.Test;
import org.solovyev.android.calculator.AndroidNumeralBase; import org.solovyev.android.calculator.AndroidNumeralBase;
import org.solovyev.math.units.Unit;
import org.solovyev.math.units.UnitConverter;
import java.util.Date; import java.util.Date;
import java.util.Random; import java.util.Random;

View File

@ -12,7 +12,7 @@ import jscl.NumeralBase;
import junit.framework.Assert; import junit.framework.Assert;
import org.junit.Test; import org.junit.Test;
import org.solovyev.android.calculator.model.CalculatorEngine; import org.solovyev.android.calculator.model.CalculatorEngine;
import org.solovyev.android.calculator.text.TextProcessor; import org.solovyev.android.calculator.model.TextProcessor;
import org.solovyev.android.calculator.view.TextHighlighter; import org.solovyev.android.calculator.view.TextHighlighter;
import java.util.Date; import java.util.Date;

View File

@ -1,321 +1,320 @@
/* /*
* Copyright (c) 2009-2011. Created by serso aka se.solovyev. * Copyright (c) 2009-2011. Created by serso aka se.solovyev.
* For more information, please, contact se.solovyev@gmail.com * For more information, please, contact se.solovyev@gmail.com
* or visit http://se.solovyev.org * or visit http://se.solovyev.org
*/ */
package org.solovyev.android.calculator.history; package org.solovyev.android.calculator.history;
import jscl.math.Generic; import jscl.math.Generic;
import junit.framework.Assert; import junit.framework.Assert;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.junit.Test; import org.junit.Test;
import org.solovyev.android.calculator.CalculatorDisplay; import org.solovyev.android.calculator.ICalculatorDisplay;
import org.solovyev.android.calculator.Editor; import org.solovyev.android.calculator.jscl.JsclOperation;
import org.solovyev.android.calculator.jscl.JsclOperation; import org.solovyev.common.equals.CollectionEqualizer;
import org.solovyev.common.equals.CollectionEqualizer; import org.solovyev.common.equals.EqualsTool;
import org.solovyev.common.equals.EqualsTool; import org.solovyev.common.history.HistoryHelper;
import org.solovyev.common.history.HistoryHelper; import org.solovyev.common.history.SimpleHistoryHelper;
import org.solovyev.common.history.SimpleHistoryHelper;
import java.util.ArrayList;
import java.util.ArrayList; import java.util.Date;
import java.util.Date; import java.util.List;
import java.util.List;
/**
/** * User: serso
* User: serso * Date: 12/17/11
* Date: 12/17/11 * Time: 10:01 PM
* Time: 10:01 PM */
*/ public class HistoryUtilsTest {
public class HistoryUtilsTest {
@Test
@Test public void testFromXml() throws Exception {
public void testFromXml() throws Exception {
}
}
private static final String emptyHistory = "<history>\n" +
private static final String emptyHistory = "<history>\n" + " <historyItems class=\"java.util.ArrayList\"/>\n" +
" <historyItems class=\"java.util.ArrayList\"/>\n" + "</history>";
"</history>";
private static final String toXml1 = "<history>\n" +
private static final String toXml1 = "<history>\n" + " <historyItems class=\"java.util.ArrayList\">\n" +
" <historyItems class=\"java.util.ArrayList\">\n" + " <calculatorHistoryState>\n" +
" <calculatorHistoryState>\n" + " <time>100000000</time>\n" +
" <time>100000000</time>\n" + " <editorState>\n" +
" <editorState>\n" + " <cursorPosition>3</cursorPosition>\n" +
" <cursorPosition>3</cursorPosition>\n" + " <text>1+1</text>\n" +
" <text>1+1</text>\n" + " </editorState>\n" +
" </editorState>\n" + " <displayState>\n" +
" <displayState>\n" + " <editorState>\n" +
" <editorState>\n" + " <cursorPosition>1</cursorPosition>\n" +
" <cursorPosition>1</cursorPosition>\n" + " <text>Error</text>\n" +
" <text>Error</text>\n" + " </editorState>\n" +
" </editorState>\n" + " <jsclOperation>simplify</jsclOperation>\n" +
" <jsclOperation>simplify</jsclOperation>\n" + " </displayState>\n" +
" </displayState>\n" + " </calculatorHistoryState>\n" +
" </calculatorHistoryState>\n" + " </historyItems>\n" +
" </historyItems>\n" + "</history>";
"</history>";
private static final String toXml2 = "<history>\n" +
private static final String toXml2 = "<history>\n" + " <historyItems class=\"java.util.ArrayList\">\n" +
" <historyItems class=\"java.util.ArrayList\">\n" + " <calculatorHistoryState>\n" +
" <calculatorHistoryState>\n" + " <time>100000000</time>\n" +
" <time>100000000</time>\n" + " <editorState>\n" +
" <editorState>\n" + " <cursorPosition>3</cursorPosition>\n" +
" <cursorPosition>3</cursorPosition>\n" + " <text>1+1</text>\n" +
" <text>1+1</text>\n" + " </editorState>\n" +
" </editorState>\n" + " <displayState>\n" +
" <displayState>\n" + " <editorState>\n" +
" <editorState>\n" + " <cursorPosition>1</cursorPosition>\n" +
" <cursorPosition>1</cursorPosition>\n" + " <text>Error</text>\n" +
" <text>Error</text>\n" + " </editorState>\n" +
" </editorState>\n" + " <jsclOperation>simplify</jsclOperation>\n" +
" <jsclOperation>simplify</jsclOperation>\n" + " </displayState>\n" +
" </displayState>\n" + " </calculatorHistoryState>\n" +
" </calculatorHistoryState>\n" + " <calculatorHistoryState>\n" +
" <calculatorHistoryState>\n" + " <time>100000000</time>\n" +
" <time>100000000</time>\n" + " <editorState>\n" +
" <editorState>\n" + " <cursorPosition>2</cursorPosition>\n" +
" <cursorPosition>2</cursorPosition>\n" + " <text>5/6</text>\n" +
" <text>5/6</text>\n" + " </editorState>\n" +
" </editorState>\n" + " <displayState>\n" +
" <displayState>\n" + " <editorState>\n" +
" <editorState>\n" + " <cursorPosition>3</cursorPosition>\n" +
" <cursorPosition>3</cursorPosition>\n" + " <text>5/6</text>\n" +
" <text>5/6</text>\n" + " </editorState>\n" +
" </editorState>\n" + " <jsclOperation>numeric</jsclOperation>\n" +
" <jsclOperation>numeric</jsclOperation>\n" + " </displayState>\n" +
" </displayState>\n" + " </calculatorHistoryState>\n" +
" </calculatorHistoryState>\n" + " <calculatorHistoryState>\n" +
" <calculatorHistoryState>\n" + " <time>100000000</time>\n" +
" <time>100000000</time>\n" + " <editorState>\n" +
" <editorState>\n" + " <cursorPosition>1</cursorPosition>\n" +
" <cursorPosition>1</cursorPosition>\n" + " <text>null</text>\n" +
" <text>null</text>\n" + " </editorState>\n" +
" </editorState>\n" + " <displayState>\n" +
" <displayState>\n" + " <editorState>\n" +
" <editorState>\n" + " <cursorPosition>1</cursorPosition>\n" +
" <cursorPosition>1</cursorPosition>\n" + " <text>Error</text>\n" +
" <text>Error</text>\n" + " </editorState>\n" +
" </editorState>\n" + " <jsclOperation>elementary</jsclOperation>\n" +
" <jsclOperation>elementary</jsclOperation>\n" + " </displayState>\n" +
" </displayState>\n" + " </calculatorHistoryState>\n" +
" </calculatorHistoryState>\n" + " <calculatorHistoryState>\n" +
" <calculatorHistoryState>\n" + " <time>100000000</time>\n" +
" <time>100000000</time>\n" + " <editorState>\n" +
" <editorState>\n" + " <cursorPosition>0</cursorPosition>\n" +
" <cursorPosition>0</cursorPosition>\n" + " <text>4+5/35sin(41)+dfdsfsdfs</text>\n" +
" <text>4+5/35sin(41)+dfdsfsdfs</text>\n" + " </editorState>\n" +
" </editorState>\n" + " <displayState>\n" +
" <displayState>\n" + " <editorState>\n" +
" <editorState>\n" + " <cursorPosition>1</cursorPosition>\n" +
" <cursorPosition>1</cursorPosition>\n" + " <text>4+5/35sin(41)+dfdsfsdfs</text>\n" +
" <text>4+5/35sin(41)+dfdsfsdfs</text>\n" + " </editorState>\n" +
" </editorState>\n" + " <jsclOperation>numeric</jsclOperation>\n" +
" <jsclOperation>numeric</jsclOperation>\n" + " </displayState>\n" +
" </displayState>\n" + " </calculatorHistoryState>\n" +
" </calculatorHistoryState>\n" + " </historyItems>\n" +
" </historyItems>\n" + "</history>";
"</history>";
@Test
@Test public void testToXml() throws Exception {
public void testToXml() throws Exception { final Date date = new Date(100000000);
final Date date = new Date(100000000);
HistoryHelper<CalculatorHistoryState> history = new SimpleHistoryHelper<CalculatorHistoryState>();
HistoryHelper<CalculatorHistoryState> history = new SimpleHistoryHelper<CalculatorHistoryState>();
ICalculatorDisplay calculatorDisplay = new TestCalculatorDisplay();
CalculatorDisplay calculatorDisplay = new TestCalculatorDisplay(); calculatorDisplay.setErrorMessage("error_msg1");
calculatorDisplay.setErrorMessage("error_msg1"); calculatorDisplay.setText("Error");
calculatorDisplay.setText("Error"); calculatorDisplay.setSelection(1);
calculatorDisplay.setSelection(1); calculatorDisplay.setJsclOperation(JsclOperation.simplify);
calculatorDisplay.setJsclOperation(JsclOperation.simplify);
Editor calculatorEditor = new TestEditor();
Editor calculatorEditor = new TestEditor(); calculatorEditor.setSelection(3);
calculatorEditor.setSelection(3); calculatorEditor.setText("1+1");
calculatorEditor.setText("1+1");
CalculatorHistoryState state = CalculatorHistoryState.newInstance(calculatorEditor, calculatorDisplay);
CalculatorHistoryState state = CalculatorHistoryState.newInstance(calculatorEditor, calculatorDisplay); state.setTime(date.getTime());
state.setTime(date.getTime()); history.addState(state);
history.addState(state);
Assert.assertEquals(emptyHistory, HistoryUtils.toXml(history.getStates()));
Assert.assertEquals(emptyHistory, HistoryUtils.toXml(history.getStates()));
state.setSaved(true);
state.setSaved(true);
Assert.assertEquals(toXml1, HistoryUtils.toXml(history.getStates()));
Assert.assertEquals(toXml1, HistoryUtils.toXml(history.getStates()));
calculatorDisplay = new TestCalculatorDisplay();
calculatorDisplay = new TestCalculatorDisplay(); calculatorDisplay.setErrorMessage(null);
calculatorDisplay.setErrorMessage(null); calculatorDisplay.setText("5/6");
calculatorDisplay.setText("5/6"); calculatorDisplay.setSelection(3);
calculatorDisplay.setSelection(3); calculatorDisplay.setJsclOperation(JsclOperation.numeric);
calculatorDisplay.setJsclOperation(JsclOperation.numeric);
calculatorEditor = new TestEditor();
calculatorEditor = new TestEditor(); calculatorEditor.setSelection(2);
calculatorEditor.setSelection(2); calculatorEditor.setText("5/6");
calculatorEditor.setText("5/6");
state = CalculatorHistoryState.newInstance(calculatorEditor, calculatorDisplay);
state = CalculatorHistoryState.newInstance(calculatorEditor, calculatorDisplay); state.setSaved(true);
state.setSaved(true); state.setTime(date.getTime());
state.setTime(date.getTime()); history.addState(state);
history.addState(state);
calculatorDisplay = new TestCalculatorDisplay();
calculatorDisplay = new TestCalculatorDisplay(); calculatorDisplay.setErrorMessage("error_msg2");
calculatorDisplay.setErrorMessage("error_msg2"); calculatorDisplay.setText("Error");
calculatorDisplay.setText("Error"); calculatorDisplay.setSelection(1);
calculatorDisplay.setSelection(1); calculatorDisplay.setJsclOperation(JsclOperation.elementary);
calculatorDisplay.setJsclOperation(JsclOperation.elementary);
calculatorEditor = new TestEditor();
calculatorEditor = new TestEditor(); calculatorEditor.setSelection(1);
calculatorEditor.setSelection(1); calculatorEditor.setText(null);
calculatorEditor.setText(null);
state = CalculatorHistoryState.newInstance(calculatorEditor, calculatorDisplay);
state = CalculatorHistoryState.newInstance(calculatorEditor, calculatorDisplay); state.setSaved(true);
state.setSaved(true); state.setTime(date.getTime());
state.setTime(date.getTime()); history.addState(state);
history.addState(state);
calculatorDisplay = new TestCalculatorDisplay();
calculatorDisplay = new TestCalculatorDisplay(); calculatorDisplay.setErrorMessage(null);
calculatorDisplay.setErrorMessage(null); calculatorDisplay.setText("4+5/35sin(41)+dfdsfsdfs");
calculatorDisplay.setText("4+5/35sin(41)+dfdsfsdfs"); calculatorDisplay.setSelection(1);
calculatorDisplay.setSelection(1); calculatorDisplay.setJsclOperation(JsclOperation.numeric);
calculatorDisplay.setJsclOperation(JsclOperation.numeric);
calculatorEditor = new TestEditor();
calculatorEditor = new TestEditor(); calculatorEditor.setSelection(0);
calculatorEditor.setSelection(0); calculatorEditor.setText("4+5/35sin(41)+dfdsfsdfs");
calculatorEditor.setText("4+5/35sin(41)+dfdsfsdfs");
state = CalculatorHistoryState.newInstance(calculatorEditor, calculatorDisplay);
state = CalculatorHistoryState.newInstance(calculatorEditor, calculatorDisplay); state.setSaved(true);
state.setSaved(true); state.setTime(date.getTime());
state.setTime(date.getTime()); history.addState(state);
history.addState(state);
String xml = HistoryUtils.toXml(history.getStates());
String xml = HistoryUtils.toXml(history.getStates()); Assert.assertEquals(toXml2, xml);
Assert.assertEquals(toXml2, xml);
final List<CalculatorHistoryState> fromXml = new ArrayList<CalculatorHistoryState>();
final List<CalculatorHistoryState> fromXml = new ArrayList<CalculatorHistoryState>(); final HistoryHelper<CalculatorHistoryState> historyFromXml = new SimpleHistoryHelper<CalculatorHistoryState>();
final HistoryHelper<CalculatorHistoryState> historyFromXml = new SimpleHistoryHelper<CalculatorHistoryState>(); HistoryUtils.fromXml(xml, fromXml);
HistoryUtils.fromXml(xml, fromXml); for (CalculatorHistoryState historyState : fromXml) {
for (CalculatorHistoryState historyState : fromXml) { historyFromXml.addState(historyState);
historyFromXml.addState(historyState); }
}
Assert.assertEquals(history.getStates().size(), historyFromXml.getStates().size());
Assert.assertEquals(history.getStates().size(), historyFromXml.getStates().size());
for (CalculatorHistoryState historyState : history.getStates()) {
for (CalculatorHistoryState historyState : history.getStates()) { historyState.setId(0);
historyState.setId(0); historyState.setSaved(true);
historyState.setSaved(true); }
} for (CalculatorHistoryState historyState : historyFromXml.getStates()) {
for (CalculatorHistoryState historyState : historyFromXml.getStates()) { historyState.setId(0);
historyState.setId(0); historyState.setSaved(true);
historyState.setSaved(true); }
} Assert.assertTrue(EqualsTool.areEqual(history.getStates(), historyFromXml.getStates(), new CollectionEqualizer<CalculatorHistoryState>(null)));
Assert.assertTrue(EqualsTool.areEqual(history.getStates(), historyFromXml.getStates(), new CollectionEqualizer<CalculatorHistoryState>(null))); }
}
private static class TestCalculatorDisplay implements ICalculatorDisplay {
private static class TestCalculatorDisplay implements CalculatorDisplay {
@NotNull
@NotNull private final TestEditor testEditor = new TestEditor();
private final TestEditor testEditor = new TestEditor();
private boolean valid;
private boolean valid;
private String errorMessage;
private String errorMessage;
private JsclOperation operation;
private JsclOperation operation;
private Generic genericResult;
private Generic genericResult;
@Override
@Override public boolean isValid() {
public boolean isValid() { return this.valid;
return this.valid; }
}
@Override
@Override public void setValid(boolean valid) {
public void setValid(boolean valid) { this.valid = valid;
this.valid = valid; }
}
@Override
@Override public String getErrorMessage() {
public String getErrorMessage() { return this.errorMessage;
return this.errorMessage; }
}
@Override
@Override public void setErrorMessage(@Nullable String errorMessage) {
public void setErrorMessage(@Nullable String errorMessage) { this.errorMessage = errorMessage;
this.errorMessage = errorMessage; }
}
@Override
@Override public void setJsclOperation(@NotNull JsclOperation jsclOperation) {
public void setJsclOperation(@NotNull JsclOperation jsclOperation) { this.operation = jsclOperation;
this.operation = jsclOperation; }
}
@NotNull
@NotNull @Override
@Override public JsclOperation getJsclOperation() {
public JsclOperation getJsclOperation() { return this.operation;
return this.operation; }
}
@Override
@Override public void setGenericResult(@Nullable Generic genericResult) {
public void setGenericResult(@Nullable Generic genericResult) { this.genericResult = genericResult;
this.genericResult = genericResult; }
}
@Override
@Override public Generic getGenericResult() {
public Generic getGenericResult() { return this.genericResult;
return this.genericResult; }
}
@Override
@Override public CharSequence getText() {
public CharSequence getText() { return this.testEditor.getText();
return this.testEditor.getText(); }
}
@Override
@Override public void setText(@Nullable CharSequence text) {
public void setText(@Nullable CharSequence text) { this.testEditor.setText(text);
this.testEditor.setText(text); }
}
@Override
@Override public int getSelection() {
public int getSelection() { return this.testEditor.getSelection();
return this.testEditor.getSelection(); }
}
@Override
@Override public void setSelection(int selection) {
public void setSelection(int selection) { this.testEditor.setSelection(selection);
this.testEditor.setSelection(selection); }
} }
}
private static class TestEditor implements Editor {
private static class TestEditor implements Editor {
@Nullable
@Nullable private CharSequence text;
private CharSequence text;
private int selection;
private int selection;
@Nullable
@Nullable @Override
@Override public CharSequence getText() {
public CharSequence getText() { return this.text;
return this.text; }
}
@Override
@Override public void setText(@Nullable CharSequence text) {
public void setText(@Nullable CharSequence text) { this.text = text;
this.text = text; }
}
@Override
@Override public int getSelection() {
public int getSelection() { return this.selection;
return this.selection; }
}
@Override
@Override public void setSelection(int selection) {
public void setSelection(int selection) { this.selection = selection;
this.selection = selection; }
} }
} }
}

View File

@ -1,445 +1,443 @@
/* /*
* Copyright (c) 2009-2011. Created by serso aka se.solovyev. * Copyright (c) 2009-2011. Created by serso aka se.solovyev.
* For more information, please, contact se.solovyev@gmail.com * For more information, please, contact se.solovyev@gmail.com
*/ */
package org.solovyev.android.calculator.model; package org.solovyev.android.calculator.model;
import jscl.AngleUnit; import jscl.AngleUnit;
import jscl.JsclMathEngine; import jscl.JsclMathEngine;
import jscl.NumeralBase; 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 jscl.math.function.CustomFunction; import jscl.math.function.CustomFunction;
import org.junit.Assert; import org.junit.Assert;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import org.solovyev.android.calculator.CalculatorEvalException; import org.solovyev.android.calculator.jscl.JsclOperation;
import org.solovyev.android.calculator.CalculatorParseException;
import org.solovyev.android.calculator.jscl.JsclOperation; import java.text.DecimalFormatSymbols;
import java.util.Locale;
import java.text.DecimalFormatSymbols;
import java.util.Locale; import static junit.framework.Assert.fail;
import static junit.framework.Assert.fail; /**
* User: serso
/** * Date: 9/17/11
* User: serso * Time: 9:47 PM
* Date: 9/17/11 */
* Time: 9:47 PM
*/ public class CalculatorEngineTest {
public class CalculatorEngineTest { @BeforeClass
public static void setUp() throws Exception {
@BeforeClass CalculatorEngine.instance.init(null, null);
public static void setUp() throws Exception { CalculatorEngine.instance.setPrecision(3);
CalculatorEngine.instance.init(null, null); CalculatorEngine.instance.setThreadKiller(new CalculatorEngine.ThreadKillerImpl());
CalculatorEngine.instance.setPrecision(3); }
CalculatorEngine.instance.setThreadKiller(new CalculatorEngine.ThreadKillerImpl());
} @Test
public void testDegrees() throws Exception {
@Test final CalculatorEngine cm = CalculatorEngine.instance;
public void testDegrees() throws Exception {
final CalculatorEngine cm = CalculatorEngine.instance; final AngleUnit defaultAngleUnit = cm.getEngine().getAngleUnits();
try {
final AngleUnit defaultAngleUnit = cm.getEngine().getAngleUnits(); cm.getEngine().setAngleUnits(AngleUnit.rad);
try { cm.setPrecision(3);
cm.getEngine().setAngleUnits(AngleUnit.rad); try {
cm.setPrecision(3); Assert.assertEquals("0.017", cm.evaluate(JsclOperation.numeric, "°"));
try { fail();
Assert.assertEquals("0.017", cm.evaluate(JsclOperation.numeric, "°")); } catch (CalculatorParseException e) {
fail();
} catch (CalculatorParseException e) { }
} Assert.assertEquals("0.017", cm.evaluate(JsclOperation.numeric, "").getResult());
Assert.assertEquals("0.349", cm.evaluate(JsclOperation.numeric, "20.0°").getResult());
Assert.assertEquals("0.017", cm.evaluate(JsclOperation.numeric, "").getStringResult()); Assert.assertEquals("0.5", cm.evaluate(JsclOperation.numeric, "sin(30°)").getResult());
Assert.assertEquals("0.349", cm.evaluate(JsclOperation.numeric, "20.0°").getStringResult()); Assert.assertEquals("0.524", cm.evaluate(JsclOperation.numeric, "asin(sin(30°))").getResult());
Assert.assertEquals("0.5", cm.evaluate(JsclOperation.numeric, "sin(30°)").getStringResult()); Assert.assertEquals("∂(cos(t), t, t, 1°)", cm.evaluate(JsclOperation.numeric, "∂(cos(t),t,t,1°)").getResult());
Assert.assertEquals("0.524", cm.evaluate(JsclOperation.numeric, "asin(sin(30°))").getStringResult());
Assert.assertEquals("∂(cos(t), t, t, 1°)", cm.evaluate(JsclOperation.numeric, "∂(cos(t),t,t,1°)").getStringResult()); Assert.assertEquals("∂(cos(t), t, t, 1°)", cm.evaluate(JsclOperation.simplify, "∂(cos(t),t,t,1°)").getResult());
} finally {
Assert.assertEquals("∂(cos(t), t, t, 1°)", cm.evaluate(JsclOperation.simplify, "∂(cos(t),t,t,1°)").getStringResult()); cm.getEngine().setAngleUnits(defaultAngleUnit);
} finally { }
cm.getEngine().setAngleUnits(defaultAngleUnit); }
}
} @Test
public void testLongExecution() throws Exception {
@Test final CalculatorEngine cm = CalculatorEngine.instance;
public void testLongExecution() throws Exception {
final CalculatorEngine cm = CalculatorEngine.instance; try {
cm.evaluate(JsclOperation.numeric, "3^10^10^10");
try { Assert.fail();
cm.evaluate(JsclOperation.numeric, "3^10^10^10"); } catch (CalculatorParseException e) {
Assert.fail(); if (e.getMessageCode().equals(Messages.msg_3)) {
} catch (CalculatorParseException e) {
if (e.getMessageCode().equals(Messages.msg_3)) { } else {
System.out.print(e.getCause().getMessage());
} else { Assert.fail();
System.out.print(e.getCause().getMessage()); }
Assert.fail(); }
}
} try {
cm.evaluate(JsclOperation.numeric, "9999999!");
try { Assert.fail();
cm.evaluate(JsclOperation.numeric, "9999999!"); } catch (CalculatorParseException e) {
Assert.fail(); if (e.getMessageCode().equals(Messages.msg_3)) {
} catch (CalculatorParseException e) {
if (e.getMessageCode().equals(Messages.msg_3)) { } else {
System.out.print(e.getCause().getMessage());
} else { Assert.fail();
System.out.print(e.getCause().getMessage()); }
Assert.fail(); }
}
} /*final long start = System.currentTimeMillis();
try {
/*final long start = System.currentTimeMillis(); cm.evaluate(JsclOperation.numeric, "3^10^10^10");
try { Assert.fail();
cm.evaluate(JsclOperation.numeric, "3^10^10^10"); } catch (ParseException e) {
Assert.fail(); if (e.getMessage().startsWith("Too long calculation")) {
} catch (ParseException e) { final long end = System.currentTimeMillis();
if (e.getMessage().startsWith("Too long calculation")) { Assert.assertTrue(end - start < 1000);
final long end = System.currentTimeMillis(); } else {
Assert.assertTrue(end - start < 1000); Assert.fail();
} else { }
Assert.fail(); }*/
}
}*/ }
} @Test
public void testEvaluate() throws Exception {
@Test final CalculatorEngine cm = CalculatorEngine.instance;
public void testEvaluate() throws Exception {
final CalculatorEngine cm = CalculatorEngine.instance; Assert.assertEquals("cos(t)+10%", cm.evaluate(JsclOperation.simplify, "cos(t)+10%").getResult());
Assert.assertEquals("cos(t)+10%", cm.evaluate(JsclOperation.simplify, "cos(t)+10%").getStringResult()); final Generic expression = cm.getEngine().simplifyGeneric("cos(t)+10%");
expression.substitute(new Constant("t"), Expression.valueOf(100d));
final Generic expression = cm.getEngine().simplifyGeneric("cos(t)+10%");
expression.substitute(new Constant("t"), Expression.valueOf(100d)); Assert.assertEquals("it", cm.evaluate(JsclOperation.simplify, "it").getResult());
Assert.assertEquals("10%", cm.evaluate(JsclOperation.simplify, "10%").getResult());
Assert.assertEquals("it", cm.evaluate(JsclOperation.simplify, "it").getStringResult()); Assert.assertEquals("0", cm.evaluate(JsclOperation.numeric, "eq(0, 1)").getResult());
Assert.assertEquals("10%", cm.evaluate(JsclOperation.simplify, "10%").getStringResult()); Assert.assertEquals("1", cm.evaluate(JsclOperation.numeric, "eq(1, 1)").getResult());
Assert.assertEquals("0", cm.evaluate(JsclOperation.numeric, "eq(0, 1)").getStringResult()); Assert.assertEquals("1", cm.evaluate(JsclOperation.numeric, "eq( 1, 1)").getResult());
Assert.assertEquals("1", cm.evaluate(JsclOperation.numeric, "eq(1, 1)").getStringResult()); Assert.assertEquals("1", cm.evaluate(JsclOperation.simplify, "eq( 1, 1)").getResult());
Assert.assertEquals("1", cm.evaluate(JsclOperation.numeric, "eq( 1, 1)").getStringResult()); Assert.assertEquals("1", cm.evaluate(JsclOperation.numeric, "lg(10)").getResult());
Assert.assertEquals("1", cm.evaluate(JsclOperation.simplify, "eq( 1, 1)").getStringResult()); Assert.assertEquals("4", cm.evaluate(JsclOperation.numeric, "2+2").getResult());
Assert.assertEquals("1", cm.evaluate(JsclOperation.numeric, "lg(10)").getStringResult()); final AngleUnit defaultAngleUnit = cm.getEngine().getAngleUnits();
Assert.assertEquals("4", cm.evaluate(JsclOperation.numeric, "2+2").getStringResult()); try {
final AngleUnit defaultAngleUnit = cm.getEngine().getAngleUnits(); cm.getEngine().setAngleUnits(AngleUnit.rad);
try { Assert.assertEquals("-0.757", cm.evaluate(JsclOperation.numeric, "sin(4)").getResult());
cm.getEngine().setAngleUnits(AngleUnit.rad); Assert.assertEquals("0.524", cm.evaluate(JsclOperation.numeric, "asin(0.5)").getResult());
Assert.assertEquals("-0.757", cm.evaluate(JsclOperation.numeric, "sin(4)").getStringResult()); Assert.assertEquals("-0.396", cm.evaluate(JsclOperation.numeric, "sin(4)asin(0.5)").getResult());
Assert.assertEquals("0.524", cm.evaluate(JsclOperation.numeric, "asin(0.5)").getStringResult()); Assert.assertEquals("-0.56", cm.evaluate(JsclOperation.numeric, "sin(4)asin(0.5)√(2)").getResult());
Assert.assertEquals("-0.396", cm.evaluate(JsclOperation.numeric, "sin(4)asin(0.5)").getStringResult()); Assert.assertEquals("-0.56", cm.evaluate(JsclOperation.numeric, "sin(4)asin(0.5)√(2)").getResult());
Assert.assertEquals("-0.56", cm.evaluate(JsclOperation.numeric, "sin(4)asin(0.5)√(2)").getStringResult()); } finally {
Assert.assertEquals("-0.56", cm.evaluate(JsclOperation.numeric, "sin(4)asin(0.5)√(2)").getStringResult()); cm.getEngine().setAngleUnits(defaultAngleUnit);
} finally { }
cm.getEngine().setAngleUnits(defaultAngleUnit); Assert.assertEquals("7.389", cm.evaluate(JsclOperation.numeric, "e^2").getResult());
} Assert.assertEquals("7.389", cm.evaluate(JsclOperation.numeric, "exp(1)^2").getResult());
Assert.assertEquals("7.389", cm.evaluate(JsclOperation.numeric, "e^2").getStringResult()); Assert.assertEquals("7.389", cm.evaluate(JsclOperation.numeric, "exp(2)").getResult());
Assert.assertEquals("7.389", cm.evaluate(JsclOperation.numeric, "exp(1)^2").getStringResult()); Assert.assertEquals("2+i", cm.evaluate(JsclOperation.numeric, "2*1+√(-1)").getResult());
Assert.assertEquals("7.389", cm.evaluate(JsclOperation.numeric, "exp(2)").getStringResult()); try {
Assert.assertEquals("2+i", cm.evaluate(JsclOperation.numeric, "2*1+√(-1)").getStringResult()); cm.getEngine().setAngleUnits(AngleUnit.rad);
try { Assert.assertEquals("0.921+Πi", cm.evaluate(JsclOperation.numeric, "ln(5cosh(38π√(2cos(2))))").getResult());
cm.getEngine().setAngleUnits(AngleUnit.rad); Assert.assertEquals("-3.41+3.41i", cm.evaluate(JsclOperation.numeric, "(5tan(2i)+2i)/(1-i)").getResult());
Assert.assertEquals("0.921+Πi", cm.evaluate(JsclOperation.numeric, "ln(5cosh(38π√(2cos(2))))").getStringResult()); } finally {
Assert.assertEquals("-3.41+3.41i", cm.evaluate(JsclOperation.numeric, "(5tan(2i)+2i)/(1-i)").getStringResult()); cm.getEngine().setAngleUnits(defaultAngleUnit);
} finally { }
cm.getEngine().setAngleUnits(defaultAngleUnit); Assert.assertEquals("7.389i", cm.evaluate(JsclOperation.numeric, "iexp(2)").getResult());
} Assert.assertEquals("2+7.389i", cm.evaluate(JsclOperation.numeric, "2+iexp(2)").getResult());
Assert.assertEquals("7.389i", cm.evaluate(JsclOperation.numeric, "iexp(2)").getStringResult()); Assert.assertEquals("2+7.389i", cm.evaluate(JsclOperation.numeric, "2+√(-1)exp(2)").getResult());
Assert.assertEquals("2+7.389i", cm.evaluate(JsclOperation.numeric, "2+iexp(2)").getStringResult()); Assert.assertEquals("2-2.5i", cm.evaluate(JsclOperation.numeric, "2-2.5i").getResult());
Assert.assertEquals("2+7.389i", cm.evaluate(JsclOperation.numeric, "2+√(-1)exp(2)").getStringResult()); Assert.assertEquals("-2-2.5i", cm.evaluate(JsclOperation.numeric, "-2-2.5i").getResult());
Assert.assertEquals("2-2.5i", cm.evaluate(JsclOperation.numeric, "2-2.5i").getStringResult()); Assert.assertEquals("-2+2.5i", cm.evaluate(JsclOperation.numeric, "-2+2.5i").getResult());
Assert.assertEquals("-2-2.5i", cm.evaluate(JsclOperation.numeric, "-2-2.5i").getStringResult()); Assert.assertEquals("-2+2.1i", cm.evaluate(JsclOperation.numeric, "-2+2.1i").getResult());
Assert.assertEquals("-2+2.5i", cm.evaluate(JsclOperation.numeric, "-2+2.5i").getStringResult()); Assert.assertEquals("-0.1-0.2i", cm.evaluate(JsclOperation.numeric, "(1-i)/(2+6i)").getResult());
Assert.assertEquals("-2+2.1i", cm.evaluate(JsclOperation.numeric, "-2+2.1i").getStringResult());
Assert.assertEquals("-0.1-0.2i", cm.evaluate(JsclOperation.numeric, "(1-i)/(2+6i)").getStringResult()); junit.framework.Assert.assertEquals("24", cm.evaluate(JsclOperation.numeric, "4!").getResult());
junit.framework.Assert.assertEquals("24", cm.evaluate(JsclOperation.numeric, "(2+2)!").getResult());
junit.framework.Assert.assertEquals("24", cm.evaluate(JsclOperation.numeric, "4!").getStringResult()); junit.framework.Assert.assertEquals("120", cm.evaluate(JsclOperation.numeric, "(2+2+1)!").getResult());
junit.framework.Assert.assertEquals("24", cm.evaluate(JsclOperation.numeric, "(2+2)!").getStringResult()); junit.framework.Assert.assertEquals("24", cm.evaluate(JsclOperation.numeric, "(2.0+2.0)!").getResult());
junit.framework.Assert.assertEquals("120", cm.evaluate(JsclOperation.numeric, "(2+2+1)!").getStringResult()); junit.framework.Assert.assertEquals("24", cm.evaluate(JsclOperation.numeric, "4.0!").getResult());
junit.framework.Assert.assertEquals("24", cm.evaluate(JsclOperation.numeric, "(2.0+2.0)!").getStringResult()); junit.framework.Assert.assertEquals("720", cm.evaluate(JsclOperation.numeric, "(3!)!").getResult());
junit.framework.Assert.assertEquals("24", cm.evaluate(JsclOperation.numeric, "4.0!").getStringResult()); junit.framework.Assert.assertEquals("36", Expression.valueOf("3!^2").numeric().toString());
junit.framework.Assert.assertEquals("720", cm.evaluate(JsclOperation.numeric, "(3!)!").getStringResult()); junit.framework.Assert.assertEquals("3", Expression.valueOf("cubic(27)").numeric().toString());
junit.framework.Assert.assertEquals("36", Expression.valueOf("3!^2").numeric().toString()); try {
junit.framework.Assert.assertEquals("3", Expression.valueOf("cubic(27)").numeric().toString()); junit.framework.Assert.assertEquals("√(-1)!", cm.evaluate(JsclOperation.numeric, "i!").getResult());
try { fail();
junit.framework.Assert.assertEquals("√(-1)!", cm.evaluate(JsclOperation.numeric, "i!").getStringResult()); } catch (CalculatorParseException e) {
fail(); }
} catch (CalculatorParseException e) {
} junit.framework.Assert.assertEquals("1", cm.evaluate(JsclOperation.numeric, "(π/π)!").getResult());
junit.framework.Assert.assertEquals("1", cm.evaluate(JsclOperation.numeric, "(π/π)!").getStringResult()); try {
junit.framework.Assert.assertEquals("i", cm.evaluate(JsclOperation.numeric, "(-1)i!").getResult());
try { fail();
junit.framework.Assert.assertEquals("i", cm.evaluate(JsclOperation.numeric, "(-1)i!").getStringResult()); } catch (CalculatorParseException e) {
fail();
} catch (CalculatorParseException e) { }
junit.framework.Assert.assertEquals("24i", cm.evaluate(JsclOperation.numeric, "4!i").getResult());
}
junit.framework.Assert.assertEquals("24i", cm.evaluate(JsclOperation.numeric, "4!i").getStringResult()); CalculatorEngine.instance.getVarsRegistry().add(new Var.Builder("si", 5d));
CalculatorEngine.instance.getVarsRegistry().add(new Var.Builder("si", 5d)); try {
cm.getEngine().setAngleUnits(AngleUnit.rad);
try { Assert.assertEquals("0.451", cm.evaluate(JsclOperation.numeric, "acos(0.8999999999999811)").getResult());
cm.getEngine().setAngleUnits(AngleUnit.rad); Assert.assertEquals("-0.959", cm.evaluate(JsclOperation.numeric, "sin(5)").getResult());
Assert.assertEquals("0.451", cm.evaluate(JsclOperation.numeric, "acos(0.8999999999999811)").getStringResult()); Assert.assertEquals("-4.795", cm.evaluate(JsclOperation.numeric, "sin(5)si").getResult());
Assert.assertEquals("-0.959", cm.evaluate(JsclOperation.numeric, "sin(5)").getStringResult()); Assert.assertEquals("-23.973", cm.evaluate(JsclOperation.numeric, "sisin(5)si").getResult());
Assert.assertEquals("-4.795", cm.evaluate(JsclOperation.numeric, "sin(5)si").getStringResult()); Assert.assertEquals("-23.973", cm.evaluate(JsclOperation.numeric, "si*sin(5)si").getResult());
Assert.assertEquals("-23.973", cm.evaluate(JsclOperation.numeric, "sisin(5)si").getStringResult()); Assert.assertEquals("-3.309", cm.evaluate(JsclOperation.numeric, "sisin(5si)si").getResult());
Assert.assertEquals("-23.973", cm.evaluate(JsclOperation.numeric, "si*sin(5)si").getStringResult()); } finally {
Assert.assertEquals("-3.309", cm.evaluate(JsclOperation.numeric, "sisin(5si)si").getStringResult()); cm.getEngine().setAngleUnits(defaultAngleUnit);
} finally { }
cm.getEngine().setAngleUnits(defaultAngleUnit);
} CalculatorEngine.instance.getVarsRegistry().add(new Var.Builder("s", 1d));
Assert.assertEquals("5", cm.evaluate(JsclOperation.numeric, "si").getResult());
CalculatorEngine.instance.getVarsRegistry().add(new Var.Builder("s", 1d));
Assert.assertEquals("5", cm.evaluate(JsclOperation.numeric, "si").getStringResult()); CalculatorEngine.instance.getVarsRegistry().add(new Var.Builder("k", 3.5d));
CalculatorEngine.instance.getVarsRegistry().add(new Var.Builder("k1", 4d));
CalculatorEngine.instance.getVarsRegistry().add(new Var.Builder("k", 3.5d)); Assert.assertEquals("4", cm.evaluate(JsclOperation.numeric, "k11").getResult());
CalculatorEngine.instance.getVarsRegistry().add(new Var.Builder("k1", 4d));
Assert.assertEquals("4", cm.evaluate(JsclOperation.numeric, "k11").getStringResult()); CalculatorEngine.instance.getVarsRegistry().add(new Var.Builder("t", (String) null));
Assert.assertEquals("11t", cm.evaluate(JsclOperation.numeric, "t11").getResult());
CalculatorEngine.instance.getVarsRegistry().add(new Var.Builder("t", (String) null)); Assert.assertEquals("11et", cm.evaluate(JsclOperation.numeric, "t11e").getResult());
Assert.assertEquals("11t", cm.evaluate(JsclOperation.numeric, "t11").getStringResult()); Assert.assertEquals("", cm.evaluate(JsclOperation.numeric, "").getResult());
Assert.assertEquals("11et", cm.evaluate(JsclOperation.numeric, "t11e").getStringResult()); Assert.assertEquals("", cm.evaluate(JsclOperation.numeric, "Infinity").getResult());
Assert.assertEquals("", cm.evaluate(JsclOperation.numeric, "").getStringResult()); Assert.assertEquals("11∞t", cm.evaluate(JsclOperation.numeric, "t11∞").getResult());
Assert.assertEquals("", cm.evaluate(JsclOperation.numeric, "Infinity").getStringResult()); Assert.assertEquals("-t+t^3", cm.evaluate(JsclOperation.numeric, "t(t-1)(t+1)").getResult());
Assert.assertEquals("11∞t", cm.evaluate(JsclOperation.numeric, "t11∞").getStringResult());
Assert.assertEquals("-t+t^3", cm.evaluate(JsclOperation.numeric, "t(t-1)(t+1)").getStringResult()); Assert.assertEquals("100", cm.evaluate(JsclOperation.numeric, "0.1E3").getResult());
Assert.assertEquals("3.957", cm.evaluate(JsclOperation.numeric, "ln(8)lg(8)+ln(8)").getResult());
Assert.assertEquals("100", cm.evaluate(JsclOperation.numeric, "0.1E3").getStringResult());
Assert.assertEquals("3.957", cm.evaluate(JsclOperation.numeric, "ln(8)lg(8)+ln(8)").getStringResult()); Assert.assertEquals("0.933", cm.evaluate(JsclOperation.numeric, "0x:E/0x:F").getResult());
Assert.assertEquals("0.933", cm.evaluate(JsclOperation.numeric, "0x:E/0x:F").getStringResult()); try {
cm.getEngine().setNumeralBase(NumeralBase.hex);
try { Assert.assertEquals("E/F", cm.evaluate(JsclOperation.numeric, "0x:E/0x:F").getResult());
cm.getEngine().setNumeralBase(NumeralBase.hex); Assert.assertEquals("E/F", cm.evaluate(JsclOperation.simplify, "0x:E/0x:F").getResult());
Assert.assertEquals("E/F", cm.evaluate(JsclOperation.numeric, "0x:E/0x:F").getStringResult()); Assert.assertEquals("E/F", cm.evaluate(JsclOperation.numeric, "E/F").getResult());
Assert.assertEquals("E/F", cm.evaluate(JsclOperation.simplify, "0x:E/0x:F").getStringResult()); Assert.assertEquals("E/F", cm.evaluate(JsclOperation.simplify, "E/F").getResult());
Assert.assertEquals("E/F", cm.evaluate(JsclOperation.numeric, "E/F").getStringResult()); } finally {
Assert.assertEquals("E/F", cm.evaluate(JsclOperation.simplify, "E/F").getStringResult()); cm.getEngine().setNumeralBase(NumeralBase.dec);
} finally { }
cm.getEngine().setNumeralBase(NumeralBase.dec);
} Assert.assertEquals("0", cm.evaluate(JsclOperation.numeric, "((((((0))))))").getResult());
Assert.assertEquals("0", cm.evaluate(JsclOperation.numeric, "((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((0))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))").getResult());
Assert.assertEquals("0", cm.evaluate(JsclOperation.numeric, "((((((0))))))").getStringResult());
Assert.assertEquals("0", cm.evaluate(JsclOperation.numeric, "((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((0))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))").getStringResult());
/* Assert.assertEquals("0.524", cm.evaluate(JsclOperation.numeric, "30°").getResult());
Assert.assertEquals("0.524", cm.evaluate(JsclOperation.numeric, "(10+20)°").getResult());
/* Assert.assertEquals("0.524", cm.evaluate(JsclOperation.numeric, "30°").getResult()); Assert.assertEquals("1.047", cm.evaluate(JsclOperation.numeric, "(10+20)°*2").getResult());
Assert.assertEquals("0.524", cm.evaluate(JsclOperation.numeric, "(10+20)°").getResult()); try {
Assert.assertEquals("1.047", cm.evaluate(JsclOperation.numeric, "(10+20)°*2").getResult()); Assert.assertEquals("0.278", cm.evaluate(JsclOperation.numeric, "30°^2").getResult());
try { junit.framework.Assert.fail();
Assert.assertEquals("0.278", cm.evaluate(JsclOperation.numeric, "30°^2").getResult()); } catch (ParseException e) {
junit.framework.Assert.fail(); if ( !e.getMessage().equals("Power operation after postfix function is currently unsupported!") ) {
} catch (ParseException e) { junit.framework.Assert.fail();
if ( !e.getMessage().equals("Power operation after postfix function is currently unsupported!") ) { }
junit.framework.Assert.fail(); }*/
}
}*/ /* try {
cm.setTimeout(5000);
/* try { Assert.assertEquals("2", cm.evaluate(JsclOperation.numeric, "2!").getResult());
cm.setTimeout(5000); } finally {
Assert.assertEquals("2", cm.evaluate(JsclOperation.numeric, "2!").getResult()); cm.setTimeout(3000);
} finally { }*/
cm.setTimeout(3000);
}*/ CalculatorEngine.instance.getVarsRegistry().add(new Var.Builder("t", (String) null));
Assert.assertEquals("2t", cm.evaluate(JsclOperation.simplify, "∂(t^2,t)").getResult());
CalculatorEngine.instance.getVarsRegistry().add(new Var.Builder("t", (String) null)); Assert.assertEquals("2t", cm.evaluate(JsclOperation.numeric, "∂(t^2,t)").getResult());
Assert.assertEquals("2t", cm.evaluate(JsclOperation.simplify, "∂(t^2,t)").getStringResult()); CalculatorEngine.instance.getVarsRegistry().add(new Var.Builder("t", "2"));
Assert.assertEquals("2t", cm.evaluate(JsclOperation.numeric, "∂(t^2,t)").getStringResult()); Assert.assertEquals("2t", cm.evaluate(JsclOperation.simplify, "∂(t^2,t)").getResult());
CalculatorEngine.instance.getVarsRegistry().add(new Var.Builder("t", "2")); Assert.assertEquals("4", cm.evaluate(JsclOperation.numeric, "∂(t^2,t)").getResult());
Assert.assertEquals("2t", cm.evaluate(JsclOperation.simplify, "∂(t^2,t)").getStringResult());
Assert.assertEquals("4", cm.evaluate(JsclOperation.numeric, "∂(t^2,t)").getStringResult()); Assert.assertEquals("-x+x*ln(x)", cm.getEngine().simplify("∫(ln(x), x)"));
Assert.assertEquals("-(x-x*ln(x))/(ln(2)+ln(5))", cm.getEngine().simplify("∫(log(10, x), x)"));
Assert.assertEquals("-x+x*ln(x)", cm.getEngine().simplify("∫(ln(x), x)"));
Assert.assertEquals("-(x-x*ln(x))/(ln(2)+ln(5))", cm.getEngine().simplify("∫(log(10, x), x)")); Assert.assertEquals("∫((ln(2)+ln(5))/ln(x), x)", cm.getEngine().simplify("∫(ln(10)/ln(x), x)"));
Assert.assertEquals("∫(ln(10)/ln(x), x)", Expression.valueOf("∫(log(x, 10), x)").expand().toString());
Assert.assertEquals("∫((ln(2)+ln(5))/ln(x), x)", cm.getEngine().simplify("∫(ln(10)/ln(x), x)")); Assert.assertEquals("∫((ln(2)+ln(5))/ln(x), x)", cm.getEngine().simplify("∫(log(x, 10), x)"));
Assert.assertEquals("∫(ln(10)/ln(x), x)", Expression.valueOf("∫(log(x, 10), x)").expand().toString()); }
Assert.assertEquals("∫((ln(2)+ln(5))/ln(x), x)", cm.getEngine().simplify("∫(log(x, 10), x)"));
} @Test
public void testFormatting() throws Exception {
@Test final CalculatorEngine ce = CalculatorEngine.instance;
public void testFormatting() throws Exception {
final CalculatorEngine ce = CalculatorEngine.instance; Assert.assertEquals("12 345", ce.evaluate(JsclOperation.simplify, "12345").getResult());
Assert.assertEquals("12 345", ce.evaluate(JsclOperation.simplify, "12345").getStringResult()); }
} @Test
public void testI() throws CalculatorParseException, CalculatorEvalException {
@Test final CalculatorEngine cm = CalculatorEngine.instance;
public void testI() throws CalculatorParseException, CalculatorEvalException {
final CalculatorEngine cm = CalculatorEngine.instance; Assert.assertEquals("-i", cm.evaluate(JsclOperation.numeric, "i^3").getResult());
for (int i = 0; i < 1000; i++) {
Assert.assertEquals("-i", cm.evaluate(JsclOperation.numeric, "i^3").getStringResult()); double real = (Math.random()-0.5) * 1000;
for (int i = 0; i < 1000; i++) { double imag = (Math.random()-0.5) * 1000;
double real = (Math.random()-0.5) * 1000; int exp = (int)(Math.random() * 10);
double imag = (Math.random()-0.5) * 1000;
int exp = (int)(Math.random() * 10); final StringBuilder sb = new StringBuilder();
sb.append(real);
final StringBuilder sb = new StringBuilder(); if ( imag > 0 ) {
sb.append(real); sb.append("+");
if ( imag > 0 ) { }
sb.append("+"); sb.append(imag);
} sb.append("^").append(exp);
sb.append(imag); try {
sb.append("^").append(exp); cm.evaluate(JsclOperation.numeric, sb.toString()).getResult();
try { } catch (Throwable e) {
cm.evaluate(JsclOperation.numeric, sb.toString()).getStringResult(); fail(sb.toString());
} catch (Throwable e) { }
fail(sb.toString()); }
} }
}
} @Test
public void testEmptyFunction() throws Exception {
@Test final CalculatorEngine cm = CalculatorEngine.instance;
public void testEmptyFunction() throws Exception { try {
final CalculatorEngine cm = CalculatorEngine.instance; cm.evaluate(JsclOperation.numeric, "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())))))))))))))))))))))))))))))))))))))");
try { Assert.fail();
cm.evaluate(JsclOperation.numeric, "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())))))))))))))))))))))))))))))))))))))"); } catch (CalculatorParseException e) {
Assert.fail(); }
} catch (CalculatorParseException e) { Assert.assertEquals("0.34+1.382i", cm.evaluate(JsclOperation.numeric, "ln(ln(ln(ln(ln(ln(ln(ln(ln(ln(ln(ln(ln(ln(ln(100)))))))))))))))").getResult());
} try {
Assert.assertEquals("0.34+1.382i", cm.evaluate(JsclOperation.numeric, "ln(ln(ln(ln(ln(ln(ln(ln(ln(ln(ln(ln(ln(ln(ln(100)))))))))))))))").getStringResult()); cm.evaluate(JsclOperation.numeric, "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())))))))))))))))))))))))))))))))))))");
try { Assert.fail();
cm.evaluate(JsclOperation.numeric, "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())))))))))))))))))))))))))))))))))))"); } catch (CalculatorParseException e) {
Assert.fail(); }
} catch (CalculatorParseException e) {
} final AngleUnit defaultAngleUnit = cm.getEngine().getAngleUnits();
try {
final AngleUnit defaultAngleUnit = cm.getEngine().getAngleUnits(); cm.getEngine().setAngleUnits(AngleUnit.rad);
try { Assert.assertEquals("0.739", cm.evaluate(JsclOperation.numeric, "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))))))))))))))))))))))))))))))))))))").getResult());
cm.getEngine().setAngleUnits(AngleUnit.rad); } finally {
Assert.assertEquals("0.739", cm.evaluate(JsclOperation.numeric, "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))))))))))))))))))))))))))))))))))))").getStringResult()); cm.getEngine().setAngleUnits(defaultAngleUnit);
} finally { }
cm.getEngine().setAngleUnits(defaultAngleUnit);
} CalculatorEngine.instance.getVarsRegistry().add(new Var.Builder("si", 5d));
Assert.assertEquals("5", cm.evaluate(JsclOperation.numeric, "si").getResult());
CalculatorEngine.instance.getVarsRegistry().add(new Var.Builder("si", 5d));
Assert.assertEquals("5", cm.evaluate(JsclOperation.numeric, "si").getStringResult()); try {
cm.evaluate(JsclOperation.numeric, "sin");
try { Assert.fail();
cm.evaluate(JsclOperation.numeric, "sin"); } catch (CalculatorParseException e) {
Assert.fail(); }
} catch (CalculatorParseException e) { }
}
} @Test
public void testRounding() throws Exception {
@Test final CalculatorEngine cm = CalculatorEngine.instance;
public void testRounding() throws Exception {
final CalculatorEngine cm = CalculatorEngine.instance; try {
DecimalFormatSymbols decimalGroupSymbols = new DecimalFormatSymbols(Locale.getDefault());
try { decimalGroupSymbols.setDecimalSeparator('.');
DecimalFormatSymbols decimalGroupSymbols = new DecimalFormatSymbols(Locale.getDefault()); decimalGroupSymbols.setGroupingSeparator('\'');
decimalGroupSymbols.setDecimalSeparator('.'); cm.setDecimalGroupSymbols(decimalGroupSymbols);
decimalGroupSymbols.setGroupingSeparator('\''); cm.setPrecision(2);
cm.setDecimalGroupSymbols(decimalGroupSymbols); Assert.assertEquals("12'345'678.9", cm.evaluate(JsclOperation.numeric, "1.23456789E7").getResult());
cm.setPrecision(2); cm.setPrecision(10);
Assert.assertEquals("12'345'678.9", cm.evaluate(JsclOperation.numeric, "1.23456789E7").getStringResult()); Assert.assertEquals("12'345'678.9", cm.evaluate(JsclOperation.numeric, "1.23456789E7").getResult());
cm.setPrecision(10); Assert.assertEquals("123'456'789", cm.evaluate(JsclOperation.numeric, "1.234567890E8").getResult());
Assert.assertEquals("12'345'678.9", cm.evaluate(JsclOperation.numeric, "1.23456789E7").getStringResult()); Assert.assertEquals("1'234'567'890.1", cm.evaluate(JsclOperation.numeric, "1.2345678901E9").getResult());
Assert.assertEquals("123'456'789", cm.evaluate(JsclOperation.numeric, "1.234567890E8").getStringResult()); } finally {
Assert.assertEquals("1'234'567'890.1", cm.evaluate(JsclOperation.numeric, "1.2345678901E9").getStringResult()); cm.setPrecision(3);
} finally { DecimalFormatSymbols decimalGroupSymbols = new DecimalFormatSymbols(Locale.getDefault());
cm.setPrecision(3); decimalGroupSymbols.setDecimalSeparator('.');
DecimalFormatSymbols decimalGroupSymbols = new DecimalFormatSymbols(Locale.getDefault()); decimalGroupSymbols.setGroupingSeparator(JsclMathEngine.GROUPING_SEPARATOR_DEFAULT.charAt(0));
decimalGroupSymbols.setDecimalSeparator('.'); cm.setDecimalGroupSymbols(decimalGroupSymbols);
decimalGroupSymbols.setGroupingSeparator(JsclMathEngine.GROUPING_SEPARATOR_DEFAULT.charAt(0)); }
cm.setDecimalGroupSymbols(decimalGroupSymbols); }
}
} @Test
public void testComparisonFunction() throws Exception {
@Test final CalculatorEngine cm = CalculatorEngine.instance;
public void testComparisonFunction() throws Exception {
final CalculatorEngine cm = CalculatorEngine.instance; Assert.assertEquals("0", cm.evaluate(JsclOperation.numeric, "eq(0, 1)").getResult());
Assert.assertEquals("1", cm.evaluate(JsclOperation.numeric, "eq(1, 1)").getResult());
Assert.assertEquals("0", cm.evaluate(JsclOperation.numeric, "eq(0, 1)").getStringResult()); Assert.assertEquals("1", cm.evaluate(JsclOperation.numeric, "eq(1, 1.0)").getResult());
Assert.assertEquals("1", cm.evaluate(JsclOperation.numeric, "eq(1, 1)").getStringResult()); Assert.assertEquals("0", cm.evaluate(JsclOperation.numeric, "eq(1, 1.000000000000001)").getResult());
Assert.assertEquals("1", cm.evaluate(JsclOperation.numeric, "eq(1, 1.0)").getStringResult()); Assert.assertEquals("0", cm.evaluate(JsclOperation.numeric, "eq(1, 0)").getResult());
Assert.assertEquals("0", cm.evaluate(JsclOperation.numeric, "eq(1, 1.000000000000001)").getStringResult());
Assert.assertEquals("0", cm.evaluate(JsclOperation.numeric, "eq(1, 0)").getStringResult()); Assert.assertEquals("1", cm.evaluate(JsclOperation.numeric, "lt(0, 1)").getResult());
Assert.assertEquals("0", cm.evaluate(JsclOperation.numeric, "lt(1, 1)").getResult());
Assert.assertEquals("1", cm.evaluate(JsclOperation.numeric, "lt(0, 1)").getStringResult()); Assert.assertEquals("0", cm.evaluate(JsclOperation.numeric, "lt(1, 0)").getResult());
Assert.assertEquals("0", cm.evaluate(JsclOperation.numeric, "lt(1, 1)").getStringResult());
Assert.assertEquals("0", cm.evaluate(JsclOperation.numeric, "lt(1, 0)").getStringResult()); Assert.assertEquals("0", cm.evaluate(JsclOperation.numeric, "gt(0, 1)").getResult());
Assert.assertEquals("0", cm.evaluate(JsclOperation.numeric, "gt(1, 1)").getResult());
Assert.assertEquals("0", cm.evaluate(JsclOperation.numeric, "gt(0, 1)").getStringResult()); Assert.assertEquals("1", cm.evaluate(JsclOperation.numeric, "gt(1, 0)").getResult());
Assert.assertEquals("0", cm.evaluate(JsclOperation.numeric, "gt(1, 1)").getStringResult());
Assert.assertEquals("1", cm.evaluate(JsclOperation.numeric, "gt(1, 0)").getStringResult()); Assert.assertEquals("1", cm.evaluate(JsclOperation.numeric, "ne(0, 1)").getResult());
Assert.assertEquals("0", cm.evaluate(JsclOperation.numeric, "ne(1, 1)").getResult());
Assert.assertEquals("1", cm.evaluate(JsclOperation.numeric, "ne(0, 1)").getStringResult()); Assert.assertEquals("1", cm.evaluate(JsclOperation.numeric, "ne(1, 0)").getResult());
Assert.assertEquals("0", cm.evaluate(JsclOperation.numeric, "ne(1, 1)").getStringResult());
Assert.assertEquals("1", cm.evaluate(JsclOperation.numeric, "ne(1, 0)").getStringResult()); Assert.assertEquals("1", cm.evaluate(JsclOperation.numeric, "le(0, 1)").getResult());
Assert.assertEquals("1", cm.evaluate(JsclOperation.numeric, "le(1, 1)").getResult());
Assert.assertEquals("1", cm.evaluate(JsclOperation.numeric, "le(0, 1)").getStringResult()); Assert.assertEquals("0", cm.evaluate(JsclOperation.numeric, "le(1, 0)").getResult());
Assert.assertEquals("1", cm.evaluate(JsclOperation.numeric, "le(1, 1)").getStringResult());
Assert.assertEquals("0", cm.evaluate(JsclOperation.numeric, "le(1, 0)").getStringResult()); Assert.assertEquals("0", cm.evaluate(JsclOperation.numeric, "ge(0, 1)").getResult());
Assert.assertEquals("1", cm.evaluate(JsclOperation.numeric, "ge(1, 1)").getResult());
Assert.assertEquals("0", cm.evaluate(JsclOperation.numeric, "ge(0, 1)").getStringResult()); Assert.assertEquals("1", cm.evaluate(JsclOperation.numeric, "ge(1, 0)").getResult());
Assert.assertEquals("1", cm.evaluate(JsclOperation.numeric, "ge(1, 1)").getStringResult());
Assert.assertEquals("1", cm.evaluate(JsclOperation.numeric, "ge(1, 0)").getStringResult()); Assert.assertEquals("0", cm.evaluate(JsclOperation.numeric, "ap(0, 1)").getResult());
Assert.assertEquals("1", cm.evaluate(JsclOperation.numeric, "ap(1, 1)").getResult());
Assert.assertEquals("0", cm.evaluate(JsclOperation.numeric, "ap(0, 1)").getStringResult()); //Assert.assertEquals("1", cm.evaluate(JsclOperation.numeric, "ap(1, 1.000000000000001)").getResult());
Assert.assertEquals("1", cm.evaluate(JsclOperation.numeric, "ap(1, 1)").getStringResult()); Assert.assertEquals("0", cm.evaluate(JsclOperation.numeric, "ap(1, 0)").getResult());
//Assert.assertEquals("1", cm.evaluate(JsclOperation.numeric, "ap(1, 1.000000000000001)").getResult());
Assert.assertEquals("0", cm.evaluate(JsclOperation.numeric, "ap(1, 0)").getStringResult()); }
}
@Test
public void testNumeralSystems() throws Exception {
@Test final CalculatorEngine cm = CalculatorEngine.instance;
public void testNumeralSystems() throws Exception {
final CalculatorEngine cm = CalculatorEngine.instance; Assert.assertEquals("11 259 375", cm.evaluate(JsclOperation.numeric, "0x:ABCDEF").getResult());
Assert.assertEquals("30 606 154.462", cm.evaluate(JsclOperation.numeric, "0x:ABCDEF*e").getResult());
Assert.assertEquals("11 259 375", cm.evaluate(JsclOperation.numeric, "0x:ABCDEF").getStringResult()); Assert.assertEquals("30 606 154.462", cm.evaluate(JsclOperation.numeric, "e*0x:ABCDEF").getResult());
Assert.assertEquals("30 606 154.462", cm.evaluate(JsclOperation.numeric, "0x:ABCDEF*e").getStringResult()); Assert.assertEquals("e", cm.evaluate(JsclOperation.numeric, "e*0x:ABCDEF/0x:ABCDEF").getResult());
Assert.assertEquals("30 606 154.462", cm.evaluate(JsclOperation.numeric, "e*0x:ABCDEF").getStringResult()); Assert.assertEquals("30 606 154.462", cm.evaluate(JsclOperation.numeric, "0x:ABCDEF*e*0x:ABCDEF/0x:ABCDEF").getResult());
Assert.assertEquals("e", cm.evaluate(JsclOperation.numeric, "e*0x:ABCDEF/0x:ABCDEF").getStringResult()); Assert.assertEquals("30 606 154.462", cm.evaluate(JsclOperation.numeric, "c+0x:ABCDEF*e*0x:ABCDEF/0x:ABCDEF-c+0x:C-0x:C").getResult());
Assert.assertEquals("30 606 154.462", cm.evaluate(JsclOperation.numeric, "0x:ABCDEF*e*0x:ABCDEF/0x:ABCDEF").getStringResult()); Assert.assertEquals("1 446 257 064 651.832", cm.evaluate(JsclOperation.numeric, "28*28 * sin(28) - 0b:1101 + √(28) + exp ( 28) ").getResult());
Assert.assertEquals("30 606 154.462", cm.evaluate(JsclOperation.numeric, "c+0x:ABCDEF*e*0x:ABCDEF/0x:ABCDEF-c+0x:C-0x:C").getStringResult()); Assert.assertEquals("13", cm.evaluate(JsclOperation.numeric, "0b:1101").getResult());
Assert.assertEquals("1 446 257 064 651.832", cm.evaluate(JsclOperation.numeric, "28*28 * sin(28) - 0b:1101 + √(28) + exp ( 28) ").getStringResult());
Assert.assertEquals("13", cm.evaluate(JsclOperation.numeric, "0b:1101").getStringResult()); try {
cm.evaluate(JsclOperation.numeric, "0b:π").getResult();
try { Assert.fail();
cm.evaluate(JsclOperation.numeric, "0b:π").getStringResult(); } catch (CalculatorParseException e) {
Assert.fail(); // ok
} catch (CalculatorParseException e) { }
// ok
} final NumeralBase defaultNumeralBase = cm.getEngine().getNumeralBase();
try{
final NumeralBase defaultNumeralBase = cm.getEngine().getNumeralBase(); cm.getEngine().setNumeralBase(NumeralBase.bin);
try{ Assert.assertEquals("101", cm.evaluate(JsclOperation.numeric, "10+11").getResult());
cm.getEngine().setNumeralBase(NumeralBase.bin); Assert.assertEquals("10/11", cm.evaluate(JsclOperation.numeric, "10/11").getResult());
Assert.assertEquals("101", cm.evaluate(JsclOperation.numeric, "10+11").getStringResult());
Assert.assertEquals("10/11", cm.evaluate(JsclOperation.numeric, "10/11").getStringResult()); cm.getEngine().setNumeralBase(NumeralBase.hex);
Assert.assertEquals("63 7B", cm.evaluate(JsclOperation.numeric, "56CE+CAD").getResult());
cm.getEngine().setNumeralBase(NumeralBase.hex); Assert.assertEquals("E", cm.evaluate(JsclOperation.numeric, "E").getResult());
Assert.assertEquals("63 7B", cm.evaluate(JsclOperation.numeric, "56CE+CAD").getStringResult()); } finally {
Assert.assertEquals("E", cm.evaluate(JsclOperation.numeric, "E").getStringResult()); cm.setNumeralBase(defaultNumeralBase);
} finally { }
cm.setNumeralBase(defaultNumeralBase); }
}
} @Test
public void testLog() throws Exception {
@Test final CalculatorEngine cm = CalculatorEngine.instance;
public void testLog() throws Exception {
final CalculatorEngine cm = CalculatorEngine.instance; Assert.assertEquals("", Expression.valueOf("1/0").numeric().toString());
Assert.assertEquals("", Expression.valueOf("ln(10)/ln(1)").numeric().toString());
Assert.assertEquals("", Expression.valueOf("1/0").numeric().toString());
Assert.assertEquals("", Expression.valueOf("ln(10)/ln(1)").numeric().toString()); // logarithm
Assert.assertEquals("ln(x)/ln(base)", ((CustomFunction) cm.getFunctionsRegistry().get("log")).getContent());
// logarithm Assert.assertEquals("", cm.evaluate(JsclOperation.numeric, "log(1, 10)").getResult());
Assert.assertEquals("ln(x)/ln(base)", ((CustomFunction) cm.getFunctionsRegistry().get("log")).getContent()); Assert.assertEquals("3.322", cm.evaluate(JsclOperation.numeric, "log(2, 10)").getResult());
Assert.assertEquals("", cm.evaluate(JsclOperation.numeric, "log(1, 10)").getStringResult()); Assert.assertEquals("1.431", cm.evaluate(JsclOperation.numeric, "log(5, 10)").getResult());
Assert.assertEquals("3.322", cm.evaluate(JsclOperation.numeric, "log(2, 10)").getStringResult()); Assert.assertEquals("0.96", cm.evaluate(JsclOperation.numeric, "log(11, 10)").getResult());
Assert.assertEquals("1.431", cm.evaluate(JsclOperation.numeric, "log(5, 10)").getStringResult()); Assert.assertEquals("1/(bln(a))", cm.evaluate(JsclOperation.simplify, "∂(log(a, b), b)").getResult());
Assert.assertEquals("0.96", cm.evaluate(JsclOperation.numeric, "log(11, 10)").getStringResult()); Assert.assertEquals("-ln(b)/(aln(a)^2)", cm.evaluate(JsclOperation.simplify, "∂(log(a, b), a)").getResult());
Assert.assertEquals("1/(bln(a))", cm.evaluate(JsclOperation.simplify, "∂(log(a, b), b)").getStringResult());
Assert.assertEquals("-ln(b)/(aln(a)^2)", cm.evaluate(JsclOperation.simplify, "∂(log(a, b), a)").getStringResult()); }
}
}
}

View File

@ -3,7 +3,6 @@ package org.solovyev.android.calculator.model;
import org.junit.Assert; import org.junit.Assert;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import org.solovyev.android.calculator.text.FromJsclSimplifyTextProcessor;
import java.text.DecimalFormatSymbols; import java.text.DecimalFormatSymbols;

View File

@ -1,148 +1,146 @@
package org.solovyev.android.calculator.model; package org.solovyev.android.calculator.model;
import au.com.bytecode.opencsv.CSVReader; import au.com.bytecode.opencsv.CSVReader;
import jscl.JsclMathEngine; import jscl.JsclMathEngine;
import jscl.MathEngine; import jscl.MathEngine;
import jscl.math.Expression; import jscl.math.Expression;
import jscl.text.ParseException; import jscl.text.ParseException;
import jscl.util.ExpressionGeneratorWithInput; import jscl.util.ExpressionGeneratorWithInput;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.junit.Assert; import org.junit.Assert;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import org.solovyev.android.calculator.CalculatorEvalException; import org.solovyev.android.calculator.jscl.JsclOperation;
import org.solovyev.android.calculator.CalculatorParseException; import org.solovyev.common.Converter;
import org.solovyev.android.calculator.jscl.JsclOperation;
import org.solovyev.common.Converter; import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.InputStreamReader; import java.util.List;
import java.util.ArrayList;
import java.util.List; /**
* User: serso
/** * Date: 12/14/11
* User: serso * Time: 4:16 PM
* Date: 12/14/11 */
* Time: 4:16 PM public class NumeralBaseTest {
*/
public class NumeralBaseTest { @BeforeClass
public static void setUp() throws Exception {
@BeforeClass CalculatorEngine.instance.init(null, null);
public static void setUp() throws Exception { CalculatorEngine.instance.setPrecision(3);
CalculatorEngine.instance.init(null, null); CalculatorEngine.instance.setThreadKiller(new CalculatorEngine.ThreadKillerImpl());
CalculatorEngine.instance.setPrecision(3); }
CalculatorEngine.instance.setThreadKiller(new CalculatorEngine.ThreadKillerImpl());
} @Test
public void testConversion() throws Exception {
@Test CSVReader reader = null;
public void testConversion() throws Exception { try {
CSVReader reader = null; final MathEngine me = JsclMathEngine.instance;
try {
final MathEngine me = JsclMathEngine.instance; reader = new CSVReader(new InputStreamReader(NumeralBaseTest.class.getResourceAsStream("/org/solovyev/android/calculator/model/nb_table.csv")), '\t');
reader = new CSVReader(new InputStreamReader(NumeralBaseTest.class.getResourceAsStream("/org/solovyev/android/calculator/model/nb_table.csv")), '\t'); // skip first line
reader.readNext();
// skip first line
reader.readNext(); String[] line = reader.readNext();
for (; line != null; line = reader.readNext()) {
String[] line = reader.readNext(); testExpression(line, new DummyExpression());
for (; line != null; line = reader.readNext()) { testExpression(line, new Expression1());
testExpression(line, new DummyExpression()); testExpression(line, new Expression2());
testExpression(line, new Expression1()); testExpression(line, new Expression3());
testExpression(line, new Expression2());
testExpression(line, new Expression3()); final String dec = line[0].toUpperCase();
final String hex = "0x:" + line[1].toUpperCase();
final String dec = line[0].toUpperCase(); final String bin = "0b:" + line[2].toUpperCase();
final String hex = "0x:" + line[1].toUpperCase();
final String bin = "0b:" + line[2].toUpperCase(); final List<String> input = new ArrayList<String>();
input.add(dec);
final List<String> input = new ArrayList<String>(); input.add(hex);
input.add(dec); input.add(bin);
input.add(hex);
input.add(bin); //System.out.println("Dec: " + dec);
//System.out.println("Hex: " + hex);
//System.out.println("Dec: " + dec); //System.out.println("Bin: " + bin);
//System.out.println("Hex: " + hex);
//System.out.println("Bin: " + bin); final ExpressionGeneratorWithInput eg = new ExpressionGeneratorWithInput(input, 20);
final List<String> expressions = eg.generate();
final ExpressionGeneratorWithInput eg = new ExpressionGeneratorWithInput(input, 20);
final List<String> expressions = eg.generate(); final String decExpression = expressions.get(0);
final String hexExpression = expressions.get(1);
final String decExpression = expressions.get(0); final String binExpression = expressions.get(2);
final String hexExpression = expressions.get(1);
final String binExpression = expressions.get(2); //System.out.println("Dec expression: " + decExpression);
//System.out.println("Hex expression: " + hexExpression);
//System.out.println("Dec expression: " + decExpression); //System.out.println("Bin expression: " + binExpression);
//System.out.println("Hex expression: " + hexExpression);
//System.out.println("Bin expression: " + binExpression); final String decResult = Expression.valueOf(decExpression).numeric().toString();
//System.out.println("Dec result: " + decResult);
final String decResult = Expression.valueOf(decExpression).numeric().toString();
//System.out.println("Dec result: " + decResult); final String hexResult = Expression.valueOf(hexExpression).numeric().toString();
//System.out.println("Hex result: " + hexResult);
final String hexResult = Expression.valueOf(hexExpression).numeric().toString();
//System.out.println("Hex result: " + hexResult); final String binResult = Expression.valueOf(binExpression).numeric().toString();
//System.out.println("Bin result: " + binResult);
final String binResult = Expression.valueOf(binExpression).numeric().toString();
//System.out.println("Bin result: " + binResult); Assert.assertEquals("dec-hex: " + decExpression + " : " + hexExpression, decResult, hexResult);
Assert.assertEquals("dec-bin: " + decExpression + " : " + binExpression, decResult, binResult);
Assert.assertEquals("dec-hex: " + decExpression + " : " + hexExpression, decResult, hexResult); }
Assert.assertEquals("dec-bin: " + decExpression + " : " + binExpression, decResult, binResult); } finally {
} if (reader != null) {
} finally { reader.close();
if (reader != null) { }
reader.close(); }
} }
}
} public static void testExpression(@NotNull String[] line, @NotNull Converter<String, String> converter) throws ParseException, CalculatorEvalException, CalculatorParseException {
final String dec = line[0].toUpperCase();
public static void testExpression(@NotNull String[] line, @NotNull Converter<String, String> converter) throws ParseException, CalculatorEvalException, CalculatorParseException { final String hex = "0x:" + line[1].toUpperCase();
final String dec = line[0].toUpperCase(); final String bin = "0b:" + line[2].toUpperCase();
final String hex = "0x:" + line[1].toUpperCase();
final String bin = "0b:" + line[2].toUpperCase(); final String decExpression = converter.convert(dec);
final String decResult = CalculatorEngine.instance.evaluate(JsclOperation.numeric, decExpression).getResult();
final String decExpression = converter.convert(dec); final String hexExpression = converter.convert(hex);
final String decResult = CalculatorEngine.instance.evaluate(JsclOperation.numeric, decExpression).getStringResult(); final String hexResult = CalculatorEngine.instance.evaluate(JsclOperation.numeric, hexExpression).getResult();
final String hexExpression = converter.convert(hex); final String binExpression = converter.convert(bin);
final String hexResult = CalculatorEngine.instance.evaluate(JsclOperation.numeric, hexExpression).getStringResult(); final String binResult = CalculatorEngine.instance.evaluate(JsclOperation.numeric, binExpression).getResult();
final String binExpression = converter.convert(bin);
final String binResult = CalculatorEngine.instance.evaluate(JsclOperation.numeric, binExpression).getStringResult(); Assert.assertEquals("dec-hex: " + decExpression + " : " + hexExpression, decResult, hexResult);
Assert.assertEquals("dec-bin: " + decExpression + " : " + binExpression, decResult, binResult);
Assert.assertEquals("dec-hex: " + decExpression + " : " + hexExpression, decResult, hexResult); }
Assert.assertEquals("dec-bin: " + decExpression + " : " + binExpression, decResult, binResult);
} private static class DummyExpression implements Converter<String, String> {
private static class DummyExpression implements Converter<String, String> { @NotNull
@Override
@NotNull public String convert(@NotNull String s) {
@Override return s;
public String convert(@NotNull String s) { }
return s; }
}
} private static class Expression1 implements Converter<String, String> {
private static class Expression1 implements Converter<String, String> { @NotNull
@Override
@NotNull public String convert(@NotNull String s) {
@Override return s + "*" + s;
public String convert(@NotNull String s) { }
return s + "*" + s; }
}
} private static class Expression2 implements Converter<String, String> {
private static class Expression2 implements Converter<String, String> { @NotNull
@Override
@NotNull public String convert(@NotNull String s) {
@Override return s + "*" + s + " * sin(" + s + ") - 0b:1101";
public String convert(@NotNull String s) { }
return s + "*" + s + " * sin(" + s + ") - 0b:1101"; }
}
} private static class Expression3 implements Converter<String, String> {
private static class Expression3 implements Converter<String, String> { @NotNull
@Override
@NotNull public String convert(@NotNull String s) {
@Override return s + "*" + s + " * sin(" + s + ") - 0b:1101 + √(" + s + ") + exp ( " + s + ")";
public String convert(@NotNull String s) { }
return s + "*" + s + " * sin(" + s + ") - 0b:1101 + √(" + s + ") + exp ( " + s + ")"; }
} }
}
}

View File

@ -11,10 +11,6 @@ import jscl.NumeralBase;
import org.junit.Assert; import org.junit.Assert;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import org.solovyev.android.calculator.CalculatorParseException;
import org.solovyev.android.calculator.PreparedExpression;
import org.solovyev.android.calculator.ToJsclTextProcessor;
import org.solovyev.android.calculator.text.TextProcessor;
/** /**
* User: serso * User: serso

37
pom.xml
View File

@ -15,7 +15,6 @@
<module>calculatorpp</module> <module>calculatorpp</module>
<module>calculatorpp-service</module> <module>calculatorpp-service</module>
<module>calculatorpp-test</module> <module>calculatorpp-test</module>
<module>calculatorpp-core</module>
</modules> </modules>
<properties> <properties>
@ -72,18 +71,6 @@
<version>1.0.0</version> <version>1.0.0</version>
</dependency> </dependency>
<dependency>
<groupId>org.solovyev</groupId>
<artifactId>jscl</artifactId>
<version>0.0.2</version>
<exclusions>
<exclusion>
<artifactId>xercesImpl</artifactId>
<groupId>xerces</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency> <dependency>
<groupId>org.solovyev.android</groupId> <groupId>org.solovyev.android</groupId>
<artifactId>android-common-other</artifactId> <artifactId>android-common-other</artifactId>
@ -94,13 +81,7 @@
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
<version>4.8.2</version> <version>4.8.1</version>
</dependency>
<dependency>
<groupId>com.intellij</groupId>
<artifactId>annotations</artifactId>
<version>7.0.3</version>
</dependency> </dependency>
<dependency> <dependency>
@ -122,22 +103,6 @@
<version>11.0.2</version> <version>11.0.2</version>
</dependency> </dependency>
<dependency>
<groupId>org.simpleframework</groupId>
<artifactId>simple-xml</artifactId>
<version>2.6.1</version>
<exclusions>
<exclusion>
<artifactId>stax-api</artifactId>
<groupId>stax</groupId>
</exclusion>
<exclusion>
<artifactId>xpp3</artifactId>
<groupId>xpp3</groupId>
</exclusion>
</exclusions>
</dependency>
</dependencies> </dependencies>
</dependencyManagement> </dependencyManagement>