New architecture

This commit is contained in:
Sergey Solovyev
2012-09-22 19:24:27 +04:00
parent 3661774d9b
commit 233c685a49
68 changed files with 2787 additions and 2475 deletions

View File

@@ -0,0 +1,126 @@
package org.solovyev.android.calculator;
import android.app.Activity;
import android.content.SharedPreferences;
import jscl.NumeralBase;
import jscl.math.Generic;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.history.CalculatorHistoryState;
import org.solovyev.android.calculator.jscl.JsclOperation;
import org.solovyev.common.history.HistoryAction;
import java.util.List;
/**
* User: serso
* Date: 9/22/12
* Time: 5:42 PM
*/
public class AndroidCalculator implements Calculator {
@NotNull
private final Calculator calculator = new CalculatorImpl();
public void init(@NotNull final Activity activity, @NotNull SharedPreferences preferences) {
final AndroidCalculatorEditorView editorView = (AndroidCalculatorEditorView) activity.findViewById(R.id.calculatorEditor);
editorView.init(preferences);
preferences.registerOnSharedPreferenceChangeListener(editorView);
CalculatorLocatorImpl.getInstance().getEditor().setView(editorView);
final AndroidCalculatorDisplayView displayView = (AndroidCalculatorDisplayView) activity.findViewById(R.id.calculatorDisplay);
displayView.setOnClickListener(new CalculatorDisplayOnClickListener(activity));
CalculatorLocatorImpl.getInstance().getDisplay().setView(displayView);
}
/*
**********************************************************************
*
* DELETED TO CALCULATOR
*
**********************************************************************
*/
@Override
@NotNull
public CalculatorEventDataId evaluate(@NotNull JsclOperation operation, @NotNull String expression) {
return calculator.evaluate(operation, expression);
}
@Override
@NotNull
public CalculatorEventDataId evaluate(@NotNull JsclOperation operation, @NotNull String expression, @NotNull Long sequenceId) {
return calculator.evaluate(operation, expression, sequenceId);
}
@Override
@NotNull
public CalculatorEventDataId convert(@NotNull Generic generic, @NotNull NumeralBase to) {
return calculator.convert(generic, to);
}
@Override
@NotNull
public CalculatorEventDataId fireCalculatorEvent(@NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
return calculator.fireCalculatorEvent(calculatorEventType, data);
}
@Override
@NotNull
public CalculatorEventDataId fireCalculatorEvent(@NotNull CalculatorEventType calculatorEventType, @Nullable Object data, @NotNull Long sequenceId) {
return calculator.fireCalculatorEvent(calculatorEventType, data, sequenceId);
}
@Override
public void init() {
this.calculator.init();
}
@Override
public void addCalculatorEventListener(@NotNull CalculatorEventListener calculatorEventListener) {
calculator.addCalculatorEventListener(calculatorEventListener);
}
@Override
public void removeCalculatorEventListener(@NotNull CalculatorEventListener calculatorEventListener) {
calculator.removeCalculatorEventListener(calculatorEventListener);
}
@Override
public void fireCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
calculator.fireCalculatorEvent(calculatorEventData, calculatorEventType, data);
}
@Override
public void fireCalculatorEvents(@NotNull List<CalculatorEvent> calculatorEvents) {
calculator.fireCalculatorEvents(calculatorEvents);
}
@Override
public void doHistoryAction(@NotNull HistoryAction historyAction) {
calculator.doHistoryAction(historyAction);
}
@Override
public void setCurrentHistoryState(@NotNull CalculatorHistoryState editorHistoryState) {
calculator.setCurrentHistoryState(editorHistoryState);
}
@Override
@NotNull
public CalculatorHistoryState getCurrentHistoryState() {
return calculator.getCurrentHistoryState();
}
@Override
public void evaluate() {
calculator.evaluate();
}
@Override
public void simplify() {
calculator.simplify();
}
}

View File

@@ -12,7 +12,6 @@ import android.text.Html;
import android.util.AttributeSet;
import android.util.Log;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.model.CalculatorEngine;
import org.solovyev.android.calculator.text.TextProcessor;
import org.solovyev.android.calculator.view.TextHighlighter;
import org.solovyev.android.view.AutoResizeTextView;
@@ -33,7 +32,7 @@ public class AndroidCalculatorDisplayView extends AutoResizeTextView implements
*/
@NotNull
private final static TextProcessor<TextHighlighter.Result, String> textHighlighter = new TextHighlighter(Color.WHITE, false, CalculatorEngine.instance.getEngine());
private final static TextProcessor<TextHighlighter.Result, String> textHighlighter = new TextHighlighter(Color.WHITE, false, CalculatorLocatorImpl.getInstance().getEngine().getEngine());
/*
**********************************************************************

View File

@@ -14,7 +14,6 @@ import android.util.AttributeSet;
import android.view.ContextMenu;
import android.widget.EditText;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.model.CalculatorEngine;
import org.solovyev.android.calculator.text.TextProcessor;
import org.solovyev.android.calculator.view.TextHighlighter;
import org.solovyev.common.collections.CollectionsUtils;
@@ -32,7 +31,7 @@ public class AndroidCalculatorEditorView extends EditText implements SharedPrefe
private boolean highlightText = true;
@NotNull
private final static TextProcessor<TextHighlighter.Result, String> textHighlighter = new TextHighlighter(Color.WHITE, true, CalculatorEngine.instance.getEngine());
private final static TextProcessor<TextHighlighter.Result, String> textHighlighter = new TextHighlighter(Color.WHITE, true, CalculatorLocatorImpl.getInstance().getEngine().getEngine());
@NotNull
private volatile CalculatorEditorViewState viewState = CalculatorEditorViewStateImpl.newDefaultInstance();
@@ -165,7 +164,7 @@ public class AndroidCalculatorEditorView extends EditText implements SharedPrefe
synchronized (this) {
if (!viewStateChange) {
super.onSelectionChanged(selStart, selEnd);
CalculatorLocatorImpl.getInstance().getCalculatorEditor().setSelection(selStart);
CalculatorLocatorImpl.getInstance().getEditor().setSelection(selStart);
}
}
}

View File

@@ -34,9 +34,8 @@ import org.solovyev.android.AndroidUtils;
import org.solovyev.android.FontSizeAdjuster;
import org.solovyev.android.LocalBinder;
import org.solovyev.android.calculator.about.CalculatorReleaseNotesActivity;
import org.solovyev.android.calculator.history.AndroidCalculatorHistoryImpl;
import org.solovyev.android.calculator.history.CalculatorHistoryState;
import org.solovyev.android.calculator.model.CalculatorEngine;
import org.solovyev.android.calculator.model.AndroidCalculatorEngine;
import org.solovyev.android.calculator.view.AngleUnitsButton;
import org.solovyev.android.calculator.view.CalculatorAdditionalTitle;
import org.solovyev.android.calculator.view.NumeralBasesButton;
@@ -74,9 +73,6 @@ public class CalculatorActivity extends Activity implements FontSizeAdjuster, Sh
@NotNull
private final Announcer<DragPreferencesChangeListener> dpclRegister = new Announcer<DragPreferencesChangeListener>(DragPreferencesChangeListener.class);
@NotNull
private CalculatorModel calculatorModel;
private volatile boolean initialized;
@NotNull
@@ -138,8 +134,7 @@ public class CalculatorActivity extends Activity implements FontSizeAdjuster, Sh
vibrator = (Vibrator) this.getSystemService(VIBRATOR_SERVICE);
AndroidCalculatorHistoryImpl.instance.load(this, preferences);
calculatorModel = CalculatorModel.instance.init(this, preferences);
getCalculator().init(this, preferences);
dpclRegister.clear();
@@ -147,7 +142,7 @@ public class CalculatorActivity extends Activity implements FontSizeAdjuster, Sh
setOnDragListeners(dragPreferences, preferences);
final OnDragListener historyOnDragListener = new OnDragListenerVibrator(newOnDragListener(new HistoryDragProcessor<CalculatorHistoryState>(this.calculatorModel), dragPreferences), vibrator, preferences);
final OnDragListener historyOnDragListener = new OnDragListenerVibrator(newOnDragListener(new HistoryDragProcessor<CalculatorHistoryState>(getCalculator()), dragPreferences), vibrator, preferences);
((DragButton) findViewById(R.id.historyButton)).setOnDragListener(historyOnDragListener);
((DragButton) findViewById(R.id.subtractionButton)).setOnDragListener(new OnDragListenerVibrator(newOnDragListener(new SimpleOnDragListener.DragProcessor() {
@@ -162,13 +157,13 @@ public class CalculatorActivity extends Activity implements FontSizeAdjuster, Sh
}, dragPreferences), vibrator, preferences));
final OnDragListener toPositionOnDragListener = new OnDragListenerVibrator(new SimpleOnDragListener(new CursorDragProcessor(calculatorModel), dragPreferences), vibrator, preferences);
final OnDragListener toPositionOnDragListener = new OnDragListenerVibrator(new SimpleOnDragListener(new CursorDragProcessor(), dragPreferences), vibrator, preferences);
((DragButton) findViewById(R.id.rightButton)).setOnDragListener(toPositionOnDragListener);
((DragButton) findViewById(R.id.leftButton)).setOnDragListener(toPositionOnDragListener);
final DragButton equalsButton = (DragButton) findViewById(R.id.equalsButton);
if (equalsButton != null) {
equalsButton.setOnDragListener(new OnDragListenerVibrator(newOnDragListener(new EvalDragProcessor(calculatorModel), dragPreferences), vibrator, preferences));
equalsButton.setOnDragListener(new OnDragListenerVibrator(newOnDragListener(new EvalDragProcessor(), dragPreferences), vibrator, preferences));
}
final AngleUnitsButton angleUnitsButton = (AngleUnitsButton) findViewById(R.id.sixDigitButton);
@@ -192,7 +187,7 @@ public class CalculatorActivity extends Activity implements FontSizeAdjuster, Sh
}
CalculatorEngine.instance.softReset(this, preferences);
getEngine().softReset();
initMultiplicationButton();
@@ -227,6 +222,16 @@ public class CalculatorActivity extends Activity implements FontSizeAdjuster, Sh
preferences.registerOnSharedPreferenceChangeListener(this);
}
@NotNull
private AndroidCalculatorEngine getEngine() {
return ((AndroidCalculatorEngine) CalculatorLocatorImpl.getInstance().getEngine());
}
@NotNull
private AndroidCalculator getCalculator() {
return ((AndroidCalculator) CalculatorLocatorImpl.getInstance().getCalculator());
}
private void fixThemeParameters(boolean fixMagicFlames) {
if (theme.getThemeType() == CalculatorPreferences.Gui.ThemeType.metro) {
@@ -294,7 +299,7 @@ public class CalculatorActivity extends Activity implements FontSizeAdjuster, Sh
private class AngleUnitsChanger implements SimpleOnDragListener.DragProcessor {
private final DigitButtonDragProcessor processor = new DigitButtonDragProcessor(CalculatorLocatorImpl.getInstance().getCalculatorKeyboard());
private final DigitButtonDragProcessor processor = new DigitButtonDragProcessor(getKeyboard());
@Override
public boolean processDragEvent(@NotNull DragDirection dragDirection,
@@ -313,7 +318,7 @@ public class CalculatorActivity extends Activity implements FontSizeAdjuster, Sh
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(CalculatorActivity.this);
CalculatorEngine.Preferences.angleUnit.putPreference(preferences, angleUnits);
AndroidCalculatorEngine.Preferences.angleUnit.putPreference(preferences, angleUnits);
Toast.makeText(CalculatorActivity.this, CalculatorActivity.this.getString(R.string.c_angle_units_changed_to, angleUnits.name()), Toast.LENGTH_LONG).show();
@@ -348,7 +353,7 @@ public class CalculatorActivity extends Activity implements FontSizeAdjuster, Sh
final NumeralBase numeralBase = NumeralBase.valueOf(directionText);
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(CalculatorActivity.this);
CalculatorEngine.Preferences.numeralBase.putPreference(preferences, numeralBase);
AndroidCalculatorEngine.Preferences.numeralBase.putPreference(preferences, numeralBase);
Toast.makeText(CalculatorActivity.this, CalculatorActivity.this.getString(R.string.c_numeral_base_changed_to, numeralBase.name()), Toast.LENGTH_LONG).show();
@@ -374,7 +379,7 @@ public class CalculatorActivity extends Activity implements FontSizeAdjuster, Sh
boolean result = false;
if (dragDirection == DragDirection.up) {
CalculatorActivityLauncher.createVar(CalculatorActivity.this, CalculatorActivity.this.calculatorModel);
CalculatorActivityLauncher.createVar(CalculatorActivity.this, CalculatorLocatorImpl.getInstance().getDisplay());
result = true;
}
@@ -383,7 +388,7 @@ public class CalculatorActivity extends Activity implements FontSizeAdjuster, Sh
}
private synchronized void setOnDragListeners(@NotNull SimpleOnDragListener.Preferences dragPreferences, @NotNull SharedPreferences preferences) {
final OnDragListener onDragListener = new OnDragListenerVibrator(newOnDragListener(new DigitButtonDragProcessor(CalculatorLocatorImpl.getInstance().getCalculatorKeyboard()), dragPreferences), vibrator, preferences);
final OnDragListener onDragListener = new OnDragListenerVibrator(newOnDragListener(new DigitButtonDragProcessor(getKeyboard()), dragPreferences), vibrator, preferences);
final List<Integer> dragButtonIds = new ArrayList<Integer>();
final List<Integer> buttonIds = new ArrayList<Integer>();
@@ -527,7 +532,7 @@ public class CalculatorActivity extends Activity implements FontSizeAdjuster, Sh
@SuppressWarnings({"UnusedDeclaration"})
public void numericButtonClickHandler(@NotNull View v) {
this.calculatorModel.evaluate();
getCalculator().evaluate();
}
@SuppressWarnings({"UnusedDeclaration"})
@@ -537,7 +542,7 @@ public class CalculatorActivity extends Activity implements FontSizeAdjuster, Sh
@SuppressWarnings({"UnusedDeclaration"})
public void eraseButtonClickHandler(@NotNull View v) {
CalculatorLocatorImpl.getInstance().getCalculatorEditor().erase();
CalculatorLocatorImpl.getInstance().getEditor().erase();
}
@SuppressWarnings({"UnusedDeclaration"})
@@ -547,34 +552,39 @@ public class CalculatorActivity extends Activity implements FontSizeAdjuster, Sh
@SuppressWarnings({"UnusedDeclaration"})
public void moveLeftButtonClickHandler(@NotNull View v) {
calculatorModel.moveCursorLeft();
getKeyboard().moveCursorLeft();
}
@SuppressWarnings({"UnusedDeclaration"})
public void moveRightButtonClickHandler(@NotNull View v) {
calculatorModel.moveCursorRight();
getKeyboard().moveCursorRight();
}
@SuppressWarnings({"UnusedDeclaration"})
public void pasteButtonClickHandler(@NotNull View v) {
CalculatorLocatorImpl.getInstance().getCalculatorKeyboard().pasteButtonPressed();
getKeyboard().pasteButtonPressed();
}
@SuppressWarnings({"UnusedDeclaration"})
public void copyButtonClickHandler(@NotNull View v) {
calculatorModel.copyResult(this);
getKeyboard().copyButtonPressed();
}
@SuppressWarnings({"UnusedDeclaration"})
@NotNull
private static CalculatorKeyboard getKeyboard() {
return CalculatorLocatorImpl.getInstance().getKeyboard();
}
@SuppressWarnings({"UnusedDeclaration"})
public void clearButtonClickHandler(@NotNull View v) {
CalculatorLocatorImpl.getInstance().getCalculatorKeyboard().clearButtonPressed();
getKeyboard().clearButtonPressed();
}
@SuppressWarnings({"UnusedDeclaration"})
public void digitButtonClickHandler(@NotNull View v) {
Log.d(String.valueOf(v.getId()), "digitButtonClickHandler() for: " + v.getId() + ". Pressed: " + v.isPressed());
if (((ColorButton) v).isShowText()) {
CalculatorLocatorImpl.getInstance().getCalculatorKeyboard().digitButtonPressed(((ColorButton) v).getText().toString());
getKeyboard().digitButtonPressed(((ColorButton) v).getText().toString());
}
}
@@ -602,7 +612,7 @@ public class CalculatorActivity extends Activity implements FontSizeAdjuster, Sh
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (useBackAsPrev) {
calculatorModel.doHistoryAction(HistoryAction.undo);
getCalculator().doHistoryAction(HistoryAction.undo);
return true;
}
}
@@ -646,8 +656,7 @@ public class CalculatorActivity extends Activity implements FontSizeAdjuster, Sh
AndroidUtils.restartActivity(this);
}
calculatorModel = CalculatorModel.instance.init(this, preferences);
calculatorModel.evaluate();
getCalculator().evaluate();
}
@Override
@@ -665,22 +674,22 @@ public class CalculatorActivity extends Activity implements FontSizeAdjuster, Sh
dpclRegister.announce().onDragPreferencesChange(SimpleOnDragListener.getPreferences(preferences, this));
}
if (CalculatorEngine.Preferences.getPreferenceKeys().contains(key)) {
CalculatorEngine.instance.softReset(this, preferences);
if (AndroidCalculatorEngine.Preferences.getPreferenceKeys().contains(key)) {
CalculatorLocatorImpl.getInstance().getEngine().softReset();
// reevaluate in order to update values (in case of preferences changed from the main window, like numeral bases and angle units)
this.calculatorModel.evaluate();
this.getCalculator().evaluate();
}
if ( CalculatorPreferences.Gui.usePrevAsBack.getKey().equals(key) ) {
useBackAsPrev = CalculatorPreferences.Gui.usePrevAsBack.getPreference(preferences);
}
if (CalculatorEngine.Preferences.numeralBase.getKey().equals(key)) {
if (AndroidCalculatorEngine.Preferences.numeralBase.getKey().equals(key)) {
numeralBaseButtons.toggleNumericDigits(this, preferences);
}
if ( CalculatorEngine.Preferences.multiplicationSign.getKey().equals(key) ) {
if ( AndroidCalculatorEngine.Preferences.multiplicationSign.getKey().equals(key) ) {
initMultiplicationButton();
}
@@ -720,7 +729,7 @@ public class CalculatorActivity extends Activity implements FontSizeAdjuster, Sh
@NotNull
private AndroidCalculatorDisplayView getCalculatorDisplayView() {
return (AndroidCalculatorDisplayView) calculatorModel.getDisplay().getView();
return (AndroidCalculatorDisplayView) CalculatorLocatorImpl.getInstance().getDisplay().getView();
}
private void toggleOrientationChange(@Nullable SharedPreferences preferences) {
@@ -735,7 +744,7 @@ public class CalculatorActivity extends Activity implements FontSizeAdjuster, Sh
private void initMultiplicationButton() {
final View multiplicationButton = findViewById(R.id.multiplicationButton);
if ( multiplicationButton instanceof Button) {
((Button) multiplicationButton).setText(CalculatorEngine.instance.getMultiplicationSign());
((Button) multiplicationButton).setText(CalculatorLocatorImpl.getInstance().getEngine().getMultiplicationSign());
}
}
@@ -745,10 +754,10 @@ public class CalculatorActivity extends Activity implements FontSizeAdjuster, Sh
final boolean result;
if ( dragDirection == DragDirection.left ) {
CalculatorLocatorImpl.getInstance().getCalculatorKeyboard().roundBracketsButtonPressed();
getKeyboard().roundBracketsButtonPressed();
result = true;
} else {
result = new DigitButtonDragProcessor(CalculatorLocatorImpl.getInstance().getCalculatorKeyboard()).processDragEvent(dragDirection, dragButton, startPoint2d, motionEvent);
result = new DigitButtonDragProcessor(getKeyboard()).processDragEvent(dragDirection, dragButton, startPoint2d, motionEvent);
}
return result;

View File

@@ -60,8 +60,8 @@ public class CalculatorActivityLauncher {
context.startActivity(intent);
}
public static void createVar(@NotNull final Context context, @NotNull CalculatorModel calculatorModel) {
final CalculatorDisplayViewState viewState = calculatorModel.getDisplay().getViewState();
public static void createVar(@NotNull final Context context, @NotNull CalculatorDisplay calculatorDisplay) {
final CalculatorDisplayViewState viewState = calculatorDisplay.getViewState();
if (viewState.isValid() ) {
final String varValue = viewState.getText();
if (!StringUtils.isEmpty(varValue)) {

View File

@@ -5,7 +5,6 @@ import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
@@ -13,7 +12,8 @@ import android.widget.TextView;
import net.robotmedia.billing.BillingController;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.ads.AdsController;
import org.solovyev.android.calculator.model.CalculatorEngine;
import org.solovyev.android.calculator.history.AndroidCalculatorHistory;
import org.solovyev.android.calculator.model.AndroidCalculatorEngine;
/**
* User: serso
@@ -22,75 +22,78 @@ import org.solovyev.android.calculator.model.CalculatorEngine;
*/
public class CalculatorApplication extends android.app.Application {
private static final String paypalDonateUrl = "https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=se%2esolovyev%40gmail%2ecom&lc=RU&item_name=Android%20Calculator&currency_code=USD&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted";
private static final String paypalDonateUrl = "https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=se%2esolovyev%40gmail%2ecom&lc=RU&item_name=Android%20Calculator&currency_code=USD&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted";
public static final String AD_FREE_PRODUCT_ID = "ad_free";
public static final String AD_FREE_P_KEY = "org.solovyev.android.calculator_ad_free";
public static final String AD_FREE_PRODUCT_ID = "ad_free";
public static final String AD_FREE_P_KEY = "org.solovyev.android.calculator_ad_free";
public static final String ADMOB_USER_ID = "a14f02cf9c80cbc";
public static final String REMOTE_STACK_TRACE_URL = "http://calculatorpp.com/crash_reports/upload.php";
public static final String ADMOB_USER_ID = "a14f02cf9c80cbc";
public static final String REMOTE_STACK_TRACE_URL = "http://calculatorpp.com/crash_reports/upload.php";
@NotNull
private static CalculatorApplication instance;
@NotNull
private static CalculatorApplication instance;
public CalculatorApplication() {
instance = this;
}
public CalculatorApplication() {
instance = this;
}
@NotNull
public static CalculatorApplication getInstance() {
return instance;
}
@NotNull
public static CalculatorApplication getInstance() {
return instance;
}
@Override
public void onCreate() {
super.onCreate();
@Override
public void onCreate() {
super.onCreate();
CalculatorLocatorImpl.getInstance().setCalculatorEngine(CalculatorEngine.instance);
CalculatorLocatorImpl.getInstance().setCalculatorNotifier(new AndroidCalculatorNotifier(this));
CalculatorLocatorImpl.getInstance().setCalculatorClipboard(new AndroidCalculatorClipboard(this));
final AndroidCalculator calculator = new AndroidCalculator();
AdsController.getInstance().init(ADMOB_USER_ID, AD_FREE_PRODUCT_ID, new BillingController.IConfiguration() {
CalculatorLocatorImpl.getInstance().init(calculator,
new AndroidCalculatorEngine(this),
new AndroidCalculatorClipboard(this),
new AndroidCalculatorNotifier(this),
new AndroidCalculatorHistory(this, calculator));
@Override
public byte[] getObfuscationSalt() {
return new byte[]{81, -114, 32, -127, -32, -104, -40, -15, -47, 57, -13, -41, -33, 67, -114, 7, -11, 53, 126, 82};
}
CalculatorLocatorImpl.getInstance().getCalculator().init();
@Override
public String getPublicKey() {
return CalculatorSecurity.getPK();
}
});
AdsController.getInstance().init(ADMOB_USER_ID, AD_FREE_PRODUCT_ID, new BillingController.IConfiguration() {
CalculatorEngine.instance.init(this, PreferenceManager.getDefaultSharedPreferences(this));
@Override
public byte[] getObfuscationSalt() {
return new byte[]{81, -114, 32, -127, -32, -104, -40, -15, -47, 57, -13, -41, -33, 67, -114, 7, -11, 53, 126, 82};
}
}
@Override
public String getPublicKey() {
return CalculatorSecurity.getPK();
}
});
}
public static void showDonationDialog(@NotNull final Context context) {
final LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
final View view = layoutInflater.inflate(R.layout.donate, null);
public static void showDonationDialog(@NotNull final Context context) {
final LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
final View view = layoutInflater.inflate(R.layout.donate, null);
final TextView donate = (TextView) view.findViewById(R.id.donateText);
donate.setMovementMethod(LinkMovementMethod.getInstance());
final TextView donate = (TextView) view.findViewById(R.id.donateText);
donate.setMovementMethod(LinkMovementMethod.getInstance());
final AlertDialog.Builder builder = new AlertDialog.Builder(context)
.setCancelable(true)
.setNegativeButton(R.string.c_cancel, null)
.setPositiveButton(R.string.c_donate, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
final Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(paypalDonateUrl));
context.startActivity(i);
}
})
.setView(view);
final AlertDialog.Builder builder = new AlertDialog.Builder(context)
.setCancelable(true)
.setNegativeButton(R.string.c_cancel, null)
.setPositiveButton(R.string.c_donate, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
final Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(paypalDonateUrl));
context.startActivity(i);
}
})
.setView(view);
builder.create().show();
}
builder.create().show();
}
public static void registerOnRemoteStackTrace() {
//Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler(null, REMOTE_STACK_TRACE_URL));
}
public static void registerOnRemoteStackTrace() {
//Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler(null, REMOTE_STACK_TRACE_URL));
}
}

