Merge branch 'dev-app-structure' into dev

Conflicts:
	android-app-core/src/main/java/org/solovyev/android/calculator/CalculatorButtons.java
	android-app/AndroidManifest.xml
	android-app/src/main/java/org/solovyev/android/calculator/about/CalculatorFragmentType.java
This commit is contained in:
Sergey Solovyev
2012-12-01 21:30:47 +04:00
698 changed files with 1528 additions and 1036 deletions

View File

@@ -0,0 +1,192 @@
/*
* Copyright (c) 2009-2011. Created by serso aka se.solovyev.
* For more information, please, contact se.solovyev@gmail.com
*/
package org.solovyev.android.calculator;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.text.Html;
import android.util.AttributeSet;
import android.util.TypedValue;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.core.R;
import org.solovyev.android.calculator.text.TextProcessor;
import org.solovyev.android.calculator.view.TextHighlighter;
import org.solovyev.android.view.AutoResizeTextView;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* User: serso
* Date: 9/17/11
* Time: 10:58 PM
*/
public class AndroidCalculatorDisplayView extends AutoResizeTextView implements CalculatorDisplayView {
/*
**********************************************************************
*
* STATIC FIELDS
*
**********************************************************************
*/
@NotNull
private final static TextProcessor<TextHighlighter.Result, String> textHighlighter = new TextHighlighter(Color.WHITE, false);
/*
**********************************************************************
*
* FIELDS
*
**********************************************************************
*/
@NotNull
private volatile CalculatorDisplayViewState state = CalculatorDisplayViewStateImpl.newDefaultInstance();
private volatile boolean viewStateChange = false;
@NotNull
private final Object lock = new Object();
@NotNull
private final Handler uiHandler = new Handler();
@NotNull
private final ExecutorService bgExecutor = Executors.newSingleThreadExecutor();
private volatile boolean initialized = false;
/*
**********************************************************************
*
* CONSTRUCTORS
*
**********************************************************************
*/
public AndroidCalculatorDisplayView(Context context) {
super(context);
}
public AndroidCalculatorDisplayView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public AndroidCalculatorDisplayView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
/*
**********************************************************************
*
* METHODS
*
**********************************************************************
*/
@Override
public void setState(@NotNull final CalculatorDisplayViewState state) {
uiHandler.post(new Runnable() {
@Override
public void run() {
synchronized (lock) {
try {
viewStateChange = true;
final CharSequence text = prepareText(state.getStringResult(), state.isValid());
AndroidCalculatorDisplayView.this.state = state;
if (state.isValid()) {
setTextColor(getResources().getColor(R.color.cpp_default_text_color));
setText(text);
adjustTextSize();
} else {
// update text in order to get rid of HTML tags
setText(getText().toString());
setTextColor(getResources().getColor(R.color.cpp_display_error_text_color));
// error messages are never shown -> just greyed out text (error message will be shown on click)
//setText(state.getErrorMessage());
//redraw();
}
} finally {
viewStateChange = false;
}
}
}
});
}
@NotNull
@Override
public CalculatorDisplayViewState getState() {
synchronized (lock) {
return this.state;
}
}
@Nullable
private static CharSequence prepareText(@Nullable String text, boolean valid) {
CharSequence result;
if (valid && text != null) {
//Log.d(this.getClass().getName(), text);
try {
final TextHighlighter.Result processedText = textHighlighter.process(text);
text = processedText.toString();
result = Html.fromHtml(text);
} catch (CalculatorParseException e) {
result = text;
}
} else {
result = text;
}
return result;
}
private void adjustTextSize() {
// todo serso: think where to move it (keep in mind org.solovyev.android.view.AutoResizeTextView.resetTextSize())
setAddEllipsis(false);
setMinTextSize(10);
resizeText();
}
public synchronized void init(@NotNull Context context) {
this.init(context, true);
}
public synchronized void init(@NotNull Context context, boolean fromApp) {
if (!initialized) {
if (fromApp) {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
final CalculatorPreferences.Gui.Layout layout = CalculatorPreferences.Gui.getLayout(preferences);
if ( layout == CalculatorPreferences.Gui.Layout.main_calculator_mobile ) {
setTextSize(TypedValue.COMPLEX_UNIT_SP, getResources().getDimension(R.dimen.cpp_display_text_size_mobile));
}
this.setOnClickListener(new CalculatorDisplayOnClickListener(context));
}
this.initialized = true;
}
}
}

View File

@@ -0,0 +1,221 @@
/*
* Copyright (c) 2009-2011. Created by serso aka se.solovyev.
* For more information, please, contact se.solovyev@gmail.com
*/
package org.solovyev.android.calculator;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ContextMenu;
import android.widget.EditText;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.text.TextProcessor;
import org.solovyev.android.calculator.view.TextHighlighter;
import org.solovyev.android.prefs.BooleanPreference;
import org.solovyev.common.collections.CollectionsUtils;
/**
* User: serso
* Date: 9/17/11
* Time: 12:25 AM
*/
public class AndroidCalculatorEditorView extends EditText implements SharedPreferences.OnSharedPreferenceChangeListener, CalculatorEditorView {
@NotNull
private static final BooleanPreference colorDisplay = new BooleanPreference("org.solovyev.android.calculator.CalculatorModel_color_display", true);
private volatile boolean initialized = false;
private boolean highlightText = true;
@NotNull
private final static TextProcessor<TextHighlighter.Result, String> textHighlighter = new TextHighlighter(Color.WHITE, false);
@NotNull
private volatile CalculatorEditorViewState viewState = CalculatorEditorViewStateImpl.newDefaultInstance();
private volatile boolean viewStateChange = false;
@Nullable
private final Object viewLock = new Object();
@NotNull
private final Handler uiHandler = new Handler();
public AndroidCalculatorEditorView(Context context) {
super(context);
}
public AndroidCalculatorEditorView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public AndroidCalculatorEditorView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public boolean onCheckIsTextEditor() {
// NOTE: code below can be used carefully and should not be copied without special intention
// The main purpose of code is to disable soft input (virtual keyboard) but leave all the TextEdit functionality, like cursor, scrolling, copy/paste menu etc
if (Build.VERSION.SDK_INT >= 11) {
// fix for missing cursor in android 3 and higher
try {
// IDEA: return false always except if method was called from TextView.isCursorVisible() method
for (StackTraceElement stackTraceElement : CollectionsUtils.asList(Thread.currentThread().getStackTrace())) {
if ("isCursorVisible".equals(stackTraceElement.getMethodName())) {
return true;
}
}
} catch (RuntimeException e) {
// just in case...
}
return false;
} else {
return false;
}
}
@Override
protected void onCreateContextMenu(ContextMenu menu) {
super.onCreateContextMenu(menu);
menu.removeItem(android.R.id.selectAll);
}
@Nullable
private CharSequence prepareText(@NotNull String text, boolean highlightText) {
CharSequence result;
if (highlightText) {
try {
final TextHighlighter.Result processesText = textHighlighter.process(text);
assert processesText.getOffset() == 0;
result = Html.fromHtml(processesText.toString());
} catch (CalculatorParseException e) {
// set raw text
result = text;
Log.e(this.getClass().getName(), e.getMessage(), e);
}
} else {
result = text;
}
return result;
}
public boolean isHighlightText() {
return highlightText;
}
public void setHighlightText(boolean highlightText) {
this.highlightText = highlightText;
Locator.getInstance().getEditor().updateViewState();
}
@Override
public void onSharedPreferenceChanged(SharedPreferences preferences, String key) {
if (colorDisplay.getKey().equals(key)) {
this.setHighlightText(colorDisplay.getPreference(preferences));
}
}
public synchronized void init(@NotNull Context context) {
if (!initialized) {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
preferences.registerOnSharedPreferenceChangeListener(this);
this.addTextChangedListener(new TextWatcherImpl());
onSharedPreferenceChanged(preferences, colorDisplay.getKey());
initialized = true;
}
}
@Override
public void setState(@NotNull final CalculatorEditorViewState viewState) {
if (viewLock != null) {
synchronized (viewLock) {
final CharSequence text = prepareText(viewState.getText(), highlightText);
uiHandler.post(new Runnable() {
@Override
public void run() {
final AndroidCalculatorEditorView editorView = AndroidCalculatorEditorView.this;
synchronized (viewLock) {
try {
editorView.viewStateChange = true;
editorView.viewState = viewState;
editorView.setText(text, BufferType.EDITABLE);
editorView.setSelection(viewState.getSelection());
} finally {
editorView.viewStateChange = false;
}
}
}
});
}
}
}
@Override
protected void onSelectionChanged(int selStart, int selEnd) {
if (viewLock != null) {
synchronized (viewLock) {
if (!viewStateChange) {
// external text change => need to notify editor
super.onSelectionChanged(selStart, selEnd);
Locator.getInstance().getEditor().setSelection(selStart);
}
}
}
}
public void handleTextChange(Editable s) {
if (viewLock != null) {
synchronized (viewLock) {
if (!viewStateChange) {
// external text change => need to notify editor
Locator.getInstance().getEditor().setText(String.valueOf(s));
}
}
}
}
private final class TextWatcherImpl implements TextWatcher {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
handleTextChange(s);
}
}
}

View File