View File

@@ -1,141 +1,140 @@
package org.solovyev.android.calculator;
import android.content.Context;
import jscl.math.Generic;
import jscl.math.function.Constant;
import jscl.math.function.IConstant;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.jscl.JsclOperation;
import org.solovyev.android.calculator.model.CalculatorEngine;
import org.solovyev.android.calculator.view.NumeralBaseConverterDialog;
import org.solovyev.android.menu.LabeledMenuItem;
import org.solovyev.common.collections.CollectionsUtils;
import java.util.HashSet;
import java.util.Set;
/**
* User: Solovyev_S
* Date: 21.09.12
* Time: 10:55
*/
public enum CalculatorDisplayMenuItem implements LabeledMenuItem<CalculatorDisplayViewState> {
copy(R.string.c_copy) {
@Override
public void onClick(@NotNull CalculatorDisplayViewState data, @NotNull Context context) {
CalculatorModel.copyResult(context, data);
}
},
convert_to_bin(R.string.convert_to_bin) {
@Override
public void onClick(@NotNull CalculatorDisplayViewState data, @NotNull Context context) {
ConversionMenuItem.convert_to_bin.onClick(data, context);
}
@Override
protected boolean isItemVisibleFor(@NotNull Generic generic, @NotNull JsclOperation operation) {
return ConversionMenuItem.convert_to_bin.isItemVisibleFor(generic, operation);
}
},
convert_to_dec(R.string.convert_to_dec) {
@Override
public void onClick(@NotNull CalculatorDisplayViewState data, @NotNull Context context) {
ConversionMenuItem.convert_to_dec.onClick(data, context);
}
@Override
protected boolean isItemVisibleFor(@NotNull Generic generic, @NotNull JsclOperation operation) {
return ConversionMenuItem.convert_to_dec.isItemVisibleFor(generic, operation);
}
},
convert_to_hex(R.string.convert_to_hex) {
@Override
public void onClick(@NotNull CalculatorDisplayViewState data, @NotNull Context context) {
ConversionMenuItem.convert_to_hex.onClick(data, context);
}
@Override
protected boolean isItemVisibleFor(@NotNull Generic generic, @NotNull JsclOperation operation) {
return ConversionMenuItem.convert_to_hex.isItemVisibleFor(generic, operation);
}
},
convert(R.string.c_convert) {
@Override
public void onClick(@NotNull CalculatorDisplayViewState data, @NotNull Context context) {
final Generic result = data.getResult();
if (result != null) {
new NumeralBaseConverterDialog(result.toString()).show(context);
}
}
@Override
protected boolean isItemVisibleFor(@NotNull Generic generic, @NotNull JsclOperation operation) {
return operation == JsclOperation.numeric && generic.getConstants().isEmpty();
}
},
plot(R.string.c_plot) {
@Override
public void onClick(@NotNull CalculatorDisplayViewState data, @NotNull Context context) {
final Generic generic = data.getResult();
assert generic != null;
final Constant constant = CollectionsUtils.getFirstCollectionElement(getNotSystemConstants(generic));
assert constant != null;
CalculatorActivityLauncher.plotGraph(context, generic, constant);
}
@Override
protected boolean isItemVisibleFor(@NotNull Generic generic, @NotNull JsclOperation operation) {
boolean result = false;
if (operation == JsclOperation.simplify) {
if (getNotSystemConstants(generic).size() == 1) {
result = true;
}
}
return result;
}
@NotNull
private Set<Constant> getNotSystemConstants(@NotNull Generic generic) {
final Set<Constant> notSystemConstants = new HashSet<Constant>();
for (Constant constant : generic.getConstants()) {
IConstant var = CalculatorEngine.instance.getVarsRegistry().get(constant.getName());
if (var != null && !var.isSystem() && !var.isDefined()) {
notSystemConstants.add(constant);
}
}
return notSystemConstants;
}
};
private final int captionId;
CalculatorDisplayMenuItem(int captionId) {
this.captionId = captionId;
}
public final boolean isItemVisible(@NotNull CalculatorDisplayViewState displayViewState) {
//noinspection ConstantConditions
return displayViewState.isValid() && displayViewState.getResult() != null && isItemVisibleFor(displayViewState.getResult(), displayViewState.getOperation());
}
protected boolean isItemVisibleFor(@NotNull Generic generic, @NotNull JsclOperation operation) {
return true;
}
@NotNull
@Override
public String getCaption(@NotNull Context context) {
return context.getString(captionId);
}
}
package org.solovyev.android.calculator;
import android.content.Context;
import jscl.math.Generic;
import jscl.math.function.Constant;
import jscl.math.function.IConstant;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.jscl.JsclOperation;
import org.solovyev.android.calculator.view.NumeralBaseConverterDialog;
import org.solovyev.android.menu.LabeledMenuItem;
import org.solovyev.common.collections.CollectionsUtils;
import java.util.HashSet;
import java.util.Set;
/**
* User: Solovyev_S
* Date: 21.09.12
* Time: 10:55
*/
public enum CalculatorDisplayMenuItem implements LabeledMenuItem<CalculatorDisplayViewState> {
copy(R.string.c_copy) {
@Override
public void onClick(@NotNull CalculatorDisplayViewState data, @NotNull Context context) {
CalculatorLocatorImpl.getInstance().getKeyboard().copyButtonPressed();
}
},
convert_to_bin(R.string.convert_to_bin) {
@Override
public void onClick(@NotNull CalculatorDisplayViewState data, @NotNull Context context) {
ConversionMenuItem.convert_to_bin.onClick(data, context);
}
@Override
protected boolean isItemVisibleFor(@NotNull Generic generic, @NotNull JsclOperation operation) {
return ConversionMenuItem.convert_to_bin.isItemVisibleFor(generic, operation);
}
},
convert_to_dec(R.string.convert_to_dec) {
@Override
public void onClick(@NotNull CalculatorDisplayViewState data, @NotNull Context context) {
ConversionMenuItem.convert_to_dec.onClick(data, context);
}
@Override
protected boolean isItemVisibleFor(@NotNull Generic generic, @NotNull JsclOperation operation) {
return ConversionMenuItem.convert_to_dec.isItemVisibleFor(generic, operation);
}
},
convert_to_hex(R.string.convert_to_hex) {
@Override
public void onClick(@NotNull CalculatorDisplayViewState data, @NotNull Context context) {
ConversionMenuItem.convert_to_hex.onClick(data, context);
}
@Override
protected boolean isItemVisibleFor(@NotNull Generic generic, @NotNull JsclOperation operation) {
return ConversionMenuItem.convert_to_hex.isItemVisibleFor(generic, operation);
}
},
convert(R.string.c_convert) {
@Override
public void onClick(@NotNull CalculatorDisplayViewState data, @NotNull Context context) {
final Generic result = data.getResult();
if (result != null) {
new NumeralBaseConverterDialog(result.toString()).show(context);
}
}
@Override
protected boolean isItemVisibleFor(@NotNull Generic generic, @NotNull JsclOperation operation) {
return operation == JsclOperation.numeric && generic.getConstants().isEmpty();
}
},
plot(R.string.c_plot) {
@Override
public void onClick(@NotNull CalculatorDisplayViewState data, @NotNull Context context) {
final Generic generic = data.getResult();
assert generic != null;
final Constant constant = CollectionsUtils.getFirstCollectionElement(getNotSystemConstants(generic));
assert constant != null;
CalculatorActivityLauncher.plotGraph(context, generic, constant);
}
@Override
protected boolean isItemVisibleFor(@NotNull Generic generic, @NotNull JsclOperation operation) {
boolean result = false;
if (operation == JsclOperation.simplify) {
if (getNotSystemConstants(generic).size() == 1) {
result = true;
}
}
return result;
}
@NotNull
private Set<Constant> getNotSystemConstants(@NotNull Generic generic) {
final Set<Constant> notSystemConstants = new HashSet<Constant>();
for (Constant constant : generic.getConstants()) {
IConstant var = CalculatorLocatorImpl.getInstance().getEngine().getVarsRegistry().get(constant.getName());
if (var != null && !var.isSystem() && !var.isDefined()) {
notSystemConstants.add(constant);
}
}
return notSystemConstants;
}
};
private final int captionId;
CalculatorDisplayMenuItem(int captionId) {
this.captionId = captionId;
}
public final boolean isItemVisible(@NotNull CalculatorDisplayViewState displayViewState) {
//noinspection ConstantConditions
return displayViewState.isValid() && displayViewState.getResult() != null && isItemVisibleFor(displayViewState.getResult(), displayViewState.getOperation());
}
protected boolean isItemVisibleFor(@NotNull Generic generic, @NotNull JsclOperation operation) {
return true;
}
@NotNull
@Override
public String getCaption(@NotNull Context context) {
return context.getString(captionId);
}
}