@@ -0,0 +1,66 @@
package org.solovyev.android.calculator;
import android.app.Application;
import org.jetbrains.annotations.NotNull;
import org.solovyev.common.DelayedExecutor;
/**
* User: serso
* Date: 12/1/12
* Time: 3:58 PM
*/
public final class App {
/*
**********************************************************************
*
* STATIC
*
**********************************************************************
*/
@NotNull
public static final App instance = new App();
/*
**********************************************************************
*
* FIELDS
*
**********************************************************************
*/
@NotNull
private volatile Application application;
@NotNull
private volatile DelayedExecutor uiThreadExecutor;
private volatile boolean initialized;
private App() {
}
@NotNull
public static App getInstance() {
return instance;
}
@NotNull
public Application getApplication() {
return application;
}
@NotNull
public DelayedExecutor getUiThreadExecutor() {
return uiThreadExecutor;
}
void init(@NotNull Application application) {
if (!initialized) {
this.application = application;
this.uiThreadExecutor = new UiThreadExecutor();
this.initialized = true;
}
}
}

View File

@@ -0,0 +1,129 @@
package org.solovyev.android.calculator;
import android.content.Context;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.core.R;
import java.util.HashMap;
import java.util.Map;
/**
* User: serso
* Date: 10/20/12
* Time: 12:05 AM
*/
public enum CalculatorButton {
/*digits*/
one(R.id.cpp_button_1, "1"),
two(R.id.cpp_button_2, "2"),
three(R.id.cpp_button_3, "3"),
four(R.id.cpp_button_4, "4"),
five(R.id.cpp_button_5, "5"),
six(R.id.cpp_button_6, "6"),
seven(R.id.cpp_button_7, "7"),
eight(R.id.cpp_button_8, "8"),
nine(R.id.cpp_button_9, "9"),
zero(R.id.cpp_button_0, "0"),
period(R.id.cpp_button_period, "."),
brackets(R.id.cpp_button_round_brackets, "()"),
settings(R.id.cpp_button_settings, CalculatorSpecialButton.settings_detached),
like(R.id.cpp_button_like, CalculatorSpecialButton.like),
/*last row*/
left(R.id.cpp_button_left, CalculatorSpecialButton.cursor_left),
right(R.id.cpp_button_right, CalculatorSpecialButton.cursor_right),
vars(R.id.cpp_button_vars, CalculatorSpecialButton.vars_detached),
functions(R.id.cpp_button_functions, CalculatorSpecialButton.functions_detached),
app(R.id.cpp_button_app, CalculatorSpecialButton.open_app),
history(R.id.cpp_button_history, CalculatorSpecialButton.history_detached),
/*operations*/
multiplication(R.id.cpp_button_multiplication, "*"),
division(R.id.cpp_button_division, "/"),
plus(R.id.cpp_button_plus, "+"),
subtraction(R.id.cpp_button_subtraction, "-"),
percent(R.id.cpp_button_percent, "%"),
power(R.id.cpp_button_power, "^"),
/*last column*/
clear(R.id.cpp_button_clear, CalculatorSpecialButton.clear),
erase(R.id.cpp_button_erase, CalculatorSpecialButton.erase, CalculatorSpecialButton.clear),
copy(R.id.cpp_button_copy, CalculatorSpecialButton.copy),
paste(R.id.cpp_button_paste, CalculatorSpecialButton.paste),
/*equals*/
equals(R.id.cpp_button_equals, CalculatorSpecialButton.equals);
private final int buttonId;
@NotNull
private final String onClickText;
@Nullable
private final String onLongClickText;
@NotNull
private static Map<Integer, CalculatorButton> buttonsByIds = new HashMap<Integer, CalculatorButton>();
CalculatorButton(int buttonId, @NotNull CalculatorSpecialButton onClickButton, @Nullable CalculatorSpecialButton onLongClickButton) {
this(buttonId, onClickButton.getActionCode(), onLongClickButton == null ? null : onLongClickButton.getActionCode());
}
CalculatorButton(int buttonId, @NotNull CalculatorSpecialButton onClickButton) {
this(buttonId, onClickButton, null);
}
CalculatorButton(int buttonId, @NotNull String onClickText, @Nullable String onLongClickText) {
this.buttonId = buttonId;
this.onClickText = onClickText;
this.onLongClickText = onLongClickText;
}
CalculatorButton(int buttonId, @NotNull String onClickText) {
this(buttonId, onClickText, null);
}
public void onLongClick(@NotNull Context context) {
Locator.getInstance().getNotifier().showDebugMessage("Calculator++ Widget", "Button pressed: " + onLongClickText);
if (onLongClickText != null) {
Locator.getInstance().getKeyboard().buttonPressed(onLongClickText);
}
}
public void onClick(@NotNull Context context) {
Locator.getInstance().getNotifier().showDebugMessage("Calculator++ Widget", "Button pressed: " + onClickText);
Locator.getInstance().getKeyboard().buttonPressed(onClickText);
}
@Nullable
public static CalculatorButton getById(int buttonId) {
initButtonsByIdsMap();
return buttonsByIds.get(buttonId);
}
private static void initButtonsByIdsMap() {
if ( buttonsByIds.isEmpty() ) {
// if not initialized
final CalculatorButton[] calculatorButtons = values();
final Map<Integer, CalculatorButton> localButtonsByIds = new HashMap<Integer, CalculatorButton>(calculatorButtons.length);
for (CalculatorButton calculatorButton : calculatorButtons) {
localButtonsByIds.put(calculatorButton.getButtonId(), calculatorButton);
}
buttonsByIds = localButtonsByIds;
}
}
public int getButtonId() {
return buttonId;
}
}

View File

@@ -0,0 +1,263 @@
package org.solovyev.android.calculator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.preference.PreferenceManager;
import android.util.Log;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.RemoteViews;
import jscl.AngleUnit;
import jscl.NumeralBase;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.AndroidUtils;
import org.solovyev.android.calculator.core.R;
import org.solovyev.android.calculator.matrix.CalculatorMatrixActivity;
import org.solovyev.android.calculator.model.AndroidCalculatorEngine;
import org.solovyev.android.calculator.view.AngleUnitsButton;
import org.solovyev.android.calculator.view.NumeralBasesButton;
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;
/**
* User: serso
* Date: 9/28/12
* Time: 12:06 AM
*/
public final class CalculatorButtons {
private CalculatorButtons () {
}
public static void processButtons(@NotNull CalculatorPreferences.Gui.Theme theme,
@NotNull CalculatorPreferences.Gui.Layout layout,
@NotNull View root) {
if ( layout == CalculatorPreferences.Gui.Layout.main_calculator_mobile ) {
final float textSize = root.getContext().getResources().getDimension(R.dimen.cpp_keyboard_button_text_size_mobile);
AndroidUtils.processViewsOfType(root, DragButton.class, new AndroidUtils.ViewProcessor<DragButton>() {
@Override
public void process(@NotNull DragButton button) {
button.setTextSize(TypedValue.COMPLEX_UNIT_DIP, textSize);
}
});
}
}
static void initMultiplicationButton(@NotNull View root) {
final View multiplicationButton = root.findViewById(R.id.cpp_button_multiplication);
if ( multiplicationButton instanceof Button) {
((Button) multiplicationButton).setText(Locator.getInstance().getEngine().getMultiplicationSign());
}
}
public static void initMultiplicationButton(@NotNull RemoteViews views) {
views.setTextViewText(R.id.cpp_button_multiplication, Locator.getInstance().getEngine().getMultiplicationSign());
}
public static void toggleEqualsButton(@Nullable SharedPreferences preferences,
@NotNull Activity activity) {
preferences = preferences == null ? PreferenceManager.getDefaultSharedPreferences(activity) : preferences;
final boolean large = AndroidUtils.isLayoutSizeAtLeast(Configuration.SCREENLAYOUT_SIZE_LARGE, activity.getResources().getConfiguration()) &&
CalculatorPreferences.Gui.getLayout(preferences) != CalculatorPreferences.Gui.Layout.main_calculator_mobile;
if (!large) {
if (AndroidUtils.getScreenOrientation(activity) == Configuration.ORIENTATION_PORTRAIT
|| !CalculatorPreferences.Gui.autoOrientation.getPreference(preferences)) {
final DragButton equalsButton = (DragButton)activity.findViewById(R.id.cpp_button_equals);
if (equalsButton != null) {
if (CalculatorPreferences.Gui.showEqualsButton.getPreference(preferences)) {
equalsButton.setVisibility(View.VISIBLE);
} else {
equalsButton.setVisibility(View.GONE);
}
}
}
}
}
/*
**********************************************************************
*
* STATIC CLASSES
*
**********************************************************************
*/
static class RoundBracketsDragProcessor implements SimpleOnDragListener.DragProcessor {
@Override
public boolean processDragEvent(@NotNull DragDirection dragDirection, @NotNull DragButton dragButton, @NotNull Point2d startPoint2d, @NotNull MotionEvent motionEvent) {
final boolean result;
if (dragDirection == DragDirection.left) {
getKeyboard().roundBracketsButtonPressed();
result = true;
} else {
result = new DigitButtonDragProcessor(getKeyboard()).processDragEvent(dragDirection, dragButton, startPoint2d, motionEvent);
}
return result;
}
}
@NotNull
private static CalculatorKeyboard getKeyboard() {
return Locator.getInstance().getKeyboard();
}
static class VarsDragProcessor implements SimpleOnDragListener.DragProcessor {
@NotNull
private Context context;
VarsDragProcessor(@NotNull Context context) {
this.context = context;
}
@Override
public boolean processDragEvent(@NotNull DragDirection dragDirection,
@NotNull DragButton dragButton,
@NotNull Point2d startPoint2d,
@NotNull MotionEvent motionEvent) {
boolean result = false;
if (dragDirection == DragDirection.up) {
Locator.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.show_create_var_dialog, null);
result = true;
} else if ( dragDirection == DragDirection.down ) {
context.startActivity(new Intent(context, CalculatorMatrixActivity.class));
result = true;
}
return result;
}
}
static class AngleUnitsChanger implements SimpleOnDragListener.DragProcessor {
@NotNull
private final DigitButtonDragProcessor processor;
@NotNull
private final Context context;
AngleUnitsChanger(@NotNull Context context) {
this.context = context;
this.processor = new DigitButtonDragProcessor(Locator.getInstance().getKeyboard());
}
@Override
public boolean processDragEvent(@NotNull DragDirection dragDirection,
@NotNull DragButton dragButton,
@NotNull Point2d startPoint2d,
@NotNull MotionEvent motionEvent) {
boolean result = false;
if (dragButton instanceof AngleUnitsButton) {
if (dragDirection != DragDirection.left) {
final String directionText = ((AngleUnitsButton) dragButton).getText(dragDirection);
if (directionText != null) {
try {
final AngleUnit angleUnits = AngleUnit.valueOf(directionText);
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
final AngleUnit oldAngleUnits = AndroidCalculatorEngine.Preferences.angleUnit.getPreference(preferences);
if (oldAngleUnits != angleUnits) {
Locator.getInstance().getPreferenceService().setAngleUnits(angleUnits);
}
result = true;
} catch (IllegalArgumentException e) {
Log.d(this.getClass().getName(), "Unsupported angle units: " + directionText);
}
}
} else if (dragDirection == DragDirection.left) {
result = processor.processDragEvent(dragDirection, dragButton, startPoint2d, motionEvent);
}
}
return result;
}
}
static class NumeralBasesChanger implements SimpleOnDragListener.DragProcessor {
@NotNull
private final Context context;
NumeralBasesChanger(@NotNull Context context) {
this.context = context;
}
@Override
public boolean processDragEvent(@NotNull DragDirection dragDirection,
@NotNull DragButton dragButton,
@NotNull Point2d startPoint2d,
@NotNull MotionEvent motionEvent) {
boolean result = false;
if (dragButton instanceof NumeralBasesButton) {
final String directionText = ((NumeralBasesButton) dragButton).getText(dragDirection);
if (directionText != null) {
try {
final NumeralBase numeralBase = NumeralBase.valueOf(directionText);
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
final NumeralBase oldNumeralBase = AndroidCalculatorEngine.Preferences.numeralBase.getPreference(preferences);
if (oldNumeralBase != numeralBase) {
Locator.getInstance().getPreferenceService().setNumeralBase(numeralBase);
}
result = true;
} catch (IllegalArgumentException e) {
Log.d(this.getClass().getName(), "Unsupported numeral base: " + directionText);
}
}
}
return result;
}
}
static class FunctionsDragProcessor implements SimpleOnDragListener.DragProcessor {
@NotNull
private Context context;
FunctionsDragProcessor(@NotNull Context context) {
this.context = context;
}
@Override
public boolean processDragEvent(@NotNull DragDirection dragDirection,
@NotNull DragButton dragButton,
@NotNull Point2d startPoint2d,
@NotNull MotionEvent motionEvent) {
boolean result = false;
if (dragDirection == DragDirection.up) {
Locator.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.show_create_function_dialog, null);
result = true;
}
return result;
}
}
}

View File

@@ -0,0 +1,118 @@
package org.solovyev.android.calculator;
import android.content.Context;
import jscl.math.Generic;
import jscl.math.function.Constant;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.core.R;
import org.solovyev.android.calculator.jscl.JsclOperation;
import org.solovyev.android.calculator.plot.PlotInput;
import org.solovyev.android.calculator.view.NumeralBaseConverterDialog;
import org.solovyev.android.menu.LabeledMenuItem;
import org.solovyev.common.collections.CollectionsUtils;
/**
* 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) {
Locator.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(CalculatorUtils.getNotSystemConstants(generic));
assert constant != null;
Locator.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.plot_graph, PlotInput.newInstance(generic, constant));
}
@Override
protected boolean isItemVisibleFor(@NotNull Generic generic, @NotNull JsclOperation operation) {
return CalculatorUtils.isPlotPossible(generic, operation);
}
};
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

@@ -0,0 +1,53 @@
package org.solovyev.android.calculator;
import android.content.Context;
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 Context context;
public CalculatorDisplayOnClickListener(@NotNull Context context) {
this.context = context;
}
@Override
public void onClick(View v) {
if (v instanceof CalculatorDisplayView) {
final CalculatorDisplay cd = Locator.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(context, MenuImpl.newInstance(filteredMenuItems)).create(displayViewState).show();
}
} else {
final String errorMessage = displayViewState.getErrorMessage();
if (errorMessage != null) {
Locator.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.show_evaluation_error, errorMessage);
}
}
}
}
}

View File

@@ -0,0 +1,212 @@
package org.solovyev.android.calculator;
import android.content.SharedPreferences;
import jscl.AngleUnit;
import jscl.NumeralBase;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.AndroidUtils;
import org.solovyev.android.calculator.math.MathType;
import org.solovyev.android.calculator.model.AndroidCalculatorEngine;
import org.solovyev.android.calculator.plot.GraphLineColor;
import org.solovyev.android.prefs.*;
import org.solovyev.android.view.VibratorContainer;
import java.text.DecimalFormatSymbols;
import java.util.Locale;
/**
* User: serso
* Date: 4/20/12
* Time: 12:42 PM
*/
public final class CalculatorPreferences {
private CalculatorPreferences() {
throw new AssertionError();
}
public static final Preference<Integer> appVersion = new IntegerPreference("application.version", -1);
public static final Preference<Integer> appOpenedCounter = new IntegerPreference("app_opened_counter", 0);
public static class OnscreenCalculator {
public static final Preference<Boolean> startOnBoot = new BooleanPreference("onscreen_start_on_boot", false);
}
public static class Calculations {
public static final Preference<Boolean> calculateOnFly = new BooleanPreference("calculations_calculate_on_fly", true);
public static final Preference<Boolean> showCalculationMessagesDialog = new BooleanPreference("show_calculation_messages_dialog", true);
public static final Preference<NumeralBase> preferredNumeralBase = StringPreference.newInstance("preferred_numeral_base", AndroidCalculatorEngine.Preferences.numeralBase.getDefaultValue(), NumeralBase.class);
public static final Preference<AngleUnit> preferredAngleUnits = StringPreference.newInstance("preferred_angle_units", AndroidCalculatorEngine.Preferences.angleUnit.getDefaultValue(), AngleUnit.class);
public static final Preference<Long> lastPreferredPreferencesCheck = new LongPreference("preferred_preferences_check_time", 0L);
}
public static class Gui {
public static final Preference<Theme> theme = StringPreference.newInstance("org.solovyev.android.calculator.CalculatorActivity_calc_theme", Theme.metro_blue_theme, Theme.class);
public static final Preference<Layout> layout = StringPreference.newInstance("org.solovyev.android.calculator.CalculatorActivity_calc_layout", Layout.main_calculator, Layout.class);
public static final Preference<Boolean> feedbackWindowShown = new BooleanPreference("feedback_window_shown", false);
public static final Preference<Boolean> notesppAnnounceShown = new BooleanPreference("notespp_announce_shown", false);
public static final Preference<Boolean> showReleaseNotes = new BooleanPreference("org.solovyev.android.calculator.CalculatorActivity_show_release_notes", true);
public static final Preference<Boolean> usePrevAsBack = new BooleanPreference("org.solovyev.android.calculator.CalculatorActivity_use_back_button_as_prev", false);
public static final Preference<Boolean> showEqualsButton = new BooleanPreference("showEqualsButton", true);
public static final Preference<Boolean> autoOrientation = new BooleanPreference("autoOrientation", true);
public static final Preference<Boolean> hideNumeralBaseDigits = new BooleanPreference("hideNumeralBaseDigits", true);
@NotNull
public static Theme getTheme(@NotNull SharedPreferences preferences) {
return theme.getPreferenceNoError(preferences);
}
@NotNull
public static Layout getLayout(@NotNull SharedPreferences preferences) {
return layout.getPreferenceNoError(preferences);
}
public static enum Theme {
default_theme(ThemeType.other, R.style.cpp_gray_theme),
violet_theme(ThemeType.other, R.style.cpp_violet_theme),
light_blue_theme(ThemeType.other, R.style.cpp_light_blue_theme),
metro_blue_theme(ThemeType.metro, R.style.cpp_metro_blue_theme),
metro_purple_theme(ThemeType.metro, R.style.cpp_metro_purple_theme),
metro_green_theme(ThemeType.metro, R.style.cpp_metro_green_theme);
@NotNull
private final ThemeType themeType;
@NotNull
private final Integer themeId;
Theme(@NotNull ThemeType themeType, @NotNull Integer themeId) {
this.themeType = themeType;
this.themeId = themeId;
}
@NotNull
public ThemeType getThemeType() {
return themeType;
}
@NotNull
public Integer getThemeId() {
return themeId;
}
}
public static enum ThemeType {
metro,
other
}
public static enum Layout {
main_calculator(R.layout.main_calculator),
main_calculator_mobile(R.layout.main_calculator_mobile),
// not used anymore
@Deprecated
main_cellphone(R.layout.main_calculator),
simple(R.layout.main_calculator);
private final int layoutId;
Layout(int layoutId) {
this.layoutId = layoutId;
}
public int getLayoutId() {
return layoutId;
}
}
}
public static class Graph {
public static final Preference<Boolean> interpolate = new BooleanPreference("graph_interpolate", true);
public static final Preference<GraphLineColor> lineColorReal = StringPreference.newInstance("graph_line_color_real", GraphLineColor.white, GraphLineColor.class);
public static final Preference<GraphLineColor> lineColorImag = StringPreference.newInstance("graph_line_color_imag", GraphLineColor.blue, GraphLineColor.class);
}
public static class History {
public static final Preference<Boolean> showIntermediateCalculations = new BooleanPreference("history_show_intermediate_calculations", false);
}
static void setDefaultValues(@NotNull SharedPreferences preferences) {
if (!AndroidCalculatorEngine.Preferences.groupingSeparator.isSet(preferences)) {
final Locale locale = Locale.getDefault();
if (locale != null) {
final DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols(locale);
int index = MathType.grouping_separator.getTokens().indexOf(String.valueOf(decimalFormatSymbols.getGroupingSeparator()));
final String groupingSeparator;
if (index >= 0) {
groupingSeparator = MathType.grouping_separator.getTokens().get(index);
} else {
groupingSeparator = " ";
}
AndroidCalculatorEngine.Preferences.groupingSeparator.putPreference(preferences, groupingSeparator);
}
}
if (!AndroidCalculatorEngine.Preferences.angleUnit.isSet(preferences)) {
AndroidCalculatorEngine.Preferences.angleUnit.putDefault(preferences);
}
if (!AndroidCalculatorEngine.Preferences.numeralBase.isSet(preferences)) {
AndroidCalculatorEngine.Preferences.numeralBase.putDefault(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
AndroidCalculatorEngine.Preferences.multiplicationSign.putPreference(preferences, "*");
}
}
applyDefaultPreference(preferences, Gui.theme);
applyDefaultPreference(preferences, Gui.layout);
if (Gui.layout.getPreference(preferences) == Gui.Layout.main_cellphone) {
Gui.layout.putDefault(preferences);
}
applyDefaultPreference(preferences, Gui.feedbackWindowShown);
applyDefaultPreference(preferences, Gui.notesppAnnounceShown);
applyDefaultPreference(preferences, Gui.showReleaseNotes);
applyDefaultPreference(preferences, Gui.usePrevAsBack);
applyDefaultPreference(preferences, Gui.showEqualsButton);
applyDefaultPreference(preferences, Gui.autoOrientation);
applyDefaultPreference(preferences, Gui.hideNumeralBaseDigits);
applyDefaultPreference(preferences, Graph.interpolate);
applyDefaultPreference(preferences, Graph.lineColorImag);
applyDefaultPreference(preferences, Graph.lineColorReal);
applyDefaultPreference(preferences, History.showIntermediateCalculations);
applyDefaultPreference(preferences, Calculations.calculateOnFly);
applyDefaultPreference(preferences, Calculations.preferredAngleUnits);
applyDefaultPreference(preferences, Calculations.preferredNumeralBase);
// renew value after each application start
Calculations.showCalculationMessagesDialog.putDefault(preferences);
Calculations.lastPreferredPreferencesCheck.putDefault(preferences);
if (!VibratorContainer.Preferences.hapticFeedbackEnabled.isSet(preferences)) {
VibratorContainer.Preferences.hapticFeedbackEnabled.putPreference(preferences, true);
}
if (!VibratorContainer.Preferences.hapticFeedbackDuration.isSet(preferences)) {
VibratorContainer.Preferences.hapticFeedbackDuration.putPreference(preferences, 60L);
}
}
private static void applyDefaultPreference(@NotNull SharedPreferences preferences, @NotNull Preference<?> preference) {
if (!preference.isSet(preferences)) {
preference.putDefault(preferences);
}
}
}