View File

@@ -1,53 +1,53 @@
package org.solovyev.android.calculator;
import android.app.Activity;
import android.view.View;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.menu.AMenuBuilder;
import org.solovyev.android.menu.MenuImpl;
import java.util.ArrayList;
import java.util.List;
/**
* User: Solovyev_S
* Date: 21.09.12
* Time: 10:58
*/
public class CalculatorDisplayOnClickListener implements View.OnClickListener {
@NotNull
private final Activity activity;
public CalculatorDisplayOnClickListener(@NotNull Activity activity) {
this.activity = activity;
}
@Override
public void onClick(View v) {
if (v instanceof CalculatorDisplayView) {
final CalculatorDisplay cd = CalculatorLocatorImpl.getInstance().getCalculatorDisplay();
final CalculatorDisplayViewState displayViewState = cd.getViewState();
if (displayViewState.isValid()) {
final List<CalculatorDisplayMenuItem> filteredMenuItems = new ArrayList<CalculatorDisplayMenuItem>(CalculatorDisplayMenuItem.values().length);
for (CalculatorDisplayMenuItem menuItem : CalculatorDisplayMenuItem.values()) {
if (menuItem.isItemVisible(displayViewState)) {
filteredMenuItems.add(menuItem);
}
}
if (!filteredMenuItems.isEmpty()) {
AMenuBuilder.newInstance(activity, MenuImpl.newInstance(filteredMenuItems)).create(displayViewState).show();
}
} else {
final String errorMessage = displayViewState.getErrorMessage();
if (errorMessage != null) {
CalculatorModel.showEvaluationError(activity, errorMessage);
}
}
}
}
}
package org.solovyev.android.calculator;
import android.app.Activity;
import android.view.View;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.menu.AMenuBuilder;
import org.solovyev.android.menu.MenuImpl;
import java.util.ArrayList;
import java.util.List;
/**
* User: Solovyev_S
* Date: 21.09.12
* Time: 10:58
*/
public class CalculatorDisplayOnClickListener implements View.OnClickListener {
@NotNull
private final Activity activity;
public CalculatorDisplayOnClickListener(@NotNull Activity activity) {
this.activity = activity;
}
@Override
public void onClick(View v) {
if (v instanceof CalculatorDisplayView) {
final CalculatorDisplay cd = CalculatorLocatorImpl.getInstance().getDisplay();
final CalculatorDisplayViewState displayViewState = cd.getViewState();
if (displayViewState.isValid()) {
final List<CalculatorDisplayMenuItem> filteredMenuItems = new ArrayList<CalculatorDisplayMenuItem>(CalculatorDisplayMenuItem.values().length);
for (CalculatorDisplayMenuItem menuItem : CalculatorDisplayMenuItem.values()) {
if (menuItem.isItemVisible(displayViewState)) {
filteredMenuItems.add(menuItem);
}
}
if (!filteredMenuItems.isEmpty()) {
AMenuBuilder.newInstance(activity, MenuImpl.newInstance(filteredMenuItems)).create(displayViewState).show();
}
} else {
final String errorMessage = displayViewState.getErrorMessage();
if (errorMessage != null) {
CalculatorModel.showEvaluationError(activity, errorMessage);
}
}
}
}
}

View File