View File

@@ -0,0 +1,52 @@
package org.solovyev.android.calculator;
import android.content.Context;
import jscl.NumeralBase;
import jscl.math.Generic;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.jscl.JsclOperation;
import org.solovyev.android.menu.AMenuItem;
/**
* User: serso
* Date: 9/21/12
* Time: 12:11 AM
*/
enum ConversionMenuItem implements AMenuItem<CalculatorDisplayViewState> {
convert_to_bin(NumeralBase.bin),
convert_to_dec(NumeralBase.dec),
convert_to_hex(NumeralBase.hex);
@NotNull
private final NumeralBase toNumeralBase;
ConversionMenuItem(@NotNull NumeralBase toNumeralBase) {
this.toNumeralBase = toNumeralBase;
}
protected boolean isItemVisibleFor(@NotNull Generic generic, @NotNull JsclOperation operation) {
boolean result = false;
if (operation == JsclOperation.numeric) {
if (generic.getConstants().isEmpty()) {
// conversion possible => return true
final NumeralBase fromNumeralBase = Locator.getInstance().getEngine().getNumeralBase();
if (fromNumeralBase != toNumeralBase) {
result = Locator.getInstance().getCalculator().isConversionPossible(generic, fromNumeralBase, this.toNumeralBase);
}
}
}
return result;
}
@Override
public void onClick(@NotNull CalculatorDisplayViewState data, @NotNull Context context) {
final Generic result = data.getResult();
if (result != null) {
Locator.getInstance().getCalculator().convert(result, this.toNumeralBase);
}
}
}

View File

@@ -0,0 +1,37 @@
/*
* Copyright (c) 2009-2011. Created by serso aka se.solovyev.
* For more information, please, contact se.solovyev@gmail.com
*/
package org.solovyev.android.calculator;
import android.view.MotionEvent;
import org.jetbrains.annotations.NotNull;
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;
/**
* User: serso
* Date: 9/16/11
* Time: 11:48 PM
*/
public class DigitButtonDragProcessor implements SimpleOnDragListener.DragProcessor {
@NotNull
private CalculatorKeyboard calculatorKeyboard;
public DigitButtonDragProcessor(@NotNull CalculatorKeyboard calculatorKeyboard) {
this.calculatorKeyboard = calculatorKeyboard;
}
@Override
public boolean processDragEvent(@NotNull DragDirection dragDirection, @NotNull DragButton dragButton, @NotNull Point2d startPoint2d, @NotNull MotionEvent motionEvent) {
assert dragButton instanceof DirectionDragButton;
calculatorKeyboard.buttonPressed(((DirectionDragButton) dragButton).getText(dragDirection));
return true;
}
}

View File

@@ -0,0 +1,107 @@
package org.solovyev.android.calculator;
import android.os.Parcel;
import android.os.Parcelable;
import jscl.math.Generic;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.jscl.JsclOperation;
/**
* User: serso
* Date: 11/18/12
* Time: 1:40 PM
*/
public final class ParcelableCalculatorDisplayViewState implements CalculatorDisplayViewState, Parcelable {
public static final Creator<ParcelableCalculatorDisplayViewState> CREATOR = new Creator<ParcelableCalculatorDisplayViewState>() {
@Override
public ParcelableCalculatorDisplayViewState createFromParcel(@NotNull Parcel in) {
return ParcelableCalculatorDisplayViewState.fromParcel(in);
}
@Override
public ParcelableCalculatorDisplayViewState[] newArray(int size) {
return new ParcelableCalculatorDisplayViewState[size];
}
};
@NotNull
private static ParcelableCalculatorDisplayViewState fromParcel(@NotNull Parcel in) {
final int selection = in.readInt();
final boolean valid = in.readInt() == 1;
final String stringResult = in.readString();
final String errorMessage = in.readString();
final JsclOperation operation = (JsclOperation) in.readSerializable();
CalculatorDisplayViewState calculatorDisplayViewState;
if (valid) {
calculatorDisplayViewState = CalculatorDisplayViewStateImpl.newValidState(operation, null, stringResult, selection);
} else {
calculatorDisplayViewState = CalculatorDisplayViewStateImpl.newErrorState(operation, errorMessage);
}
return new ParcelableCalculatorDisplayViewState(calculatorDisplayViewState);
}
@NotNull
private CalculatorDisplayViewState viewState;
public ParcelableCalculatorDisplayViewState(@NotNull CalculatorDisplayViewState viewState) {
this.viewState = viewState;
}
@Override
@NotNull
public String getText() {
return viewState.getText();
}
@Override
public int getSelection() {
return viewState.getSelection();
}
@Override
@Nullable
public Generic getResult() {
return viewState.getResult();
}
@Override
public boolean isValid() {
return viewState.isValid();
}
@Override
@Nullable
public String getErrorMessage() {
return viewState.getErrorMessage();
}
@Override
@NotNull
public JsclOperation getOperation() {
return viewState.getOperation();
}
@Override
@Nullable
public String getStringResult() {
return viewState.getStringResult();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(@NotNull Parcel out, int flags) {
out.writeInt(viewState.getSelection());
out.writeInt(viewState.isValid() ? 1 : 0);
out.writeString(viewState.getStringResult());
out.writeString(viewState.getErrorMessage());
out.writeSerializable(viewState.getOperation());
}
}

View File

@@ -0,0 +1,61 @@
package org.solovyev.android.calculator;
import android.os.Parcel;
import android.os.Parcelable;
import org.jetbrains.annotations.NotNull;
/**
* User: serso
* Date: 11/18/12
* Time: 1:40 PM
*/
public final class ParcelableCalculatorEditorViewState implements CalculatorEditorViewState, Parcelable {
public static final Creator<ParcelableCalculatorEditorViewState> CREATOR = new Creator<ParcelableCalculatorEditorViewState>() {
@Override
public ParcelableCalculatorEditorViewState createFromParcel(@NotNull Parcel in) {
return ParcelableCalculatorEditorViewState.fromParcel(in);
}
@Override
public ParcelableCalculatorEditorViewState[] newArray(int size) {
return new ParcelableCalculatorEditorViewState[size];
}
};
@NotNull
private CalculatorEditorViewState viewState;
public ParcelableCalculatorEditorViewState(@NotNull CalculatorEditorViewState viewState) {
this.viewState = viewState;
}
@NotNull
private static ParcelableCalculatorEditorViewState fromParcel(@NotNull Parcel in) {
final String text = in.readString();
final int selection = in.readInt();
return new ParcelableCalculatorEditorViewState(CalculatorEditorViewStateImpl.newInstance(text, selection));
}
@Override
@NotNull
public String getText() {
return viewState.getText();
}
@Override
public int getSelection() {
return viewState.getSelection();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(@NotNull Parcel out, int flags) {
out.writeString(viewState.getText());
out.writeInt(viewState.getSelection());
}
}

View File

@@ -0,0 +1,35 @@
package org.solovyev.android.calculator;
import android.os.Handler;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.AndroidUtils;
import org.solovyev.common.DelayedExecutor;
import java.util.concurrent.TimeUnit;
/**
* User: serso
* Date: 12/1/12
* Time: 4:11 PM
*/
public class UiThreadExecutor implements DelayedExecutor {
@NotNull
private final Handler uiHandler;
public UiThreadExecutor() {
assert AndroidUtils.isUiThread() : "Must be called on UI thread!";
this.uiHandler = new Handler();
}
@Override
public void execute(@NotNull Runnable command, long delay, @NotNull TimeUnit delayUnit) {
this.uiHandler.postDelayed(command, delayUnit.toMillis(delay));
}
@Override
public void execute(@NotNull Runnable command) {
this.uiHandler.post(command);
}
}

View File

@@ -0,0 +1,113 @@
package org.solovyev.android.calculator.external;
import android.content.Context;
import android.content.Intent;
import android.os.Parcelable;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.*;
import java.util.HashSet;
import java.util.Set;
/**
* User: serso
* Date: 10/19/12
* Time: 11:11 PM
*/
public class AndroidExternalListenersContainer implements CalculatorExternalListenersContainer, CalculatorEventListener {
/*
**********************************************************************
*
* CONSTANTS
*
**********************************************************************
*/
public static final String EVENT_ID_EXTRA = "eventId";
public static final String INIT_ACTION = "org.solovyev.android.calculator.INIT";
public static final String INIT_ACTION_CREATE_VIEW_EXTRA = "createView";
public static final String EDITOR_STATE_CHANGED_ACTION = "org.solovyev.android.calculator.EDITOR_STATE_CHANGED";
public static final String EDITOR_STATE_EXTRA = "editorState";
public static final String DISPLAY_STATE_CHANGED_ACTION = "org.solovyev.android.calculator.DISPLAY_STATE_CHANGED";
public static final String DISPLAY_STATE_EXTRA = "displayState";
private static final String TAG = "Calculator++ External Listener Helper";
private final Set<Class<?>> externalListeners = new HashSet<Class<?>>();
@NotNull
private final CalculatorEventHolder lastEvent = new CalculatorEventHolder(CalculatorUtils.createFirstEventDataId());
public AndroidExternalListenersContainer(@NotNull Calculator calculator) {
calculator.addCalculatorEventListener(this);
}
public void onEditorStateChanged(@NotNull Context context,
@NotNull CalculatorEventData calculatorEventData,
@NotNull CalculatorEditorViewState editorViewState) {
for (Class<?> externalListener : externalListeners) {
final Intent intent = new Intent(EDITOR_STATE_CHANGED_ACTION);
intent.setClass(context, externalListener);
intent.putExtra(EVENT_ID_EXTRA, calculatorEventData.getEventId());
intent.putExtra(EDITOR_STATE_EXTRA, (Parcelable) new ParcelableCalculatorEditorViewState(editorViewState));
context.sendBroadcast(intent);
Locator.getInstance().getNotifier().showDebugMessage(TAG, "Editor state changed broadcast sent");
}
}
private void onDisplayStateChanged(@NotNull Context context,
@NotNull CalculatorEventData calculatorEventData,
@NotNull CalculatorDisplayViewState displayViewState) {
for (Class<?> externalListener : externalListeners) {
final Intent intent = new Intent(DISPLAY_STATE_CHANGED_ACTION);
intent.setClass(context, externalListener);
intent.putExtra(EVENT_ID_EXTRA, calculatorEventData.getEventId());
intent.putExtra(DISPLAY_STATE_EXTRA, (Parcelable) new ParcelableCalculatorDisplayViewState(displayViewState));
context.sendBroadcast(intent);
Locator.getInstance().getNotifier().showDebugMessage(TAG, "Display state changed broadcast sent");
}
}
@Override
public void addExternalListener(@NotNull Class<?> externalCalculatorClass) {
externalListeners.add(externalCalculatorClass);
}
@Override
public boolean removeExternalListener(@NotNull Class<?> externalCalculatorClass) {
return externalListeners.remove(externalCalculatorClass);
}
@Override
public void onCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
final CalculatorEventHolder.Result result = lastEvent.apply(calculatorEventData);
if (result.isNewAfter()) {
switch (calculatorEventType) {
case editor_state_changed_light:
case editor_state_changed:
final CalculatorEditorChangeEventData editorChangeData = (CalculatorEditorChangeEventData) data;
final CalculatorEditorViewState newEditorState = editorChangeData.getNewValue();
Locator.getInstance().getNotifier().showDebugMessage(TAG, "Editor state changed: " + newEditorState.getText());
onEditorStateChanged(App.getInstance().getApplication(), calculatorEventData, newEditorState);
break;
case display_state_changed:
final CalculatorDisplayChangeEventData displayChangeData = (CalculatorDisplayChangeEventData) data;
final CalculatorDisplayViewState newDisplayState = displayChangeData.getNewValue();
Locator.getInstance().getNotifier().showDebugMessage(TAG, "Display state changed: " + newDisplayState.getText());
onDisplayStateChanged(App.getInstance().getApplication(), calculatorEventData, newDisplayState);
break;
}
}
}
}

View File

@@ -0,0 +1,92 @@
package org.solovyev.android.calculator.external;
import android.content.Context;
import android.content.Intent;
import android.os.Parcelable;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.CalculatorDisplayViewState;
import org.solovyev.android.calculator.CalculatorEditorViewState;
import org.solovyev.android.calculator.Locator;
import org.solovyev.common.MutableObject;
/**
* User: serso
* Date: 11/20/12
* Time: 10:34 PM
*/
public class DefaultExternalCalculatorIntentHandler implements ExternalCalculatorIntentHandler {
private static final String TAG = ExternalCalculatorIntentHandler.class.getSimpleName();
@NotNull
private final MutableObject<Long> lastDisplayEventId = new MutableObject<Long>(0L);
@NotNull
private final MutableObject<Long> lastEditorEventId = new MutableObject<Long>(0L);
@NotNull
private final ExternalCalculatorStateUpdater stateUpdater;
public DefaultExternalCalculatorIntentHandler(@NotNull ExternalCalculatorStateUpdater stateUpdater) {
this.stateUpdater = stateUpdater;
}
@Override
public void onIntent(@NotNull Context context, @NotNull Intent intent) {
if (AndroidExternalListenersContainer.EDITOR_STATE_CHANGED_ACTION.equals(intent.getAction())) {
Locator.getInstance().getNotifier().showDebugMessage(TAG, "Editor state changed broadcast received!");
final Long eventId = intent.getLongExtra(AndroidExternalListenersContainer.EVENT_ID_EXTRA, 0L);
boolean updateEditor = false;
synchronized (lastEditorEventId) {
if (eventId > lastEditorEventId.getObject()) {
lastEditorEventId.setObject(eventId);
updateEditor = true;
}
}
if (updateEditor) {
final Parcelable object = intent.getParcelableExtra(AndroidExternalListenersContainer.EDITOR_STATE_EXTRA);
if (object instanceof CalculatorEditorViewState) {
onEditorStateChanged(context, (CalculatorEditorViewState) object);
}
}
} else if (AndroidExternalListenersContainer.DISPLAY_STATE_CHANGED_ACTION.equals(intent.getAction())) {
Locator.getInstance().getNotifier().showDebugMessage(TAG, "Display state changed broadcast received!");
final Long eventId = intent.getLongExtra(AndroidExternalListenersContainer.EVENT_ID_EXTRA, 0L);
boolean updateDisplay = false;
synchronized (lastDisplayEventId) {
if (eventId > lastDisplayEventId.getObject()) {
lastDisplayEventId.setObject(eventId);
updateDisplay = true;
}
}
if (updateDisplay) {
final Parcelable object = intent.getParcelableExtra(AndroidExternalListenersContainer.DISPLAY_STATE_EXTRA);
if (object instanceof CalculatorDisplayViewState) {
onDisplayStateChanged(context, (CalculatorDisplayViewState) object);
}
}
} else if ( AndroidExternalListenersContainer.INIT_ACTION.equals(intent.getAction()) ) {
updateState(context, Locator.getInstance().getEditor().getViewState(), Locator.getInstance().getDisplay().getViewState());
}
}
protected void updateState(@NotNull Context context,
@NotNull CalculatorEditorViewState editorViewState,
@NotNull CalculatorDisplayViewState displayViewState) {
stateUpdater.updateState(context, editorViewState, displayViewState);
}
protected void onDisplayStateChanged(@NotNull Context context, @NotNull CalculatorDisplayViewState displayViewState) {
updateState(context, Locator.getInstance().getEditor().getViewState(), displayViewState);
}
protected void onEditorStateChanged(@NotNull Context context, @NotNull CalculatorEditorViewState editorViewState) {
updateState(context, editorViewState, Locator.getInstance().getDisplay().getViewState());
}
}

View File

@@ -0,0 +1,15 @@
package org.solovyev.android.calculator.external;
import android.content.Context;
import android.content.Intent;
import org.jetbrains.annotations.NotNull;
/**
* User: serso
* Date: 11/20/12
* Time: 10:33 PM
*/
public interface ExternalCalculatorIntentHandler {
void onIntent(@NotNull Context context, @NotNull Intent intent);
}

View File

@@ -0,0 +1,18 @@
package org.solovyev.android.calculator.external;
import android.content.Context;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.CalculatorDisplayViewState;
import org.solovyev.android.calculator.CalculatorEditorViewState;
/**
* User: serso
* Date: 11/20/12
* Time: 10:42 PM
*/
public interface ExternalCalculatorStateUpdater {
void updateState(@NotNull Context context,
@NotNull CalculatorEditorViewState editorState,
@NotNull CalculatorDisplayViewState displayState);
}

View File

@@ -0,0 +1,286 @@
/*
* Copyright (c) 2009-2011. Created by serso aka se.solovyev.
* For more information, please, contact se.solovyev@gmail.com
*/
package org.solovyev.android.calculator.model;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import jscl.AngleUnit;
import jscl.JsclMathEngine;
import jscl.MathEngine;
import jscl.NumeralBase;
import jscl.math.function.Function;
import jscl.math.function.IConstant;
import jscl.math.operator.Operator;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.*;
import org.solovyev.android.calculator.core.R;
import org.solovyev.android.prefs.BooleanPreference;
import org.solovyev.android.prefs.Preference;
import org.solovyev.android.prefs.StringPreference;
import org.solovyev.common.text.EnumMapper;
import org.solovyev.common.text.NumberMapper;
import org.solovyev.common.text.StringUtils;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* User: serso
* Date: 9/12/11
* Time: 11:38 PM
*/
public class AndroidCalculatorEngine implements CalculatorEngine, SharedPreferences.OnSharedPreferenceChangeListener {
private static final String GROUPING_SEPARATOR_P_KEY = "org.solovyev.android.calculator.CalculatorActivity_calc_grouping_separator";
private static final String MULTIPLICATION_SIGN_P_KEY = "org.solovyev.android.calculator.CalculatorActivity_calc_multiplication_sign";
private static final String MULTIPLICATION_SIGN_DEFAULT = "×";
private static final String MAX_CALCULATION_TIME_P_KEY = "calculation.max_calculation_time";
private static final String MAX_CALCULATION_TIME_DEFAULT = "5";
private static final String SCIENCE_NOTATION_P_KEY = "calculation.output.science_notation";
private static final boolean SCIENCE_NOTATION_DEFAULT = false;
private static final String ROUND_RESULT_P_KEY = "org.solovyev.android.calculator.CalculatorModel_round_result";
private static final boolean ROUND_RESULT_DEFAULT = true;
private static final String RESULT_PRECISION_P_KEY = "org.solovyev.android.calculator.CalculatorModel_result_precision";
private static final String RESULT_PRECISION_DEFAULT = "5";
private static final String NUMERAL_BASES_P_KEY = "org.solovyev.android.calculator.CalculatorActivity_numeral_bases";
private static final String NUMERAL_BASES_DEFAULT = "dec";
private static final String ANGLE_UNITS_P_KEY = "org.solovyev.android.calculator.CalculatorActivity_angle_units";
private static final String ANGLE_UNITS_DEFAULT = "deg";
public static class Preferences {
public static final Preference<String> groupingSeparator = StringPreference.newInstance(GROUPING_SEPARATOR_P_KEY, JsclMathEngine.GROUPING_SEPARATOR_DEFAULT);
public static final Preference<String> multiplicationSign = StringPreference.newInstance(MULTIPLICATION_SIGN_P_KEY, MULTIPLICATION_SIGN_DEFAULT);
public static final Preference<Integer> precision = StringPreference.newInstance(RESULT_PRECISION_P_KEY, RESULT_PRECISION_DEFAULT, new NumberMapper<Integer>(Integer.class));
public static final Preference<Boolean> roundResult = new BooleanPreference(ROUND_RESULT_P_KEY, ROUND_RESULT_DEFAULT);
public static final Preference<NumeralBase> numeralBase = StringPreference.newInstance(NUMERAL_BASES_P_KEY, NUMERAL_BASES_DEFAULT, EnumMapper.newInstance(NumeralBase.class));
public static final Preference<AngleUnit> angleUnit = StringPreference.newInstance(ANGLE_UNITS_P_KEY, ANGLE_UNITS_DEFAULT, EnumMapper.newInstance(AngleUnit.class));
public static final Preference<Boolean> scienceNotation = new BooleanPreference(SCIENCE_NOTATION_P_KEY, SCIENCE_NOTATION_DEFAULT);
public static final Preference<Integer> maxCalculationTime = StringPreference.newInstance(MAX_CALCULATION_TIME_P_KEY, MAX_CALCULATION_TIME_DEFAULT, new NumberMapper<Integer>(Integer.class));
private static final List<String> preferenceKeys = new ArrayList<String>();
static {
preferenceKeys.add(groupingSeparator.getKey());
preferenceKeys.add(multiplicationSign.getKey());
preferenceKeys.add(precision.getKey());
preferenceKeys.add(roundResult.getKey());
preferenceKeys.add(numeralBase.getKey());
preferenceKeys.add(angleUnit.getKey());
preferenceKeys.add(scienceNotation.getKey());
preferenceKeys.add(maxCalculationTime.getKey());
}
@NotNull
public static List<String> getPreferenceKeys() {
return Collections.unmodifiableList(preferenceKeys);
}
}
@NotNull
private final Context context;
@NotNull
private final CalculatorEngine calculatorEngine;
@NotNull
private final Object lock;
public AndroidCalculatorEngine(@NotNull Application application) {
this.context = application;
PreferenceManager.getDefaultSharedPreferences(application).registerOnSharedPreferenceChangeListener(this);
this.lock = new Object();
final JsclMathEngine engine = JsclMathEngine.getInstance();
this.calculatorEngine = new CalculatorEngineImpl(engine,
new CalculatorVarsRegistry(engine.getConstantsRegistry(), new AndroidMathEntityDao<Var>(R.string.p_calc_vars, application, Vars.class)),
new CalculatorFunctionsMathRegistry(engine.getFunctionsRegistry(), new AndroidMathEntityDao<AFunction>(R.string.p_calc_functions, application, Functions.class)),
new CalculatorOperatorsMathRegistry(engine.getOperatorsRegistry(), new AndroidMathEntityDao<MathPersistenceEntity>(null, application, null)),
new CalculatorPostfixFunctionsRegistry(engine.getPostfixFunctionsRegistry(), new AndroidMathEntityDao<MathPersistenceEntity>(null, application, null)),
this.lock);
}
@Override
@NotNull
public CalculatorMathRegistry<IConstant> getVarsRegistry() {
return calculatorEngine.getVarsRegistry();
}
@Override
@NotNull
public CalculatorMathRegistry<Function> getFunctionsRegistry() {
return calculatorEngine.getFunctionsRegistry();
}
@Override
@NotNull
public CalculatorMathRegistry<Operator> getOperatorsRegistry() {
return calculatorEngine.getOperatorsRegistry();
}
@Override
@NotNull
public CalculatorMathRegistry<Operator> getPostfixFunctionsRegistry() {
return calculatorEngine.getPostfixFunctionsRegistry();
}
@Override
@NotNull
public CalculatorMathEngine getMathEngine() {
return calculatorEngine.getMathEngine();
}
@NotNull
@Override
public MathEngine getMathEngine0() {
return calculatorEngine.getMathEngine0();
}
@NotNull
@Override
public NumeralBase getNumeralBase() {
return calculatorEngine.getNumeralBase();
}
@Override
public void init() {
synchronized (lock) {
reset();
}
}
@Override
public void reset() {
synchronized (lock) {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
softReset(preferences);
calculatorEngine.reset();
}
}
@Override
public void softReset() {
synchronized (lock) {
softReset(PreferenceManager.getDefaultSharedPreferences(context));
calculatorEngine.softReset();
}
}
@Override
public void setUseGroupingSeparator(boolean useGroupingSeparator) {
calculatorEngine.setUseGroupingSeparator(useGroupingSeparator);
}
@Override
public void setGroupingSeparator(char groupingSeparator) {
calculatorEngine.setGroupingSeparator(groupingSeparator);
}
@Override
public void setPrecision(@NotNull Integer precision) {
calculatorEngine.setPrecision(precision);
}
@Override
public void setRoundResult(@NotNull Boolean round) {
calculatorEngine.setRoundResult(round);
}
@NotNull
@Override
public AngleUnit getAngleUnits() {
return calculatorEngine.getAngleUnits();
}
@Override
public void setAngleUnits(@NotNull AngleUnit angleUnits) {
calculatorEngine.setAngleUnits(angleUnits);
}
@Override
public void setNumeralBase(@NotNull NumeralBase numeralBase) {
calculatorEngine.setNumeralBase(numeralBase);
}
@Override
public void setMultiplicationSign(@NotNull String multiplicationSign) {
calculatorEngine.setMultiplicationSign(multiplicationSign);
}
@Override
public void setScienceNotation(@NotNull Boolean scienceNotation) {
calculatorEngine.setScienceNotation(scienceNotation);
}
@Override
public void setTimeout(@NotNull Integer timeout) {
calculatorEngine.setTimeout(timeout);
}
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));
final String groupingSeparator = Preferences.groupingSeparator.getPreference(preferences);
if (StringUtils.isEmpty(groupingSeparator)) {
this.setUseGroupingSeparator(false);
} else {
this.setUseGroupingSeparator(true);
setGroupingSeparator(groupingSeparator.charAt(0));
}
}
@NotNull
public NumeralBase getNumeralBaseFromPrefs(@NotNull SharedPreferences preferences) {
return Preferences.numeralBase.getPreference(preferences);
}
@NotNull
public AngleUnit getAngleUnitsFromPrefs(@NotNull SharedPreferences preferences) {
return Preferences.angleUnit.getPreference(preferences);
}
//for tests only
public void setDecimalGroupSymbols(@NotNull DecimalFormatSymbols decimalGroupSymbols) {
this.calculatorEngine.setDecimalGroupSymbols(decimalGroupSymbols);
}
@Override
@NotNull
public String getMultiplicationSign() {
return calculatorEngine.getMultiplicationSign();
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if ( Preferences.getPreferenceKeys().contains(key) ) {
this.softReset();
}
}
}