@@ -7,32 +7,24 @@ package org.solovyev.android.calculator;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.CursorControl;
import org.solovyev.android.calculator.history.AndroidCalculatorHistoryImpl;
import org.solovyev.android.calculator.history.CalculatorHistoryState;
import org.solovyev.android.calculator.jscl.JsclOperation;
import org.solovyev.android.history.HistoryControl;
import org.solovyev.common.history.HistoryAction;
import org.solovyev.common.gui.CursorControl;
/**
* User: serso
* Date: 9/12/11
* Time: 11:15 PM
*/
public enum CalculatorModel implements HistoryControl<CalculatorHistoryState>, CalculatorEngineControl, CursorControl {
public enum CalculatorModel implements CalculatorEngineControl, CursorControl {
instance;
// millis to wait before evaluation after user edit action
public static final int EVAL_DELAY_MILLIS = 0;
@NotNull
private final CalculatorEditor editor;
@@ -40,11 +32,11 @@ public enum CalculatorModel implements HistoryControl<CalculatorHistoryState>, C
private final CalculatorDisplay display;
private CalculatorModel() {
display = CalculatorLocatorImpl.getInstance().getCalculatorDisplay();
editor = CalculatorLocatorImpl.getInstance().getCalculatorEditor();
display = CalculatorLocatorImpl.getInstance().getDisplay();
editor = CalculatorLocatorImpl.getInstance().getEditor();
}
public CalculatorModel init(@NotNull final Activity activity, @NotNull SharedPreferences preferences) {
public CalculatorModel attachViews(@NotNull final Activity activity, @NotNull SharedPreferences preferences) {
Log.d(this.getClass().getName(), "CalculatorModel initialization with activity: " + activity);
final AndroidCalculatorEditorView editorView = (AndroidCalculatorEditorView) activity.findViewById(R.id.calculatorEditor);
@@ -72,19 +64,6 @@ public enum CalculatorModel implements HistoryControl<CalculatorHistoryState>, C
builder.create().show();
}
public void copyResult(@NotNull Context context) {
copyResult(context, display.getViewState());
}
public static void copyResult(@NotNull Context context,
@NotNull final CalculatorDisplayViewState viewState) {
CalculatorLocatorImpl.getInstance().getCalculatorKeyboard().copyButtonPressed();
}
private void saveHistoryState() {
AndroidCalculatorHistoryImpl.instance.addState(getCurrentHistoryState());
}
@Override
public void setCursorOnStart() {
this.editor.setCursorOnStart();
@@ -115,34 +94,6 @@ public enum CalculatorModel implements HistoryControl<CalculatorHistoryState>, C
CalculatorLocatorImpl.getInstance().getCalculator().evaluate(JsclOperation.simplify, this.editor.getViewState().getText());
}
@Override
public void doHistoryAction(@NotNull HistoryAction historyAction) {
synchronized (AndroidCalculatorHistoryImpl.instance) {
if (AndroidCalculatorHistoryImpl.instance.isActionAvailable(historyAction)) {
final CalculatorHistoryState newState = AndroidCalculatorHistoryImpl.instance.doAction(historyAction, getCurrentHistoryState());
if (newState != null) {
setCurrentHistoryState(newState);
}
}
}
}
@Override
public void setCurrentHistoryState(@NotNull CalculatorHistoryState editorHistoryState) {
synchronized (AndroidCalculatorHistoryImpl.instance) {
Log.d(this.getClass().getName(), "Saved history found: " + editorHistoryState);
editorHistoryState.setValuesFromHistory(this.editor, this.display);
}
}
@Override
@NotNull
public CalculatorHistoryState getCurrentHistoryState() {
synchronized (AndroidCalculatorHistoryImpl.instance) {
return CalculatorHistoryState.newInstance(this.editor, display);
}
}
@NotNull
public CalculatorDisplay getDisplay() {

View File

@@ -4,7 +4,7 @@ import android.content.SharedPreferences;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.AndroidUtils;
import org.solovyev.android.calculator.math.MathType;
import org.solovyev.android.calculator.model.CalculatorEngine;
import org.solovyev.android.calculator.model.AndroidCalculatorEngine;
import org.solovyev.android.prefs.BooleanPreference;
import org.solovyev.android.prefs.IntegerPreference;
import org.solovyev.android.prefs.Preference;
@@ -93,7 +93,7 @@ public final class CalculatorPreferences {
}
static void setDefaultValues(@NotNull SharedPreferences preferences) {
if (!CalculatorEngine.Preferences.groupingSeparator.isSet(preferences)) {
if (!AndroidCalculatorEngine.Preferences.groupingSeparator.isSet(preferences)) {
final Locale locale = Locale.getDefault();
if (locale != null) {
final DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols(locale);
@@ -105,22 +105,22 @@ public final class CalculatorPreferences {
groupingSeparator = " ";
}
CalculatorEngine.Preferences.groupingSeparator.putPreference(preferences, groupingSeparator);
AndroidCalculatorEngine.Preferences.groupingSeparator.putPreference(preferences, groupingSeparator);
}
}
if (!CalculatorEngine.Preferences.angleUnit.isSet(preferences)) {
CalculatorEngine.Preferences.angleUnit.putDefault(preferences);
if (!AndroidCalculatorEngine.Preferences.angleUnit.isSet(preferences)) {
AndroidCalculatorEngine.Preferences.angleUnit.putDefault(preferences);
}
if (!CalculatorEngine.Preferences.numeralBase.isSet(preferences)) {
CalculatorEngine.Preferences.numeralBase.putDefault(preferences);
if (!AndroidCalculatorEngine.Preferences.numeralBase.isSet(preferences)) {
AndroidCalculatorEngine.Preferences.numeralBase.putDefault(preferences);
}
if (!CalculatorEngine.Preferences.multiplicationSign.isSet(preferences)) {
if (!AndroidCalculatorEngine.Preferences.multiplicationSign.isSet(preferences)) {
if ( AndroidUtils.isPhoneModel(AndroidUtils.PhoneModel.samsung_galaxy_s) || AndroidUtils.isPhoneModel(AndroidUtils.PhoneModel.samsung_galaxy_s_2) ) {
// workaround ofr samsung galaxy s phones
CalculatorEngine.Preferences.multiplicationSign.putPreference(preferences, "*");
AndroidCalculatorEngine.Preferences.multiplicationSign.putPreference(preferences, "*");
}
}
}

View File

@@ -23,7 +23,7 @@ import net.robotmedia.billing.model.Transaction;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.AndroidUtils;
import org.solovyev.android.ads.AdsController;
import org.solovyev.android.calculator.model.CalculatorEngine;
import org.solovyev.android.calculator.model.AndroidCalculatorEngine;
import org.solovyev.android.view.VibratorContainer;
/**
@@ -51,7 +51,7 @@ public class CalculatorPreferencesActivity extends PreferenceActivity implements
final SharedPreferences preferences = getPreferenceManager().getSharedPreferences();
preferences.registerOnSharedPreferenceChangeListener(this);
onSharedPreferenceChanged(preferences, CalculatorEngine.Preferences.roundResult.getKey());
onSharedPreferenceChanged(preferences, AndroidCalculatorEngine.Preferences.roundResult.getKey());
onSharedPreferenceChanged(preferences, VibratorContainer.Preferences.hapticFeedbackEnabled.getKey());
final Preference clearBillingInfoPreference = findPreference(CLEAR_BILLING_INFO);
@@ -128,8 +128,8 @@ public class CalculatorPreferencesActivity extends PreferenceActivity implements
@Override
public void onSharedPreferenceChanged(SharedPreferences preferences, String key) {
if (CalculatorEngine.Preferences.roundResult.getKey().equals(key)) {
findPreference(CalculatorEngine.Preferences.precision.getKey()).setEnabled(preferences.getBoolean(key, CalculatorEngine.Preferences.roundResult.getDefaultValue()));
if (AndroidCalculatorEngine.Preferences.roundResult.getKey().equals(key)) {
findPreference(AndroidCalculatorEngine.Preferences.precision.getKey()).setEnabled(preferences.getBoolean(key, AndroidCalculatorEngine.Preferences.roundResult.getDefaultValue()));
} else if (VibratorContainer.Preferences.hapticFeedbackEnabled.getKey().equals(key)) {
findPreference(VibratorContainer.Preferences.hapticFeedbackDuration.getKey()).setEnabled(VibratorContainer.Preferences.hapticFeedbackEnabled.getPreference(preferences));
}

View File

@@ -5,7 +5,6 @@ import jscl.NumeralBase;
import jscl.math.Generic;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.jscl.JsclOperation;
import org.solovyev.android.calculator.model.CalculatorEngine;
import org.solovyev.android.menu.AMenuItem;
/**
@@ -43,7 +42,7 @@ enum ConversionMenuItem implements AMenuItem<CalculatorDisplayViewState> {
@Override
public void onClick(@NotNull CalculatorDisplayViewState data, @NotNull Context context) {
final NumeralBase fromNumeralBase = CalculatorEngine.instance.getEngine().getNumeralBase();
final NumeralBase fromNumeralBase = CalculatorLocatorImpl.getInstance().getEngine().getEngine().getNumeralBase();
final Generic lastResult = data.getResult();

View File

@@ -7,11 +7,10 @@ package org.solovyev.android.calculator;
import android.view.MotionEvent;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.CursorControl;
import org.solovyev.android.view.drag.DragDirection;
import org.solovyev.android.view.drag.SimpleOnDragListener;
import org.solovyev.android.view.drag.DirectionDragButton;
import org.solovyev.android.view.drag.DragButton;
import org.solovyev.android.view.drag.DragDirection;
import org.solovyev.android.view.drag.SimpleOnDragListener;
import org.solovyev.common.math.Point2d;
/**
@@ -21,11 +20,7 @@ import org.solovyev.common.math.Point2d;
*/
public class CursorDragProcessor implements SimpleOnDragListener.DragProcessor{
@NotNull
private final CursorControl cursorControl;
public CursorDragProcessor(@NotNull CursorControl cursorControl) {
this.cursorControl = cursorControl;
public CursorDragProcessor() {
}
@Override
@@ -35,10 +30,10 @@ public class CursorDragProcessor implements SimpleOnDragListener.DragProcessor{
if (dragButton instanceof DirectionDragButton) {
String text = ((DirectionDragButton) dragButton).getText(dragDirection);
if ("◀◀".equals(text)) {
cursorControl.setCursorOnStart();
CalculatorLocatorImpl.getInstance().getEditor().setCursorOnStart();
result = true;
} else if ("▶▶".equals(text)) {
cursorControl.setCursorOnEnd();
CalculatorLocatorImpl.getInstance().getEditor().setCursorOnEnd();
result = true;
}
}

View File

@@ -20,11 +20,8 @@ import org.solovyev.common.math.Point2d;
* Time: 9:52 PM
*/
public class EvalDragProcessor implements SimpleOnDragListener.DragProcessor {
@NotNull
private final CalculatorEngineControl calculatorControl;
public EvalDragProcessor(@NotNull CalculatorEngineControl calculatorControl) {
this.calculatorControl = calculatorControl;
public EvalDragProcessor() {
}
@Override
@@ -34,7 +31,7 @@ public class EvalDragProcessor implements SimpleOnDragListener.DragProcessor {
if (dragButton instanceof DirectionDragButton) {
String text = ((DirectionDragButton) dragButton).getText(dragDirection);
if ("".equals(text)) {
calculatorControl.simplify();
CalculatorLocatorImpl.getInstance().getCalculator().simplify();
result = true;
}
}

View File

@@ -4,7 +4,7 @@ import android.app.Activity;
import android.content.SharedPreferences;
import jscl.NumeralBase;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.model.CalculatorEngine;
import org.solovyev.android.calculator.model.AndroidCalculatorEngine;
/**
* User: serso
@@ -25,7 +25,7 @@ public class NumeralBaseButtons {
public synchronized void toggleNumericDigits(@NotNull Activity activity, @NotNull SharedPreferences preferences) {
if (CalculatorPreferences.Gui.hideNumeralBaseDigits.getPreference(preferences)) {
final NumeralBase nb = CalculatorEngine.Preferences.numeralBase.getPreference(preferences);
final NumeralBase nb = AndroidCalculatorEngine.Preferences.numeralBase.getPreference(preferences);
this.toggleNumericDigits(activity, nb);
} else {
// set HEX to show all digits

View File

@@ -156,7 +156,7 @@ public abstract class AbstractHistoryActivity extends ListActivity {
boolean result = false;
try {
historyState.setSaved(true);
if ( CollectionsUtils.contains(historyState, AndroidCalculatorHistoryImpl.instance.getSavedHistory(), new Equalizer<CalculatorHistoryState>() {
if ( CollectionsUtils.contains(historyState, CalculatorLocatorImpl.getInstance().getHistory().getSavedHistory(), new Equalizer<CalculatorHistoryState>() {
@Override
public boolean equals(@Nullable CalculatorHistoryState first, @Nullable CalculatorHistoryState second) {
return first != null && second != null &&
@@ -175,7 +175,7 @@ public abstract class AbstractHistoryActivity extends ListActivity {
public static void useHistoryItem(@NotNull final CalculatorHistoryState historyState, @NotNull AbstractHistoryActivity activity) {
final EditorHistoryState editorState = historyState.getEditorState();
CalculatorLocatorImpl.getInstance().getCalculatorEditor().setText(StringUtils.getNotEmpty(editorState.getText(), ""), editorState.getCursorPosition());
CalculatorLocatorImpl.getInstance().getEditor().setText(StringUtils.getNotEmpty(editorState.getText(), ""), editorState.getCursorPosition());
activity.finish();
}

View File

@@ -1,18 +1,149 @@
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);
}
/*
* 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.app.Application;
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.*;
import org.solovyev.common.history.HistoryAction;
import java.util.List;
/**
* User: serso
* Date: 10/9/11
* Time: 6:35 PM
*/
public class AndroidCalculatorHistory implements CalculatorHistory {
@NotNull
private final CalculatorHistoryImpl calculatorHistory;
@NotNull
private final Context context;
public AndroidCalculatorHistory(@NotNull Application application, @NotNull Calculator calculator) {
this.context = application;
calculatorHistory = new CalculatorHistoryImpl(calculator);
}
@Override
public void load() {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
if (preferences != null) {
final String value = preferences.getString(context.getString(R.string.p_calc_history), null);
if (value != null) {
calculatorHistory.fromXml(value);
}
}
}
public void save() {
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() {
calculatorHistory.clearSavedHistory();
save();
}
public void removeSavedHistory(@NotNull CalculatorHistoryState historyState) {
historyState.setSaved(false);
calculatorHistory.removeSavedHistory(historyState);
save();
}
@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 onCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
calculatorHistory.onCalculatorEvent(calculatorEventData, calculatorEventType, data);
}
}

View File

@@ -1,154 +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.CalculatorEventData;
import org.solovyev.android.calculator.CalculatorEventType;
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);
if (value != 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);
}
@Override
public void onCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
calculatorHistory.onCalculatorEvent(calculatorEventData, calculatorEventType, data);
}
}

View File

@@ -1,37 +1,38 @@
/*
* 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 org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.R;
import java.util.ArrayList;
import java.util.List;
/**
* User: serso
* Date: 12/18/11
* Time: 7:39 PM
*/
public class HistoryActivityTab extends AbstractHistoryActivity {
@Override
protected int getLayoutId() {
return R.layout.history;
}
@NotNull
@Override
protected List<CalculatorHistoryState> getHistoryItems() {
return new ArrayList<CalculatorHistoryState>(AndroidCalculatorHistoryImpl.instance.getStates());
}
@Override
protected void clearHistory() {
AndroidCalculatorHistoryImpl.instance.clear();
getAdapter().clear();
}
}
/*
* 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 org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.CalculatorLocatorImpl;
import org.solovyev.android.calculator.R;
import java.util.ArrayList;
import java.util.List;
/**
* User: serso
* Date: 12/18/11
* Time: 7:39 PM
*/
public class HistoryActivityTab extends AbstractHistoryActivity {
@Override
protected int getLayoutId() {
return R.layout.history;
}
@NotNull
@Override
protected List<CalculatorHistoryState> getHistoryItems() {
return new ArrayList<CalculatorHistoryState>(CalculatorLocatorImpl.getInstance().getHistory().getStates());
}
@Override
protected void clearHistory() {
CalculatorLocatorImpl.getInstance().getHistory().clear();
getAdapter().clear();
}
}

View File

@@ -1,154 +1,155 @@
/*
* 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.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.ClipboardManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.R;
import org.solovyev.android.menu.LabeledMenuItem;
import org.solovyev.common.text.StringUtils;
/**
* User: serso
* Date: 12/18/11
* Time: 3:09 PM
*/
public enum HistoryItemMenuItem implements LabeledMenuItem<HistoryItemMenuData> {
use(R.string.c_use) {
@Override
public void onClick(@NotNull HistoryItemMenuData data, @NotNull Context context) {
if (context instanceof AbstractHistoryActivity) {
AbstractHistoryActivity.useHistoryItem(data.getHistoryState(), (AbstractHistoryActivity) context);
} else {
Log.e(HistoryItemMenuItem.class.getName(), AbstractHistoryActivity.class + " must be passed as context!");
}
}
},
copy_expression(R.string.c_copy_expression) {
@Override
public void onClick(@NotNull HistoryItemMenuData data, @NotNull Context context) {
final CalculatorHistoryState calculatorHistoryState = data.getHistoryState();
final String text = calculatorHistoryState.getEditorState().getText();
if (!StringUtils.isEmpty(text)) {
final ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Activity.CLIPBOARD_SERVICE);
clipboard.setText(text);
Toast.makeText(context, context.getText(R.string.c_expression_copied), Toast.LENGTH_SHORT).show();
}
}
},
copy_result(R.string.c_copy_result) {
@Override
public void onClick(@NotNull HistoryItemMenuData data, @NotNull Context context) {
final CalculatorHistoryState calculatorHistoryState = data.getHistoryState();
final String text = calculatorHistoryState.getDisplayState().getEditorState().getText();
if (!StringUtils.isEmpty(text)) {
final ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Activity.CLIPBOARD_SERVICE);
clipboard.setText(text);
Toast.makeText(context, context.getText(R.string.c_result_copied), Toast.LENGTH_SHORT).show();
}
}
},
save(R.string.c_save) {
@Override
public void onClick(@NotNull final HistoryItemMenuData data, @NotNull final Context context) {
final CalculatorHistoryState historyState = data.getHistoryState();
if (!historyState.isSaved()) {
createEditHistoryDialog(data, context, true);
} else {
Toast.makeText(context, context.getText(R.string.c_history_already_saved), Toast.LENGTH_LONG).show();
}
}
},
edit(R.string.c_edit) {
@Override
public void onClick(@NotNull final HistoryItemMenuData data, @NotNull final Context context) {
final CalculatorHistoryState historyState = data.getHistoryState();
if (historyState.isSaved()) {
createEditHistoryDialog(data, context, false);
} else {
Toast.makeText(context, context.getText(R.string.c_history_must_be_saved), Toast.LENGTH_LONG).show();
}
}
},
remove(R.string.c_remove) {
@Override
public void onClick(@NotNull HistoryItemMenuData data, @NotNull Context context) {
final CalculatorHistoryState historyState = data.getHistoryState();
if (historyState.isSaved()) {
data.getAdapter().remove(historyState);
AndroidCalculatorHistoryImpl.instance.removeSavedHistory(historyState, context);
Toast.makeText(context, context.getText(R.string.c_history_was_removed), Toast.LENGTH_LONG).show();
data.getAdapter().notifyDataSetChanged();
}
}
};
private static void createEditHistoryDialog(@NotNull final HistoryItemMenuData data, @NotNull final Context context, final boolean save) {
final CalculatorHistoryState historyState = data.getHistoryState();
final LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View editView = layoutInflater.inflate(R.layout.history_edit, null);
final TextView historyExpression = (TextView)editView.findViewById(R.id.history_edit_expression);
historyExpression.setText(AbstractHistoryActivity.getHistoryText(historyState));
final EditText comment = (EditText)editView.findViewById(R.id.history_edit_comment);
comment.setText(historyState.getComment());
final AlertDialog.Builder builder = new AlertDialog.Builder(context)
.setTitle(save ? R.string.c_save_history : R.string.c_edit_history)
.setCancelable(true)
.setNegativeButton(R.string.c_cancel, null)
.setPositiveButton(R.string.c_save, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (save) {
final CalculatorHistoryState savedHistoryItem = AndroidCalculatorHistoryImpl.instance.addSavedState(historyState);
savedHistoryItem.setComment(comment.getText().toString());
AndroidCalculatorHistoryImpl.instance.save(context);
// 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);
} else {
historyState.setComment(comment.getText().toString());
AndroidCalculatorHistoryImpl.instance.save(context);
}
data.getAdapter().notifyDataSetChanged();
Toast.makeText(context, context.getText(R.string.c_history_saved), Toast.LENGTH_LONG).show();
}
})
.setView(editView);
builder.create().show();
}
private final int captionId;
private HistoryItemMenuItem(int captionId) {
this.captionId = captionId;
}
@NotNull
@Override
public String getCaption(@NotNull Context context) {
return context.getString(captionId);
}
}
/*
* 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.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.ClipboardManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.CalculatorLocatorImpl;
import org.solovyev.android.calculator.R;
import org.solovyev.android.menu.LabeledMenuItem;
import org.solovyev.common.text.StringUtils;
/**
* User: serso
* Date: 12/18/11
* Time: 3:09 PM
*/
public enum HistoryItemMenuItem implements LabeledMenuItem<HistoryItemMenuData> {
use(R.string.c_use) {
@Override
public void onClick(@NotNull HistoryItemMenuData data, @NotNull Context context) {
if (context instanceof AbstractHistoryActivity) {
AbstractHistoryActivity.useHistoryItem(data.getHistoryState(), (AbstractHistoryActivity) context);
} else {
Log.e(HistoryItemMenuItem.class.getName(), AbstractHistoryActivity.class + " must be passed as context!");
}
}
},
copy_expression(R.string.c_copy_expression) {
@Override
public void onClick(@NotNull HistoryItemMenuData data, @NotNull Context context) {
final CalculatorHistoryState calculatorHistoryState = data.getHistoryState();
final String text = calculatorHistoryState.getEditorState().getText();
if (!StringUtils.isEmpty(text)) {
final ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Activity.CLIPBOARD_SERVICE);
clipboard.setText(text);
Toast.makeText(context, context.getText(R.string.c_expression_copied), Toast.LENGTH_SHORT).show();
}
}
},
copy_result(R.string.c_copy_result) {
@Override
public void onClick(@NotNull HistoryItemMenuData data, @NotNull Context context) {
final CalculatorHistoryState calculatorHistoryState = data.getHistoryState();
final String text = calculatorHistoryState.getDisplayState().getEditorState().getText();
if (!StringUtils.isEmpty(text)) {
final ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Activity.CLIPBOARD_SERVICE);
clipboard.setText(text);
Toast.makeText(context, context.getText(R.string.c_result_copied), Toast.LENGTH_SHORT).show();
}
}
},
save(R.string.c_save) {
@Override
public void onClick(@NotNull final HistoryItemMenuData data, @NotNull final Context context) {
final CalculatorHistoryState historyState = data.getHistoryState();
if (!historyState.isSaved()) {
createEditHistoryDialog(data, context, true);
} else {
Toast.makeText(context, context.getText(R.string.c_history_already_saved), Toast.LENGTH_LONG).show();
}
}
},
edit(R.string.c_edit) {
@Override
public void onClick(@NotNull final HistoryItemMenuData data, @NotNull final Context context) {
final CalculatorHistoryState historyState = data.getHistoryState();
if (historyState.isSaved()) {
createEditHistoryDialog(data, context, false);
} else {
Toast.makeText(context, context.getText(R.string.c_history_must_be_saved), Toast.LENGTH_LONG).show();
}
}
},
remove(R.string.c_remove) {
@Override
public void onClick(@NotNull HistoryItemMenuData data, @NotNull Context context) {
final CalculatorHistoryState historyState = data.getHistoryState();
if (historyState.isSaved()) {
data.getAdapter().remove(historyState);
CalculatorLocatorImpl.getInstance().getHistory().removeSavedHistory(historyState);
Toast.makeText(context, context.getText(R.string.c_history_was_removed), Toast.LENGTH_LONG).show();
data.getAdapter().notifyDataSetChanged();
}
}
};
private static void createEditHistoryDialog(@NotNull final HistoryItemMenuData data, @NotNull final Context context, final boolean save) {
final CalculatorHistoryState historyState = data.getHistoryState();
final LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View editView = layoutInflater.inflate(R.layout.history_edit, null);
final TextView historyExpression = (TextView)editView.findViewById(R.id.history_edit_expression);
historyExpression.setText(AbstractHistoryActivity.getHistoryText(historyState));
final EditText comment = (EditText)editView.findViewById(R.id.history_edit_comment);
comment.setText(historyState.getComment());
final AlertDialog.Builder builder = new AlertDialog.Builder(context)
.setTitle(save ? R.string.c_save_history : R.string.c_edit_history)
.setCancelable(true)
.setNegativeButton(R.string.c_cancel, null)
.setPositiveButton(R.string.c_save, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (save) {
final CalculatorHistoryState savedHistoryItem = CalculatorLocatorImpl.getInstance().getHistory().addSavedState(historyState);
savedHistoryItem.setComment(comment.getText().toString());
CalculatorLocatorImpl.getInstance().getHistory().save();
// 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);
} else {
historyState.setComment(comment.getText().toString());
CalculatorLocatorImpl.getInstance().getHistory().save();
}
data.getAdapter().notifyDataSetChanged();
Toast.makeText(context, context.getText(R.string.c_history_saved), Toast.LENGTH_LONG).show();
}
})
.setView(editView);
builder.create().show();
}
private final int captionId;
private HistoryItemMenuItem(int captionId) {
this.captionId = captionId;
}
@NotNull
@Override
public String getCaption(@NotNull Context context) {
return context.getString(captionId);
}
}

View File

@@ -1,37 +1,38 @@
/*
* 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 org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.R;
import java.util.ArrayList;
import java.util.List;
/**
* User: serso
* Date: 12/18/11
* Time: 7:40 PM
*/
public class SavedHistoryActivityTab extends AbstractHistoryActivity {
@Override
protected int getLayoutId() {
return R.layout.saved_history;
}
@NotNull
@Override
protected List<CalculatorHistoryState> getHistoryItems() {
return new ArrayList<CalculatorHistoryState>(AndroidCalculatorHistoryImpl.instance.getSavedHistory());
}
@Override
protected void clearHistory() {
AndroidCalculatorHistoryImpl.instance.clearSavedHistory(this);
getAdapter().clear();
}
}
/*
* 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 org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.CalculatorLocatorImpl;
import org.solovyev.android.calculator.R;
import java.util.ArrayList;
import java.util.List;
/**
* User: serso
* Date: 12/18/11
* Time: 7:40 PM
*/
public class SavedHistoryActivityTab extends AbstractHistoryActivity {
@Override
protected int getLayoutId() {
return R.layout.saved_history;
}
@NotNull
@Override
protected List<CalculatorHistoryState> getHistoryItems() {
return new ArrayList<CalculatorHistoryState>(CalculatorLocatorImpl.getInstance().getHistory().getSavedHistory());
}
@Override
protected void clearHistory() {
CalculatorLocatorImpl.getInstance().getHistory().clearSavedHistory();
getAdapter().clear();
}
}

View File

@@ -21,7 +21,7 @@ import org.jetbrains.annotations.Nullable;
import org.solovyev.android.ads.AdsController;
import org.solovyev.android.calculator.CalculatorLocatorImpl;
import org.solovyev.android.calculator.R;
import org.solovyev.android.calculator.model.AndroidMathRegistry;
import org.solovyev.android.calculator.CalculatorMathRegistry;
import org.solovyev.android.menu.AMenuBuilder;
import org.solovyev.android.menu.LabeledMenuItem;
import org.solovyev.android.menu.MenuImpl;
@@ -106,7 +106,7 @@ public abstract class AbstractMathEntityListActivity<T extends MathEntity> exten
final int position,
final long id) {
CalculatorLocatorImpl.getInstance().getCalculatorKeyboard().digitButtonPressed(((MathEntity) parent.getItemAtPosition(position)).getName());
CalculatorLocatorImpl.getInstance().getKeyboard().digitButtonPressed(((MathEntity) parent.getItemAtPosition(position)).getName());
AbstractMathEntityListActivity.this.finish();
}
@@ -238,15 +238,15 @@ public abstract class AbstractMathEntityListActivity<T extends MathEntity> exten
protected static class MathEntityDescriptionGetterImpl implements MathEntityDescriptionGetter {
@NotNull
private final AndroidMathRegistry<?> mathRegistry;
private final CalculatorMathRegistry<?> mathRegistry;
public MathEntityDescriptionGetterImpl(@NotNull AndroidMathRegistry<?> mathRegistry) {
public MathEntityDescriptionGetterImpl(@NotNull CalculatorMathRegistry<?> mathRegistry) {
this.mathRegistry = mathRegistry;
}
@Override
public String getDescription(@NotNull Context context, @NotNull String mathEntityName) {
return this.mathRegistry.getDescription(context, mathEntityName);
return this.mathRegistry.getDescription(mathEntityName);
}
}

View File

@@ -14,7 +14,6 @@ import jscl.math.function.Function;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.CalculatorLocatorImpl;
import org.solovyev.android.calculator.R;
import org.solovyev.android.calculator.model.CalculatorEngine;
import org.solovyev.android.menu.LabeledMenuItem;
import org.solovyev.common.text.StringUtils;
@@ -33,7 +32,7 @@ public class CalculatorFunctionsActivity extends AbstractMathEntityListActivity<
use(R.string.c_use) {
@Override
public void onClick(@NotNull Function data, @NotNull Context context) {
CalculatorLocatorImpl.getInstance().getCalculatorKeyboard().digitButtonPressed(data.getName());
CalculatorLocatorImpl.getInstance().getKeyboard().digitButtonPressed(data.getName());
if (context instanceof Activity) {
((Activity) context).finish();
}
@@ -51,7 +50,7 @@ public class CalculatorFunctionsActivity extends AbstractMathEntityListActivity<
copy_description(R.string.c_copy_description) {
@Override
public void onClick(@NotNull Function data, @NotNull Context context) {
final String text = CalculatorEngine.instance.getFunctionsRegistry().getDescription(context, data.getName());
final String text = CalculatorLocatorImpl.getInstance().getEngine().getFunctionsRegistry().getDescription(data.getName());
if (!StringUtils.isEmpty(text)) {
final ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Activity.CLIPBOARD_SERVICE);
clipboard.setText(text);
@@ -110,7 +109,7 @@ public class CalculatorFunctionsActivity extends AbstractMathEntityListActivity<
protected List<LabeledMenuItem<Function>> getMenuItemsOnLongClick(@NotNull Function item) {
List<LabeledMenuItem<Function>> result = new ArrayList<LabeledMenuItem<Function>>(Arrays.asList(LongClickMenuItem.values()));
if ( StringUtils.isEmpty(CalculatorEngine.instance.getFunctionsRegistry().getDescription(this, item.getName())) ) {
if ( StringUtils.isEmpty(CalculatorLocatorImpl.getInstance().getEngine().getFunctionsRegistry().getDescription(item.getName())) ) {
result.remove(LongClickMenuItem.copy_description);
}
@@ -206,17 +205,17 @@ public class CalculatorFunctionsActivity extends AbstractMathEntityListActivity<
@NotNull
@Override
protected MathEntityDescriptionGetter getDescriptionGetter() {
return new MathEntityDescriptionGetterImpl(CalculatorEngine.instance.getFunctionsRegistry());
return new MathEntityDescriptionGetterImpl(CalculatorLocatorImpl.getInstance().getEngine().getFunctionsRegistry());
}
@NotNull
@Override
protected List<Function> getMathEntities() {
return new ArrayList<Function>(CalculatorEngine.instance.getFunctionsRegistry().getEntities());
return new ArrayList<Function>(CalculatorLocatorImpl.getInstance().getEngine().getFunctionsRegistry().getEntities());
}
@Override
protected String getMathEntityCategory(@NotNull Function function) {
return CalculatorEngine.instance.getFunctionsRegistry().getCategory(function);
return CalculatorLocatorImpl.getInstance().getEngine().getFunctionsRegistry().getCategory(function);
}
}

View File

@@ -7,7 +7,6 @@ import jscl.math.operator.Operator;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.CalculatorLocatorImpl;
import org.solovyev.android.calculator.R;
import org.solovyev.android.calculator.model.CalculatorEngine;
import org.solovyev.android.menu.LabeledMenuItem;
import org.solovyev.common.text.StringUtils;
@@ -28,7 +27,7 @@ public class CalculatorOperatorsActivity extends AbstractMathEntityListActivity<
use(R.string.c_use) {
@Override
public void onClick(@NotNull Operator data, @NotNull Context context) {
CalculatorLocatorImpl.getInstance().getCalculatorKeyboard().digitButtonPressed(data.getName());
CalculatorLocatorImpl.getInstance().getKeyboard().digitButtonPressed(data.getName());
if (context instanceof Activity) {
((Activity) context).finish();
}
@@ -82,17 +81,17 @@ public class CalculatorOperatorsActivity extends AbstractMathEntityListActivity<
protected List<Operator> getMathEntities() {
final List<Operator> result = new ArrayList<Operator>();
result.addAll(CalculatorEngine.instance.getOperatorsRegistry().getEntities());
result.addAll(CalculatorEngine.instance.getPostfixFunctionsRegistry().getEntities());
result.addAll(CalculatorLocatorImpl.getInstance().getEngine().getOperatorsRegistry().getEntities());
result.addAll(CalculatorLocatorImpl.getInstance().getEngine().getPostfixFunctionsRegistry().getEntities());
return result;
}
@Override
protected String getMathEntityCategory(@NotNull Operator operator) {
String result = CalculatorEngine.instance.getOperatorsRegistry().getCategory(operator);
String result = CalculatorLocatorImpl.getInstance().getEngine().getOperatorsRegistry().getCategory(operator);
if (result == null) {
result = CalculatorEngine.instance.getPostfixFunctionsRegistry().getCategory(operator);
result = CalculatorLocatorImpl.getInstance().getEngine().getPostfixFunctionsRegistry().getCategory(operator);
}
return result;
@@ -104,9 +103,9 @@ public class CalculatorOperatorsActivity extends AbstractMathEntityListActivity<
@Override
public String getDescription(@NotNull Context context, @NotNull String mathEntityName) {
String result = CalculatorEngine.instance.getOperatorsRegistry().getDescription(context, mathEntityName);
String result = CalculatorLocatorImpl.getInstance().getEngine().getOperatorsRegistry().getDescription(mathEntityName);
if (StringUtils.isEmpty(result)) {
result = CalculatorEngine.instance.getPostfixFunctionsRegistry().getDescription(context, mathEntityName);
result = CalculatorLocatorImpl.getInstance().getEngine().getPostfixFunctionsRegistry().getDescription(mathEntityName);
}
return result;

View File

@@ -24,7 +24,6 @@ import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.CalculatorLocatorImpl;
import org.solovyev.android.calculator.R;
import org.solovyev.android.calculator.math.MathType;
import org.solovyev.android.calculator.model.CalculatorEngine;
import org.solovyev.android.calculator.model.Var;
import org.solovyev.android.menu.LabeledMenuItem;
import org.solovyev.common.JPredicate;
@@ -46,7 +45,7 @@ public class CalculatorVarsActivity extends AbstractMathEntityListActivity<ICons
use(R.string.c_use) {
@Override
public void onClick(@NotNull IConstant data, @NotNull Context context) {
CalculatorLocatorImpl.getInstance().getCalculatorKeyboard().digitButtonPressed(data.getName());
CalculatorLocatorImpl.getInstance().getKeyboard().digitButtonPressed(data.getName());
if (context instanceof Activity) {
((Activity) context).finish();
}
@@ -66,7 +65,7 @@ public class CalculatorVarsActivity extends AbstractMathEntityListActivity<ICons
@Override
public void onClick(@NotNull IConstant data, @NotNull Context context) {
if (context instanceof AbstractMathEntityListActivity) {
new MathEntityRemover<IConstant>(data, null, CalculatorEngine.instance.getVarsRegistry(), ((AbstractMathEntityListActivity<IConstant>) context)).showConfirmationDialog();
new MathEntityRemover<IConstant>(data, null, CalculatorLocatorImpl.getInstance().getEngine().getVarsRegistry(), ((AbstractMathEntityListActivity<IConstant>) context)).showConfirmationDialog();
}
}
},
@@ -85,7 +84,7 @@ public class CalculatorVarsActivity extends AbstractMathEntityListActivity<ICons
copy_description(R.string.c_copy_description) {
@Override
public void onClick(@NotNull IConstant data, @NotNull Context context) {
final String text = CalculatorEngine.instance.getVarsRegistry().getDescription(context, data.getName());
final String text = CalculatorLocatorImpl.getInstance().getEngine().getVarsRegistry().getDescription(data.getName());
if (!StringUtils.isEmpty(text)) {
final ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Activity.CLIPBOARD_SERVICE);
clipboard.setText(text);
@@ -138,7 +137,7 @@ public class CalculatorVarsActivity extends AbstractMathEntityListActivity<ICons
result.remove(LongClickMenuItem.remove);
}
if ( StringUtils.isEmpty(CalculatorEngine.instance.getVarsRegistry().getDescription(this, item.getName())) ) {
if ( StringUtils.isEmpty(CalculatorLocatorImpl.getInstance().getEngine().getVarsRegistry().getDescription(item.getName())) ) {
result.remove(LongClickMenuItem.copy_description);
}
@@ -152,7 +151,7 @@ public class CalculatorVarsActivity extends AbstractMathEntityListActivity<ICons
@NotNull
@Override
protected MathEntityDescriptionGetter getDescriptionGetter() {
return new MathEntityDescriptionGetterImpl(CalculatorEngine.instance.getVarsRegistry());
return new MathEntityDescriptionGetterImpl(CalculatorLocatorImpl.getInstance().getEngine().getVarsRegistry());
}
@SuppressWarnings({"UnusedDeclaration"})
@@ -163,7 +162,7 @@ public class CalculatorVarsActivity extends AbstractMathEntityListActivity<ICons
@NotNull
@Override
protected List<IConstant> getMathEntities() {
final List<IConstant> result = new ArrayList<IConstant>(CalculatorEngine.instance.getVarsRegistry().getEntities());
final List<IConstant> result = new ArrayList<IConstant>(CalculatorLocatorImpl.getInstance().getEngine().getVarsRegistry().getEntities());
CollectionsUtils.removeAll(result, new JPredicate<IConstant>() {
@Override
@@ -177,7 +176,7 @@ public class CalculatorVarsActivity extends AbstractMathEntityListActivity<ICons
@Override
protected String getMathEntityCategory(@NotNull IConstant var) {
return CalculatorEngine.instance.getVarsRegistry().getCategory(var);
return CalculatorLocatorImpl.getInstance().getEngine().getVarsRegistry().getCategory(var);
}
private static void createEditVariableDialog(@NotNull final AbstractMathEntityListActivity<IConstant> activity,
@@ -234,7 +233,7 @@ public class CalculatorVarsActivity extends AbstractMathEntityListActivity<ICons
final AlertDialog.Builder builder = new AlertDialog.Builder(activity)
.setCancelable(true)
.setNegativeButton(R.string.c_cancel, null)
.setPositiveButton(R.string.c_save, new VarEditorSaver<IConstant>(varBuilder, var, editView, activity, CalculatorEngine.instance.getVarsRegistry(), new VarEditorSaver.EditorCreator<IConstant>() {
.setPositiveButton(R.string.c_save, new VarEditorSaver<IConstant>(varBuilder, var, editView, activity, CalculatorLocatorImpl.getInstance().getEngine().getVarsRegistry(), new VarEditorSaver.EditorCreator<IConstant>() {
@Override
public void showEditor(@NotNull AbstractMathEntityListActivity<IConstant> activity, @Nullable IConstant editedInstance, @Nullable String name, @Nullable String value, @Nullable String description) {
createEditVariableDialog(activity, editedInstance, name, value, description);
@@ -251,7 +250,7 @@ public class CalculatorVarsActivity extends AbstractMathEntityListActivity<ICons
public void onClick(DialogInterface dialog, int which) {
createEditVariableDialog(activity, var, name, value, description);
}
}, CalculatorEngine.instance.getVarsRegistry(), activity));
}, CalculatorLocatorImpl.getInstance().getEngine().getVarsRegistry(), activity));
} else {
// CREATE mode

View File

@@ -18,10 +18,10 @@ import jscl.text.ParseException;
import jscl.text.Parser;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.CalculatorLocatorImpl;
import org.solovyev.android.calculator.CalculatorMathRegistry;
import org.solovyev.android.calculator.R;
import org.solovyev.android.calculator.math.MathType;
import org.solovyev.android.calculator.model.AndroidMathRegistry;
import org.solovyev.android.calculator.model.CalculatorEngine;
import org.solovyev.android.calculator.model.MathEntityBuilder;
import org.solovyev.common.math.MathEntity;
import org.solovyev.common.text.StringUtils;
@@ -52,7 +52,7 @@ public class FunctionEditorSaver implements DialogInterface.OnClickListener{
private final CustomFunction editedInstance;
@NotNull
private final AndroidMathRegistry<Function> mathRegistry;
private final CalculatorMathRegistry<Function> mathRegistry;
@NotNull
private final AbstractMathEntityListActivity<Function> activity;
@@ -64,7 +64,7 @@ public class FunctionEditorSaver implements DialogInterface.OnClickListener{
@Nullable CustomFunction editedInstance,
@NotNull View editView,
@NotNull AbstractMathEntityListActivity<Function> activity,
@NotNull AndroidMathRegistry<Function> mathRegistry,
@NotNull CalculatorMathRegistry<Function> mathRegistry,
@NotNull EditorCreator<Function> editorCreator) {
this.varBuilder = varBuilder;
this.editedInstance = editedInstance;
@@ -145,7 +145,7 @@ public class FunctionEditorSaver implements DialogInterface.OnClickListener{
activity.addToAdapter(addedVar);
}
mathRegistry.save(activity);
mathRegistry.save();
if (activity.isInCategory(addedVar)) {
activity.sort();
@@ -160,7 +160,7 @@ public class FunctionEditorSaver implements DialogInterface.OnClickListener{
if (!StringUtils.isEmpty(name)) {
try {
assert name != null;
Identifier.parser.parse(Parser.Parameters.newInstance(name, new MutableInt(0), CalculatorEngine.instance.getEngine()), null);
Identifier.parser.parse(Parser.Parameters.newInstance(name, new MutableInt(0), CalculatorLocatorImpl.getInstance().getEngine().getEngine()), null);
result = true;
} catch (ParseException e) {
// not valid name;

View File

@@ -12,7 +12,7 @@ import android.widget.TextView;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.R;
import org.solovyev.android.calculator.model.AndroidMathRegistry;
import org.solovyev.android.calculator.CalculatorMathRegistry;
import org.solovyev.common.math.MathEntity;
/**
@@ -31,14 +31,14 @@ class MathEntityRemover<T extends MathEntity> implements DialogInterface.OnClick
private final boolean confirmed;
@NotNull
private final AndroidMathRegistry<? super T> varsRegistry;
private final CalculatorMathRegistry<? super T> varsRegistry;
@NotNull
private final AbstractMathEntityListActivity<T> activity;
public MathEntityRemover(@NotNull T mathEntity,
@Nullable DialogInterface.OnClickListener callbackOnCancel,
@NotNull AndroidMathRegistry<? super T> varsRegistry,
@NotNull CalculatorMathRegistry<? super T> varsRegistry,
@NotNull AbstractMathEntityListActivity<T> activity) {
this(mathEntity, callbackOnCancel, false, varsRegistry, activity);
}
@@ -46,7 +46,7 @@ class MathEntityRemover<T extends MathEntity> implements DialogInterface.OnClick
public MathEntityRemover(@NotNull T mathEntity,
@Nullable DialogInterface.OnClickListener callbackOnCancel,
boolean confirmed,
@NotNull AndroidMathRegistry<? super T> varsRegistry,
@NotNull CalculatorMathRegistry<? super T> varsRegistry,
@NotNull AbstractMathEntityListActivity<T> activity) {
this.mathEntity = mathEntity;
this.callbackOnCancel = callbackOnCancel;
@@ -65,7 +65,7 @@ class MathEntityRemover<T extends MathEntity> implements DialogInterface.OnClick
}
varsRegistry.remove(mathEntity);
varsRegistry.save(activity);
varsRegistry.save();
if (activity.isInCategory(mathEntity)) {
activity.notifyAdapter();
}

View File

@@ -16,10 +16,10 @@ import jscl.text.ParseException;
import jscl.text.Parser;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.CalculatorLocatorImpl;
import org.solovyev.android.calculator.CalculatorMathRegistry;
import org.solovyev.android.calculator.R;
import org.solovyev.android.calculator.math.MathType;
import org.solovyev.android.calculator.model.AndroidMathRegistry;
import org.solovyev.android.calculator.model.CalculatorEngine;
import org.solovyev.android.calculator.model.MathEntityBuilder;
import org.solovyev.common.math.MathEntity;
import org.solovyev.common.text.StringUtils;
@@ -49,7 +49,7 @@ class VarEditorSaver<T extends MathEntity> implements DialogInterface.OnClickLis
private final T editedInstance;
@NotNull
private final AndroidMathRegistry<T> mathRegistry;
private final CalculatorMathRegistry<T> mathRegistry;
@NotNull
private final AbstractMathEntityListActivity<T> activity;
@@ -61,7 +61,7 @@ class VarEditorSaver<T extends MathEntity> implements DialogInterface.OnClickLis
@Nullable T editedInstance,
@NotNull View editView,
@NotNull AbstractMathEntityListActivity<T> activity,
@NotNull AndroidMathRegistry<T> mathRegistry,
@NotNull CalculatorMathRegistry<T> mathRegistry,
@NotNull EditorCreator<T> editorCreator) {
this.varBuilder = varBuilder;
this.editedInstance = editedInstance;
@@ -142,7 +142,7 @@ class VarEditorSaver<T extends MathEntity> implements DialogInterface.OnClickLis
activity.addToAdapter(addedVar);
}
mathRegistry.save(activity);
mathRegistry.save();
if (activity.isInCategory(addedVar)) {
activity.sort();
@@ -157,7 +157,7 @@ class VarEditorSaver<T extends MathEntity> implements DialogInterface.OnClickLis
if (!StringUtils.isEmpty(name)) {
try {
assert name != null;
Identifier.parser.parse(Parser.Parameters.newInstance(name, new MutableInt(0), CalculatorEngine.instance.getEngine()), null);
Identifier.parser.parse(Parser.Parameters.newInstance(name, new MutableInt(0), CalculatorLocatorImpl.getInstance().getEngine().getEngine()), null);
result = true;
} catch (ParseException e) {
// not valid name;

View File

@@ -6,6 +6,7 @@
package org.solovyev.android.calculator.model;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
@@ -13,6 +14,7 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
import org.solovyev.android.calculator.CalculatorMathRegistry;
import org.solovyev.android.calculator.R;
import org.solovyev.android.calculator.about.TextHelper;
import org.solovyev.common.JBuilder;
@@ -28,7 +30,7 @@ import java.util.Map;
* Date: 10/30/11
* Time: 1:03 AM
*/
public abstract class AbstractAndroidMathRegistry<T extends MathEntity, P extends MathPersistenceEntity> implements AndroidMathRegistry<T> {
public abstract class AbstractAndroidMathRegistry<T extends MathEntity, P extends MathPersistenceEntity> implements CalculatorMathRegistry<T> {
@NotNull
private final MathRegistry<T> mathRegistry;
@@ -36,17 +38,25 @@ public abstract class AbstractAndroidMathRegistry<T extends MathEntity, P extend
@NotNull
private final String prefix;
protected AbstractAndroidMathRegistry(@NotNull MathRegistry<T> mathRegistry, @NotNull String prefix) {
@NotNull
private final Context context;
protected AbstractAndroidMathRegistry(@NotNull MathRegistry<T> mathRegistry,
@NotNull String prefix,
@NotNull Application application) {
this.mathRegistry = mathRegistry;
this.prefix = prefix;
this.context = application;
}
@NotNull
@NotNull
protected abstract Map<String, String> getSubstitutes();
@Nullable
@Override
public String getDescription(@NotNull Context context, @NotNull String mathEntityName) {
public String getDescription(@NotNull String mathEntityName) {
final String stringName;
final Map<String, String> substitutes = getSubstitutes();
@@ -60,9 +70,10 @@ public abstract class AbstractAndroidMathRegistry<T extends MathEntity, P extend
return new TextHelper(context.getResources(), R.class.getPackage().getName()).getText(stringName);
}
public synchronized void load(@Nullable Context context, @Nullable SharedPreferences preferences) {
public synchronized void load() {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
if (context != null && preferences != null) {
if (preferences != null) {
final Integer preferenceStringId = getPreferenceStringId();
if (preferenceStringId != null) {
final String value = preferences.getString(context.getString(preferenceStringId), null);
@@ -99,7 +110,7 @@ public abstract class AbstractAndroidMathRegistry<T extends MathEntity, P extend
@Override
public synchronized void save(@NotNull Context context) {
public synchronized void save() {
final Integer preferenceStringId = getPreferenceStringId();
if (preferenceStringId != null) {

View File

@@ -5,8 +5,10 @@
package org.solovyev.android.calculator.model;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import jscl.*;
import jscl.math.Generic;
import jscl.math.function.Function;
@@ -42,9 +44,7 @@ import java.util.concurrent.TimeUnit;
* Time: 11:38 PM
*/
public enum CalculatorEngine implements JCalculatorEngine {
instance;
public class AndroidCalculatorEngine implements CalculatorEngine {
private static final String GROUPING_SEPARATOR_P_KEY = "org.solovyev.android.calculator.CalculatorActivity_calc_grouping_separator";
@@ -108,15 +108,15 @@ public enum CalculatorEngine implements JCalculatorEngine {
public final TextProcessor<PreparedExpression, String> preprocessor = ToJsclTextProcessor.getInstance();
@NotNull
private final AndroidMathRegistry<IConstant> varsRegistry = new AndroidVarsRegistryImpl(engine.getConstantsRegistry());
private final CalculatorMathRegistry<IConstant> varsRegistry;
@NotNull
private final AndroidMathRegistry<jscl.math.function.Function> functionsRegistry = new AndroidFunctionsMathRegistry(engine.getFunctionsRegistry());
private final CalculatorMathRegistry<Function> functionsRegistry;
@NotNull
private final AndroidMathRegistry<Operator> operatorsRegistry = new AndroidOperatorsMathRegistry(engine.getOperatorsRegistry());
private final CalculatorMathRegistry<Operator> operatorsRegistry;
private final AndroidMathRegistry<Operator> postfixFunctionsRegistry = new AndroidPostfixFunctionsRegistry(engine.getPostfixFunctionsRegistry());
private final CalculatorMathRegistry<Operator> postfixFunctionsRegistry;
@Nullable
private ThreadKiller threadKiller = new AndroidThreadKiller();
@@ -127,10 +127,20 @@ public enum CalculatorEngine implements JCalculatorEngine {
@NotNull
private String multiplicationSign = MULTIPLICATION_SIGN_DEFAULT;
CalculatorEngine() {
@NotNull
private final Context context;
public AndroidCalculatorEngine(@NotNull Application application) {
this.context = application;
this.engine.setRoundResult(true);
this.engine.setUseGroupingSeparator(true);
}
this.varsRegistry = new AndroidVarsRegistryImpl(engine.getConstantsRegistry(), application);
this.functionsRegistry = new AndroidFunctionsMathRegistry(engine.getFunctionsRegistry(), application);
this.operatorsRegistry = new AndroidOperatorsMathRegistry(engine.getOperatorsRegistry(), application);
this.postfixFunctionsRegistry = new AndroidPostfixFunctionsRegistry(engine.getPostfixFunctionsRegistry(), application);
}
@Override
@NotNull
@@ -273,47 +283,54 @@ public enum CalculatorEngine implements JCalculatorEngine {
this.getEngine().setRoundResult(roundResult);
}
public void init(@Nullable Context context, @Nullable SharedPreferences preferences) {
@Override
public void init() {
synchronized (lock) {
reset(context, preferences);
reset();
}
}
public void reset(@Nullable Context context, @Nullable SharedPreferences preferences) {
@Override
public void reset() {
synchronized (lock) {
softReset(context, preferences);
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
varsRegistry.load(context, preferences);
functionsRegistry.load(context, preferences);
operatorsRegistry.load(context, preferences);
postfixFunctionsRegistry.load(context, preferences);
softReset(preferences);
varsRegistry.load();
functionsRegistry.load();
operatorsRegistry.load();
postfixFunctionsRegistry.load();
}
}
public void softReset(@Nullable Context context, @Nullable SharedPreferences preferences) {
@Override
public void softReset() {
synchronized (lock) {
if (preferences != null) {
this.setPrecision(Preferences.precision.getPreference(preferences));
this.setRoundResult(Preferences.roundResult.getPreference(preferences));
this.setAngleUnits(getAngleUnitsFromPrefs(preferences));
this.setNumeralBase(getNumeralBaseFromPrefs(preferences));
this.setMultiplicationSign(Preferences.multiplicationSign.getPreference(preferences));
this.setScienceNotation(Preferences.scienceNotation.getPreference(preferences));
this.setTimeout(Preferences.maxCalculationTime.getPreference(preferences));
final String groupingSeparator = Preferences.groupingSeparator.getPreference(preferences);
if (StringUtils.isEmpty(groupingSeparator)) {
this.getEngine().setUseGroupingSeparator(false);
} else {
this.getEngine().setUseGroupingSeparator(true);
this.getEngine().setGroupingSeparator(groupingSeparator.charAt(0));
}
}
softReset(PreferenceManager.getDefaultSharedPreferences(context));
}
}
private void softReset(@NotNull SharedPreferences preferences) {
this.setPrecision(Preferences.precision.getPreference(preferences));
this.setRoundResult(Preferences.roundResult.getPreference(preferences));
this.setAngleUnits(getAngleUnitsFromPrefs(preferences));
this.setNumeralBase(getNumeralBaseFromPrefs(preferences));
this.setMultiplicationSign(Preferences.multiplicationSign.getPreference(preferences));
this.setScienceNotation(Preferences.scienceNotation.getPreference(preferences));
this.setTimeout(Preferences.maxCalculationTime.getPreference(preferences));
@NotNull
final String groupingSeparator = Preferences.groupingSeparator.getPreference(preferences);
if (StringUtils.isEmpty(groupingSeparator)) {
this.getEngine().setUseGroupingSeparator(false);
} else {
this.getEngine().setUseGroupingSeparator(true);
this.getEngine().setGroupingSeparator(groupingSeparator.charAt(0));
}
}
@NotNull
public NumeralBase getNumeralBaseFromPrefs(@NotNull SharedPreferences preferences) {
return Preferences.numeralBase.getPreference(preferences);
}
@@ -332,25 +349,25 @@ public enum CalculatorEngine implements JCalculatorEngine {
@Override
@NotNull
public AndroidMathRegistry<IConstant> getVarsRegistry() {
public CalculatorMathRegistry<IConstant> getVarsRegistry() {
return varsRegistry;
}
@Override
@NotNull
public AndroidMathRegistry<Function> getFunctionsRegistry() {
public CalculatorMathRegistry<Function> getFunctionsRegistry() {
return functionsRegistry;
}
@Override
@NotNull
public AndroidMathRegistry<Operator> getOperatorsRegistry() {
public CalculatorMathRegistry<Operator> getOperatorsRegistry() {
return operatorsRegistry;
}
@Override
@NotNull
public AndroidMathRegistry<Operator> getPostfixFunctionsRegistry() {
public CalculatorMathRegistry<Operator> getPostfixFunctionsRegistry() {
return postfixFunctionsRegistry;
}

View File

@@ -6,11 +6,9 @@
package org.solovyev.android.calculator.model;
import android.content.Context;
import android.content.SharedPreferences;
import android.app.Application;
import jscl.math.function.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.R;
import org.solovyev.common.JBuilder;
import org.solovyev.common.collections.CollectionsUtils;
@@ -115,13 +113,14 @@ public class AndroidFunctionsMathRegistry extends AbstractAndroidMathRegistry<Fu
@NotNull
private static final String FUNCTION_DESCRIPTION_PREFIX = "c_fun_description_";
public AndroidFunctionsMathRegistry(@NotNull MathRegistry<jscl.math.function.Function> functionsRegistry) {
super(functionsRegistry, FUNCTION_DESCRIPTION_PREFIX);
public AndroidFunctionsMathRegistry(@NotNull MathRegistry<Function> functionsRegistry,
@NotNull Application application) {
super(functionsRegistry, FUNCTION_DESCRIPTION_PREFIX, application);
}
@Override
public void load(@Nullable Context context, @Nullable SharedPreferences preferences) {
super.load(context, preferences);
public void load() {
super.load();
add(new CustomFunction.Builder(true, "log", new String[]{"base", "x"}, "ln(x)/ln(base)"));
}

View File

@@ -1,32 +0,0 @@
/*
* Copyright (c) 2009-2011. Created by serso aka se.solovyev.
* For more information, please, contact se.solovyev@gmail.com
* or visit http://se.solovyev.org
*/
package org.solovyev.android.calculator.model;
import android.content.Context;
import android.content.SharedPreferences;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.common.math.MathEntity;
import org.solovyev.common.math.MathRegistry;
/**
* User: serso
* Date: 10/30/11
* Time: 1:02 AM
*/
public interface AndroidMathRegistry<T extends MathEntity> extends MathRegistry<T> {
@Nullable
String getDescription(@NotNull Context context, @NotNull String mathEntityName);
@Nullable
String getCategory(@NotNull T mathEntity);
void load(@Nullable Context context, @Nullable SharedPreferences preferences);
void save(@NotNull Context context);
}

View File

@@ -6,11 +6,9 @@
package org.solovyev.android.calculator.model;
import android.content.Context;
import android.content.SharedPreferences;
import android.app.Application;
import jscl.math.operator.Operator;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.common.JBuilder;
import org.solovyev.common.math.MathRegistry;
@@ -38,8 +36,9 @@ public class AndroidOperatorsMathRegistry extends AbstractAndroidMathRegistry<Op
@NotNull
private static final String OPERATOR_DESCRIPTION_PREFIX = "c_op_description_";
protected AndroidOperatorsMathRegistry(@NotNull MathRegistry<Operator> functionsRegistry) {
super(functionsRegistry, OPERATOR_DESCRIPTION_PREFIX);
protected AndroidOperatorsMathRegistry(@NotNull MathRegistry<Operator> functionsRegistry,
@NotNull Application application) {
super(functionsRegistry, OPERATOR_DESCRIPTION_PREFIX, application);
}
@NotNull
@@ -54,7 +53,7 @@ public class AndroidOperatorsMathRegistry extends AbstractAndroidMathRegistry<Op
}
@Override
public void load(@Nullable Context context, @Nullable SharedPreferences preferences) {
public void load() {
// not supported yet
}
@@ -76,7 +75,7 @@ public class AndroidOperatorsMathRegistry extends AbstractAndroidMathRegistry<Op
}
@Override
public void save(@NotNull Context context) {
public void save() {
// not supported yet
}

View File

@@ -6,11 +6,9 @@
package org.solovyev.android.calculator.model;
import android.content.Context;
import android.content.SharedPreferences;
import android.app.Application;
import jscl.math.operator.Operator;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.common.JBuilder;
import org.solovyev.common.math.MathRegistry;
@@ -36,8 +34,9 @@ public class AndroidPostfixFunctionsRegistry extends AbstractAndroidMathRegistry
@NotNull
private static final String POSTFIX_FUNCTION_DESCRIPTION_PREFIX = "c_pf_description_";
protected AndroidPostfixFunctionsRegistry(@NotNull MathRegistry<Operator> functionsRegistry) {
super(functionsRegistry, POSTFIX_FUNCTION_DESCRIPTION_PREFIX);
protected AndroidPostfixFunctionsRegistry(@NotNull MathRegistry<Operator> functionsRegistry,
@NotNull Application application) {
super(functionsRegistry, POSTFIX_FUNCTION_DESCRIPTION_PREFIX, application);
}
@@ -53,7 +52,7 @@ public class AndroidPostfixFunctionsRegistry extends AbstractAndroidMathRegistry
}
@Override
public void load(@Nullable Context context, @Nullable SharedPreferences preferences) {
public void load() {
// not supported yet
}
@@ -75,7 +74,7 @@ public class AndroidPostfixFunctionsRegistry extends AbstractAndroidMathRegistry
}
@Override
public void save(@NotNull Context context) {
public void save() {
// not supported yet
}

View File

@@ -6,11 +6,9 @@
package org.solovyev.android.calculator.model;
import android.content.Context;
import android.content.SharedPreferences;
import android.app.Application;
import jscl.math.function.IConstant;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.R;
import org.solovyev.common.JBuilder;
import org.solovyev.common.math.MathRegistry;
@@ -35,8 +33,9 @@ class AndroidVarsRegistryImpl extends AbstractAndroidMathRegistry<IConstant, Var
substitutes.put("NaN", "nan");
}
protected AndroidVarsRegistryImpl(@NotNull MathRegistry<IConstant> mathRegistry) {
super(mathRegistry, "c_var_description_");
protected AndroidVarsRegistryImpl(@NotNull MathRegistry<IConstant> mathRegistry,
@NotNull Application application) {
super(mathRegistry, "c_var_description_", application);
}
@NotNull
@@ -45,8 +44,8 @@ class AndroidVarsRegistryImpl extends AbstractAndroidMathRegistry<IConstant, Var
return substitutes;
}
public synchronized void load(@Nullable Context context, @Nullable SharedPreferences preferences) {
super.load(context, preferences);
public synchronized void load() {
super.load();
tryToAddAuxVar("x");
tryToAddAuxVar("y");
@@ -101,12 +100,12 @@ class AndroidVarsRegistryImpl extends AbstractAndroidMathRegistry<IConstant, Var
}
@Override
public String getDescription(@NotNull Context context, @NotNull String mathEntityName) {
public String getDescription(@NotNull String mathEntityName) {
final IConstant var = get(mathEntityName);
if (var != null && !var.isSystem()) {
return var.getDescription();
} else {
return super.getDescription(context, mathEntityName);
return super.getDescription(mathEntityName);
}
}

View File

@@ -12,8 +12,8 @@ import android.graphics.Paint;
import android.text.TextPaint;
import android.util.AttributeSet;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.CalculatorLocatorImpl;
import org.solovyev.android.calculator.R;
import org.solovyev.android.calculator.model.CalculatorEngine;
import org.solovyev.android.view.drag.DirectionDragButton;
/**
@@ -34,7 +34,7 @@ public class AngleUnitsButton extends DirectionDragButton {
super.initDirectionTextPaint(basePaint, directionTextData, resources);
final TextPaint directionTextPaint = directionTextData.getPaint();
if (CalculatorEngine.instance.getEngine().getAngleUnits().name().equals(directionTextData.getText())) {
if (CalculatorLocatorImpl.getInstance().getEngine().getEngine().getAngleUnits().name().equals(directionTextData.getText())) {
directionTextPaint.setColor(resources.getColor(R.color.selected_angle_unit_text_color));
} else {
directionTextPaint.setColor(resources.getColor(R.color.default_text_color));

View File

@@ -12,7 +12,8 @@ import android.util.AttributeSet;
import android.widget.TextView;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.model.CalculatorEngine;
import org.solovyev.android.calculator.CalculatorLocatorImpl;
import org.solovyev.android.calculator.model.AndroidCalculatorEngine;
/**
* User: serso
@@ -39,6 +40,8 @@ public class CalculatorAdditionalTitle extends TextView implements SharedPrefere
@Override
public void onSharedPreferenceChanged(SharedPreferences preferences, @Nullable String key) {
setText(CalculatorEngine.instance.getNumeralBaseFromPrefs(preferences) + " / " + CalculatorEngine.instance.getAngleUnitsFromPrefs(preferences));
setText(((AndroidCalculatorEngine) CalculatorLocatorImpl.getInstance().getEngine()).getNumeralBaseFromPrefs(preferences)
+ " / " +
((AndroidCalculatorEngine) CalculatorLocatorImpl.getInstance().getEngine()).getAngleUnitsFromPrefs(preferences));
}
}

View File

@@ -9,7 +9,6 @@ import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.*;
import org.solovyev.math.units.Unit;
import org.solovyev.math.units.UnitImpl;
import org.solovyev.android.calculator.model.CalculatorEngine;
import org.solovyev.common.MutableObject;
import org.solovyev.common.text.StringUtils;
@@ -38,12 +37,12 @@ public class NumeralBaseConverterDialog {
String value = initialFromValue;
try {
value = ToJsclTextProcessor.getInstance().process(value).getExpression();
b.setFromValue(UnitImpl.newInstance(value, AndroidNumeralBase.valueOf(CalculatorEngine.instance.getEngine().getNumeralBase())));
b.setFromValue(UnitImpl.newInstance(value, AndroidNumeralBase.valueOf(CalculatorLocatorImpl.getInstance().getEngine().getEngine().getNumeralBase())));
} catch (CalculatorParseException e) {
b.setFromValue(UnitImpl.newInstance(value, AndroidNumeralBase.valueOf(CalculatorEngine.instance.getEngine().getNumeralBase())));
b.setFromValue(UnitImpl.newInstance(value, AndroidNumeralBase.valueOf(CalculatorLocatorImpl.getInstance().getEngine().getEngine().getNumeralBase())));
}
} else {
b.setFromValue(UnitImpl.newInstance("", AndroidNumeralBase.valueOf(CalculatorEngine.instance.getEngine().getNumeralBase())));
b.setFromValue(UnitImpl.newInstance("", AndroidNumeralBase.valueOf(CalculatorLocatorImpl.getInstance().getEngine().getEngine().getNumeralBase())));
}
b.setConverter(AndroidNumeralBase.getConverter());
@@ -64,11 +63,11 @@ public class NumeralBaseConverterDialog {
public void onClick(@NotNull Unit<String> fromUnits, @NotNull Unit<String> toUnits) {
String toUnitsValue = toUnits.getValue();
if (!toUnits.getUnitType().equals(AndroidNumeralBase.valueOf(CalculatorEngine.instance.getEngine().getNumeralBase()))) {
if (!toUnits.getUnitType().equals(AndroidNumeralBase.valueOf(CalculatorLocatorImpl.getInstance().getEngine().getEngine().getNumeralBase()))) {
toUnitsValue = ((AndroidNumeralBase) toUnits.getUnitType()).getNumeralBase().getJsclPrefix() + toUnitsValue;
}
CalculatorLocatorImpl.getInstance().getCalculatorKeyboard().digitButtonPressed(toUnitsValue);
CalculatorLocatorImpl.getInstance().getKeyboard().digitButtonPressed(toUnitsValue);
final AlertDialog alertDialog = alertDialogHolder.getObject();
if (alertDialog != null) {
alertDialog.dismiss();

View File

@@ -12,8 +12,8 @@ import android.graphics.Paint;
import android.text.TextPaint;
import android.util.AttributeSet;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.CalculatorLocatorImpl;
import org.solovyev.android.calculator.R;
import org.solovyev.android.calculator.model.CalculatorEngine;
import org.solovyev.android.view.drag.DirectionDragButton;
/**
@@ -34,7 +34,7 @@ public class NumeralBasesButton extends DirectionDragButton {
super.initDirectionTextPaint(basePaint, directionTextData, resources);
final TextPaint directionTextPaint = directionTextData.getPaint();
if (CalculatorEngine.instance.getEngine().getNumeralBase().name().equals(directionTextData.getText())) {
if (CalculatorLocatorImpl.getInstance().getEngine().getEngine().getNumeralBase().name().equals(directionTextData.getText())) {
directionTextPaint.setColor(resources.getColor(R.color.selected_angle_unit_text_color));
} else {
directionTextPaint.setColor(resources.getColor(R.color.default_text_color));

View File

@@ -1,243 +1,239 @@
/*
* 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.view;
import jscl.MathContext;
import org.jetbrains.annotations.NotNull;
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.model.*;
import org.solovyev.android.calculator.text.TextProcessor;
import org.solovyev.common.MutableObject;
import java.util.HashMap;
import java.util.Map;
/**
* User: serso
* Date: 10/12/11
* Time: 9:47 PM
*/
public class TextHighlighter implements TextProcessor<TextHighlighter.Result, String> {
private static final Map<String, String> nbFontAttributes = new HashMap<String, String>();
static {
nbFontAttributes.put("color", "#008000");
}
@NotNull
public final MathContext mathContext;
public static class Result implements CharSequence {
@NotNull
private final String string;
private final int offset;
public Result(@NotNull String string, int offset) {
this.string = string;
this.offset = offset;
}
@Override
public int length() {
return string.length();
}
@Override
public char charAt(int i) {
return string.charAt(i);
}
@Override
public CharSequence subSequence(int i, int i1) {
return string.subSequence(i, i1);
}
@Override
public String toString() {
return string;
}
public int getOffset() {
return offset;
}
}
private final int color;
private final int colorRed;
private final int colorGreen;
private final int colorBlue;
private final boolean formatNumber;
public TextHighlighter(int baseColor, boolean formatNumber, @NotNull MathContext mathContext) {
this.color = baseColor;
this.formatNumber = formatNumber;
this.mathContext = mathContext;
//this.colorRed = Color.red(baseColor);
this.colorRed = (baseColor >> 16) & 0xFF;
//this.colorGreen = Color.green(baseColor);
this.colorGreen = (color >> 8) & 0xFF;
//this.colorBlue = Color.blue(baseColor);
this.colorBlue = color & 0xFF;
}
@NotNull
@Override
public Result process(@NotNull String text) throws CalculatorParseException {
final String result;
int maxNumberOfOpenGroupSymbols = 0;
int numberOfOpenGroupSymbols = 0;
final StringBuilder text1 = new StringBuilder();
int resultOffset = 0;
final AbstractNumberBuilder numberBuilder;
if (!formatNumber) {
numberBuilder = new LiteNumberBuilder(CalculatorEngine.instance.getEngine());
} else {
numberBuilder = new NumberBuilder(CalculatorEngine.instance.getEngine());
}
for (int i = 0; i < text.length(); i++) {
MathType.Result mathType = MathType.getType(text, i, numberBuilder.isHexMode());
if (numberBuilder instanceof NumberBuilder) {
final MutableObject<Integer> numberOffset = new MutableObject<Integer>(0);
((NumberBuilder) numberBuilder).process(text1, mathType, numberOffset);
resultOffset += numberOffset.getObject();
} else {
((LiteNumberBuilder) numberBuilder).process(mathType);
}
final String match = mathType.getMatch();
switch (mathType.getMathType()) {
case open_group_symbol:
numberOfOpenGroupSymbols++;
maxNumberOfOpenGroupSymbols = Math.max(maxNumberOfOpenGroupSymbols, numberOfOpenGroupSymbols);
text1.append(text.charAt(i));
break;
case close_group_symbol:
numberOfOpenGroupSymbols--;
text1.append(text.charAt(i));
break;
case operator:
text1.append(match);
if (match.length() > 1) {
i += match.length() - 1;
}
break;
case function:
i = processHighlightedText(text1, i, match, "i", null);
break;
case constant:
i = processHighlightedText(text1, i, match, "b", null);
break;
case numeral_base:
i = processHighlightedText(text1, i, match, "b", null);
break;
default:
if (mathType.getMathType() == MathType.text || match.length() <= 1) {
text1.append(text.charAt(i));
} else {
text1.append(match);
i += match.length() - 1;
}
}
}
if (numberBuilder instanceof NumberBuilder) {
final MutableObject<Integer> numberOffset = new MutableObject<Integer>(0);
((NumberBuilder) numberBuilder).processNumber(text1, numberOffset);
resultOffset += numberOffset.getObject();
}
if (maxNumberOfOpenGroupSymbols > 0) {
final StringBuilder text2 = new StringBuilder();
String s = text1.toString();
int i = processBracketGroup(text2, s, 0, 0, maxNumberOfOpenGroupSymbols);
for (; i < s.length(); i++) {
text2.append(s.charAt(i));
}
//Log.d(AndroidCalculatorEditorView.class.getName(), text2.toString());
result = text2.toString();
} else {
result = text1.toString();
}
return new Result(result, resultOffset);
}
private int processHighlightedText(@NotNull StringBuilder result, int i, @NotNull String match, @NotNull String tag, @Nullable Map<String, String> tagAttributes) {
result.append("<").append(tag);
if (tagAttributes != null) {
for (Map.Entry<String, String> entry : tagAttributes.entrySet()) {
// attr1="attr1_value" attr2="attr2_value"
result.append(" ").append(entry.getKey()).append("=\"").append(entry.getValue()).append("\"");
}
}
result.append(">").append(match).append("</").append(tag).append(">");
if (match.length() > 1) {
return i + match.length() - 1;
} else {
return i;
}
}
private int processBracketGroup(@NotNull StringBuilder result, @NotNull String s, int i, int numberOfOpenings, int maxNumberOfGroups) {
result.append("<font color=\"").append(getColor(maxNumberOfGroups, numberOfOpenings)).append("\">");
for (; i < s.length(); i++) {
char ch = s.charAt(i);
if (MathType.open_group_symbol.getTokens().contains(String.valueOf(ch))) {
result.append(ch);
result.append("</font>");
i = processBracketGroup(result, s, i + 1, numberOfOpenings + 1, maxNumberOfGroups);
result.append("<font color=\"").append(getColor(maxNumberOfGroups, numberOfOpenings)).append("\">");
if (i < s.length() && MathType.close_group_symbol.getTokens().contains(String.valueOf(s.charAt(i)))) {
result.append(s.charAt(i));
}
} else if (MathType.close_group_symbol.getTokens().contains(String.valueOf(ch))) {
break;
} else {
result.append(ch);
}
}
result.append("</font>");
return i;
}
private String getColor(int totalNumberOfOpenings, int numberOfOpenings) {
double c = 0.8;
int offset = ((int) (255 * c)) * numberOfOpenings / (totalNumberOfOpenings + 1);
// for tests:
// innt result = Color.rgb(BASE_COLOUR_RED_COMPONENT - offset, BASE_COLOUR_GREEN_COMPONENT - offset, BASE_COLOUR_BLUE_COMPONENT - offset);
int result = (0xFF << 24) | ((colorRed - offset) << 16) | ((colorGreen - offset) << 8) | (colorBlue - offset);
return "#" + Integer.toHexString(result).substring(2);
}
}
/*
* 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.view;
import jscl.MathContext;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.*;
import org.solovyev.android.calculator.math.MathType;
import org.solovyev.android.calculator.text.TextProcessor;
import org.solovyev.common.MutableObject;
import java.util.HashMap;
import java.util.Map;
/**
* User: serso
* Date: 10/12/11
* Time: 9:47 PM
*/
public class TextHighlighter implements TextProcessor<TextHighlighter.Result, String> {
private static final Map<String, String> nbFontAttributes = new HashMap<String, String>();
static {
nbFontAttributes.put("color", "#008000");
}
@NotNull
public final MathContext mathContext;
public static class Result implements CharSequence {
@NotNull
private final String string;
private final int offset;
public Result(@NotNull String string, int offset) {
this.string = string;
this.offset = offset;
}
@Override
public int length() {
return string.length();
}
@Override
public char charAt(int i) {
return string.charAt(i);
}
@Override
public CharSequence subSequence(int i, int i1) {
return string.subSequence(i, i1);
}
@Override
public String toString() {
return string;
}
public int getOffset() {
return offset;
}
}
private final int color;
private final int colorRed;
private final int colorGreen;
private final int colorBlue;
private final boolean formatNumber;
public TextHighlighter(int baseColor, boolean formatNumber, @NotNull MathContext mathContext) {
this.color = baseColor;
this.formatNumber = formatNumber;
this.mathContext = mathContext;
//this.colorRed = Color.red(baseColor);
this.colorRed = (baseColor >> 16) & 0xFF;
//this.colorGreen = Color.green(baseColor);
this.colorGreen = (color >> 8) & 0xFF;
//this.colorBlue = Color.blue(baseColor);
this.colorBlue = color & 0xFF;
}
@NotNull
@Override
public Result process(@NotNull String text) throws CalculatorParseException {
final String result;
int maxNumberOfOpenGroupSymbols = 0;
int numberOfOpenGroupSymbols = 0;
final StringBuilder text1 = new StringBuilder();
int resultOffset = 0;
final AbstractNumberBuilder numberBuilder;
if (!formatNumber) {
numberBuilder = new LiteNumberBuilder(CalculatorLocatorImpl.getInstance().getEngine().getEngine());
} else {
numberBuilder = new NumberBuilder(CalculatorLocatorImpl.getInstance().getEngine().getEngine());
}
for (int i = 0; i < text.length(); i++) {
MathType.Result mathType = MathType.getType(text, i, numberBuilder.isHexMode());
if (numberBuilder instanceof NumberBuilder) {
final MutableObject<Integer> numberOffset = new MutableObject<Integer>(0);
((NumberBuilder) numberBuilder).process(text1, mathType, numberOffset);
resultOffset += numberOffset.getObject();
} else {
((LiteNumberBuilder) numberBuilder).process(mathType);
}
final String match = mathType.getMatch();
switch (mathType.getMathType()) {
case open_group_symbol:
numberOfOpenGroupSymbols++;
maxNumberOfOpenGroupSymbols = Math.max(maxNumberOfOpenGroupSymbols, numberOfOpenGroupSymbols);
text1.append(text.charAt(i));
break;
case close_group_symbol:
numberOfOpenGroupSymbols--;
text1.append(text.charAt(i));
break;
case operator:
text1.append(match);
if (match.length() > 1) {
i += match.length() - 1;
}
break;
case function:
i = processHighlightedText(text1, i, match, "i", null);
break;
case constant:
i = processHighlightedText(text1, i, match, "b", null);
break;
case numeral_base:
i = processHighlightedText(text1, i, match, "b", null);
break;
default:
if (mathType.getMathType() == MathType.text || match.length() <= 1) {
text1.append(text.charAt(i));
} else {
text1.append(match);
i += match.length() - 1;
}
}
}
if (numberBuilder instanceof NumberBuilder) {
final MutableObject<Integer> numberOffset = new MutableObject<Integer>(0);
((NumberBuilder) numberBuilder).processNumber(text1, numberOffset);
resultOffset += numberOffset.getObject();
}
if (maxNumberOfOpenGroupSymbols > 0) {
final StringBuilder text2 = new StringBuilder();
String s = text1.toString();
int i = processBracketGroup(text2, s, 0, 0, maxNumberOfOpenGroupSymbols);
for (; i < s.length(); i++) {
text2.append(s.charAt(i));
}
//Log.d(AndroidCalculatorEditorView.class.getName(), text2.toString());
result = text2.toString();
} else {
result = text1.toString();
}
return new Result(result, resultOffset);
}
private int processHighlightedText(@NotNull StringBuilder result, int i, @NotNull String match, @NotNull String tag, @Nullable Map<String, String> tagAttributes) {
result.append("<").append(tag);
if (tagAttributes != null) {
for (Map.Entry<String, String> entry : tagAttributes.entrySet()) {
// attr1="attr1_value" attr2="attr2_value"
result.append(" ").append(entry.getKey()).append("=\"").append(entry.getValue()).append("\"");
}
}
result.append(">").append(match).append("</").append(tag).append(">");
if (match.length() > 1) {
return i + match.length() - 1;
} else {
return i;
}
}
private int processBracketGroup(@NotNull StringBuilder result, @NotNull String s, int i, int numberOfOpenings, int maxNumberOfGroups) {
result.append("<font color=\"").append(getColor(maxNumberOfGroups, numberOfOpenings)).append("\">");
for (; i < s.length(); i++) {
char ch = s.charAt(i);
if (MathType.open_group_symbol.getTokens().contains(String.valueOf(ch))) {
result.append(ch);
result.append("</font>");
i = processBracketGroup(result, s, i + 1, numberOfOpenings + 1, maxNumberOfGroups);
result.append("<font color=\"").append(getColor(maxNumberOfGroups, numberOfOpenings)).append("\">");
if (i < s.length() && MathType.close_group_symbol.getTokens().contains(String.valueOf(s.charAt(i)))) {
result.append(s.charAt(i));
}
} else if (MathType.close_group_symbol.getTokens().contains(String.valueOf(ch))) {
break;
} else {
result.append(ch);
}
}
result.append("</font>");
return i;
}
private String getColor(int totalNumberOfOpenings, int numberOfOpenings) {
double c = 0.8;
int offset = ((int) (255 * c)) * numberOfOpenings / (totalNumberOfOpenings + 1);
// for tests:
// innt result = Color.rgb(BASE_COLOUR_RED_COMPONENT - offset, BASE_COLOUR_GREEN_COMPONENT - offset, BASE_COLOUR_BLUE_COMPONENT - offset);
int result = (0xFF << 24) | ((colorRed - offset) << 16) | ((colorGreen - offset) << 8) | (colorBlue - offset);
return "#" + Integer.toHexString(result).substring(2);
}
}