View File

@@ -0,0 +1,99 @@
package org.solovyev.android.calculator.model;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.preference.PreferenceManager;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
import org.solovyev.android.calculator.App;
import org.solovyev.android.calculator.MathEntityDao;
import org.solovyev.android.calculator.MathEntityPersistenceContainer;
import org.solovyev.android.calculator.MathPersistenceEntity;
import java.io.StringWriter;
/**
* User: serso
* Date: 10/7/12
* Time: 6:46 PM
*/
public class AndroidMathEntityDao<T extends MathPersistenceEntity> implements MathEntityDao<T> {
@NotNull
private static final String TAG = AndroidMathEntityDao.class.getSimpleName();
@Nullable
private final Integer preferenceStringId;
@NotNull
private final Context context;
@Nullable
private final Class<? extends MathEntityPersistenceContainer<T>> persistenceContainerClass;
public AndroidMathEntityDao(@Nullable Integer preferenceStringId,
@NotNull Application application,
@Nullable Class<? extends MathEntityPersistenceContainer<T>> persistenceContainerClass) {
this.preferenceStringId = preferenceStringId;
this.context = application;
this.persistenceContainerClass = persistenceContainerClass;
}
@Override
public void save(@NotNull MathEntityPersistenceContainer<T> container) {
if (preferenceStringId != null) {
final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
final SharedPreferences.Editor editor = settings.edit();
final StringWriter sw = new StringWriter();
final Serializer serializer = new Persister();
try {
serializer.write(container, sw);
} catch (Exception e) {
throw new RuntimeException(e);
}
editor.putString(context.getString(preferenceStringId), sw.toString());
editor.commit();
}
}
@Nullable
@Override
public MathEntityPersistenceContainer<T> load() {
if (persistenceContainerClass != null && preferenceStringId != null) {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
if (preferences != null) {
final String value = preferences.getString(context.getString(preferenceStringId), null);
if (value != null) {
final Serializer serializer = new Persister();
try {
return serializer.read(persistenceContainerClass, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
return null;
}
@Nullable
public String getDescription(@NotNull String descriptionId) {
final Resources resources = context.getResources();
final int stringId = resources.getIdentifier(descriptionId, "string", App.getInstance().getApplication().getClass().getPackage().getName());
try {
return resources.getString(stringId);
} catch (Resources.NotFoundException e) {
return null;
}
}
}

View File

@@ -0,0 +1,28 @@
package org.solovyev.android.calculator.plot;
import android.graphics.Color;
/**
* User: serso
* Date: 10/4/12
* Time: 10:08 PM
*/
public enum GraphLineColor {
white(Color.WHITE),
grey(Color.GRAY),
red(Color.RED),
blue(Color.rgb(16, 100, 140)),
green(Color.GREEN);
private final int color;
private GraphLineColor(int color) {
this.color = color;
}
public int getColor() {
return this.color;
}
}

View File

@@ -0,0 +1,42 @@
package org.solovyev.android.calculator.plot;
import jscl.math.Generic;
import jscl.math.function.Constant;
import org.jetbrains.annotations.NotNull;
/**
* User: serso
* Date: 12/1/12
* Time: 5:09 PM
*/
public class PlotInput {
@NotNull
private Generic function;
@NotNull
private Constant constant;
public PlotInput() {
}
private PlotInput(@NotNull Generic function, @NotNull Constant constant) {
this.function = function;
this.constant = constant;
}
@NotNull
public static PlotInput newInstance(@NotNull Generic function, @NotNull Constant constant) {
return new PlotInput(function, constant);
}
@NotNull
public Generic getFunction() {
return function;
}
@NotNull
public Constant getConstant() {
return constant;
}
}

View File

@@ -0,0 +1,44 @@
/*
* 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 android.content.Context;
import android.content.res.Resources;
import android.graphics.Paint;
import android.text.TextPaint;
import android.util.AttributeSet;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.Locator;
import org.solovyev.android.calculator.core.R;
import org.solovyev.android.view.drag.DirectionDragButton;
/**
* User: serso
* Date: 11/22/11
* Time: 2:42 PM
*/
public class AngleUnitsButton extends DirectionDragButton {
public AngleUnitsButton(Context context, @NotNull AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void initDirectionTextPaint(@NotNull Paint basePaint,
@NotNull DirectionTextData directionTextData,
@NotNull Resources resources) {
super.initDirectionTextPaint(basePaint, directionTextData, resources);
final TextPaint directionTextPaint = directionTextData.getPaint();
if (Locator.getInstance().getEngine().getAngleUnits().name().equals(directionTextData.getText())) {
directionTextPaint.setColor(resources.getColor(R.color.cpp_selected_angle_unit_text_color));
} else {
directionTextPaint.setColor(resources.getColor(R.color.cpp_default_text_color));
directionTextPaint.setAlpha(getDirectionTextAlpha());
}
}
}

View File

@@ -0,0 +1,98 @@
package org.solovyev.android.calculator.view;
import android.app.AlertDialog;
import android.content.Context;
import android.view.View;
import android.view.WindowManager;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.CalculatorParseException;
import org.solovyev.android.calculator.Locator;
import org.solovyev.android.calculator.ToJsclTextProcessor;
import org.solovyev.android.calculator.core.R;
import org.solovyev.android.calculator.units.CalculatorNumeralBase;
import org.solovyev.common.MutableObject;
import org.solovyev.common.text.StringUtils;
import org.solovyev.math.units.Unit;
import org.solovyev.math.units.UnitImpl;
import java.util.Arrays;
/**
* User: serso
* Date: 4/22/12
* Time: 12:20 AM
*/
public class NumeralBaseConverterDialog {
@Nullable
private String initialFromValue;
public NumeralBaseConverterDialog(String initialFromValue) {
this.initialFromValue = initialFromValue;
}
public void show(@NotNull Context context) {
final UnitConverterViewBuilder b = new UnitConverterViewBuilder();
b.setFromUnitTypes(Arrays.asList(CalculatorNumeralBase.values()));
b.setToUnitTypes(Arrays.asList(CalculatorNumeralBase.values()));
if (!StringUtils.isEmpty(initialFromValue)) {
String value = initialFromValue;
try {
value = ToJsclTextProcessor.getInstance().process(value).getExpression();
b.setFromValue(UnitImpl.newInstance(value, CalculatorNumeralBase.valueOf(Locator.getInstance().getEngine().getNumeralBase())));
} catch (CalculatorParseException e) {
b.setFromValue(UnitImpl.newInstance(value, CalculatorNumeralBase.valueOf(Locator.getInstance().getEngine().getNumeralBase())));
}
} else {
b.setFromValue(UnitImpl.newInstance("", CalculatorNumeralBase.valueOf(Locator.getInstance().getEngine().getNumeralBase())));
}
b.setConverter(CalculatorNumeralBase.getConverter());
final MutableObject<AlertDialog> alertDialogHolder = new MutableObject<AlertDialog>();
b.setOkButtonOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final AlertDialog alertDialog = alertDialogHolder.getObject();
if (alertDialog != null) {
alertDialog.dismiss();
}
}
});
b.setCustomButtonData(new UnitConverterViewBuilder.CustomButtonData(context.getString(R.string.c_use_short), new UnitConverterViewBuilder.CustomButtonOnClickListener() {
@Override
public void onClick(@NotNull Unit<String> fromUnits, @NotNull Unit<String> toUnits) {
String toUnitsValue = toUnits.getValue();
if (!toUnits.getUnitType().equals(CalculatorNumeralBase.valueOf(Locator.getInstance().getEngine().getNumeralBase()))) {
toUnitsValue = ((CalculatorNumeralBase) toUnits.getUnitType()).getNumeralBase().getJsclPrefix() + toUnitsValue;
}
Locator.getInstance().getKeyboard().buttonPressed(toUnitsValue);
final AlertDialog alertDialog = alertDialogHolder.getObject();
if (alertDialog != null) {
alertDialog.dismiss();
}
}
}));
final AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
alertBuilder.setView(b.build(context));
alertBuilder.setTitle(R.string.c_conversion_tool);
final AlertDialog alertDialog = alertBuilder.create();
final WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(alertDialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.FILL_PARENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
alertDialogHolder.setObject(alertDialog);
alertDialog.show();
alertDialog.getWindow().setAttributes(lp);
}
}

View File

@@ -0,0 +1,44 @@
/*
* 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 android.content.Context;
import android.content.res.Resources;
import android.graphics.Paint;
import android.text.TextPaint;
import android.util.AttributeSet;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.Locator;
import org.solovyev.android.calculator.core.R;
import org.solovyev.android.view.drag.DirectionDragButton;
/**
* User: serso
* Date: 12/8/11
* Time: 2:22 AM
*/
public class NumeralBasesButton extends DirectionDragButton {
public NumeralBasesButton(Context context, @NotNull AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void initDirectionTextPaint(@NotNull Paint basePaint,
@NotNull DirectionTextData directionTextData,
@NotNull Resources resources) {
super.initDirectionTextPaint(basePaint, directionTextData, resources);
final TextPaint directionTextPaint = directionTextData.getPaint();
if (Locator.getInstance().getEngine().getNumeralBase().name().equals(directionTextData.getText())) {
directionTextPaint.setColor(resources.getColor(R.color.cpp_selected_angle_unit_text_color));
} else {
directionTextPaint.setColor(resources.getColor(R.color.cpp_default_text_color));
directionTextPaint.setAlpha(getDirectionTextAlpha());
}
}
}

View File

@@ -0,0 +1,246 @@
/*
* 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 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");
}
public static class Result implements CharSequence {
@NotNull
private final CharSequence charSequence;
@Nullable
private String string;
private final int offset;
public Result(@NotNull CharSequence charSequence, int offset) {
this.charSequence = charSequence;
this.offset = offset;
}
@Override
public int length() {
return charSequence.length();
}
@Override
public char charAt(int i) {
return charSequence.charAt(i);
}
@Override
public CharSequence subSequence(int i, int i1) {
return charSequence.subSequence(i, i1);
}
@Override
public String toString() {
if (string == null) {
string = charSequence.toString();
}
return string;
}
@NotNull
public CharSequence getCharSequence() {
return charSequence;
}
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) {
this.color = baseColor;
this.formatNumber = formatNumber;
//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 CharSequence result;
int maxNumberOfOpenGroupSymbols = 0;
int numberOfOpenGroupSymbols = 0;
final StringBuilder text1 = new StringBuilder(5 * text.length());
int resultOffset = 0;
final AbstractNumberBuilder numberBuilder;
if (!formatNumber) {
numberBuilder = new LiteNumberBuilder(Locator.getInstance().getEngine());
} else {
numberBuilder = new NumberBuilder(Locator.getInstance().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(text1.length());
final CharSequence s = text1;
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 && !tagAttributes.entrySet().isEmpty()) {
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 CharSequence 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);
String strCh = String.valueOf(ch);
if (MathType.open_group_symbol.getTokens().contains(strCh)) {
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(strCh)) {
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);
}
}

View File

@@ -0,0 +1,220 @@
package org.solovyev.android.calculator.view;
import android.app.Activity;
import android.content.Context;
import android.text.ClipboardManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.core.R;
import org.solovyev.android.view.ViewBuilder;
import org.solovyev.android.view.ViewFromLayoutBuilder;
import org.solovyev.math.units.*;
import java.util.Collections;
import java.util.List;
/**
* User: serso
* Date: 4/20/12
* Time: 4:50 PM
*/
public class UnitConverterViewBuilder implements ViewBuilder<View> {
@NotNull
private List<? extends UnitType<String>> fromUnitTypes = Collections.emptyList();
@NotNull
private List<? extends UnitType<String>> toUnitTypes = Collections.emptyList();
@Nullable
private Unit<String> fromValue;
@NotNull
private UnitConverter<String> converter = UnitConverter.Dummy.getInstance();
@Nullable
private View.OnClickListener okButtonOnClickListener;
@Nullable
private CustomButtonData customButtonData;
public void setFromUnitTypes(@NotNull List<? extends UnitType<String>> fromUnitTypes) {
this.fromUnitTypes = fromUnitTypes;
}
public void setToUnitTypes(@NotNull List<? extends UnitType<String>> toUnitTypes) {
this.toUnitTypes = toUnitTypes;
}
public void setFromValue(@Nullable Unit<String> fromValue) {
this.fromValue = fromValue;
}
public void setConverter(@NotNull UnitConverter<String> converter) {
this.converter = converter;
}
public void setOkButtonOnClickListener(@Nullable View.OnClickListener okButtonOnClickListener) {
this.okButtonOnClickListener = okButtonOnClickListener;
}
public void setCustomButtonData(@Nullable CustomButtonData customButtonData) {
this.customButtonData = customButtonData;
}
@NotNull
@Override
public View build(@NotNull final Context context) {
final View main = ViewFromLayoutBuilder.newInstance(R.layout.cpp_unit_converter).build(context);
final Spinner fromSpinner = (Spinner) main.findViewById(R.id.unit_types_from);
final EditText fromEditText = (EditText) main.findViewById(R.id.units_from);
fromEditText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
doConversion(main, context, UnitConverterViewBuilder.this.converter);
}
});
fillSpinner(main, context, R.id.unit_types_from, fromUnitTypes);
fillSpinner(main, context, R.id.unit_types_to, toUnitTypes);
if (fromValue != null) {
fromEditText.setText(fromValue.getValue());
int i = fromUnitTypes.indexOf(fromValue.getUnitType());
if ( i >= 0 ) {
fromSpinner.setSelection(i);
}
}
final Button copyButton = (Button) main.findViewById(R.id.unit_converter_copy_button);
copyButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final EditText toEditText = (EditText) main.findViewById(R.id.units_to);
final ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Activity.CLIPBOARD_SERVICE);
clipboard.setText(toEditText.getText().toString());
Toast.makeText(context, context.getText(R.string.c_result_copied), Toast.LENGTH_SHORT).show();
}
});
final Button okButton = (Button) main.findViewById(R.id.unit_converter_ok_button);
if ( okButtonOnClickListener == null ) {
((ViewGroup) okButton.getParent()).removeView(okButton);
} else {
okButton.setOnClickListener(this.okButtonOnClickListener);
}
final Button customButton = (Button) main.findViewById(R.id.unit_converter_custom_button);
if ( customButtonData == null ) {
((ViewGroup) customButton.getParent()).removeView(customButton);
} else {
customButton.setText(customButtonData.text);
customButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
customButtonData.clickListener.onClick(getFromUnit(main), getToUnit(main));
}
});
}
return main;
}
private void fillSpinner(@NotNull final View main,
@NotNull final Context context,
final int spinnerId,
@NotNull List<? extends UnitType<String>> unitTypes) {
final Spinner spinner = (Spinner) main.findViewById(spinnerId);
final ArrayAdapter<UnitType<String>> adapter = new ArrayAdapter<UnitType<String>>(context, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
for (UnitType<String> fromUnitType : unitTypes) {
adapter.add(fromUnitType);
}
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
doConversion(main, context, UnitConverterViewBuilder.this.converter);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
spinner.setAdapter(adapter);
}
private static void doConversion(@NotNull View main, @NotNull Context context, @NotNull UnitConverter<String> converter) {
final EditText fromEditText = (EditText) main.findViewById(R.id.units_from);
final EditText toEditText = (EditText) main.findViewById(R.id.units_to);
final String from = fromEditText.getText().toString();
try {
toEditText.setText(ConversionUtils.doConversion(converter, from, getFromUnitType(main), getToUnitType(main)));
} catch (ConversionException e) {
toEditText.setText(context.getString(R.string.c_error));
}
}
@NotNull
private static Unit<String> getToUnit(@NotNull View main) {
final EditText toUnits = (EditText) main.findViewById(R.id.units_to);
return UnitImpl.newInstance(toUnits.getText().toString(), getToUnitType(main));
}
@NotNull
private static UnitType<String> getToUnitType(@NotNull View main) {
final Spinner toSpinner = (Spinner) main.findViewById(R.id.unit_types_to);
return (UnitType<String>) toSpinner.getSelectedItem();
}
@NotNull
private static Unit<String> getFromUnit(@NotNull View main) {
final EditText fromUnits = (EditText) main.findViewById(R.id.units_from);
return UnitImpl.newInstance(fromUnits.getText().toString(), getFromUnitType(main));
}
@NotNull
private static UnitType<String> getFromUnitType(@NotNull View main) {
final Spinner fromSpinner = (Spinner) main.findViewById(R.id.unit_types_from);
return (UnitType<String>) fromSpinner.getSelectedItem();
}
public static class CustomButtonData {
@NotNull
private String text;
@NotNull
private CustomButtonOnClickListener clickListener;
public CustomButtonData(@NotNull String text, @NotNull CustomButtonOnClickListener clickListener) {
this.text = text;
this.clickListener = clickListener;
}
}
public static interface CustomButtonOnClickListener {
void onClick(@NotNull Unit<String> fromUnits, @NotNull Unit<String> toUnits);
}
}