code reformat

This commit is contained in:
Sergey Solovyev
2013-06-15 00:31:49 +04:00
parent 30e8b55a73
commit e57ce8cf2c
523 changed files with 20785 additions and 19727 deletions

View File

@@ -7,8 +7,8 @@ package org.solovyev.android;
*/
public final class AndroidUtils2 {
private AndroidUtils2() {
throw new AssertionError();
}
private AndroidUtils2() {
throw new AssertionError();
}
}

View File

@@ -31,148 +31,148 @@ import java.util.concurrent.Executors;
*/
public class AndroidCalculatorDisplayView extends AutoResizeTextView implements CalculatorDisplayView {
/*
**********************************************************************
*
* STATIC FIELDS
*
**********************************************************************
*/
/*
**********************************************************************
*
* STATIC FIELDS
*
**********************************************************************
*/
@NotNull
private final static TextProcessor<TextHighlighter.Result, String> textHighlighter = new TextHighlighter(Color.WHITE, false);
@NotNull
private final static TextProcessor<TextHighlighter.Result, String> textHighlighter = new TextHighlighter(Color.WHITE, false);
/*
**********************************************************************
*
* FIELDS
*
**********************************************************************
*/
/*
**********************************************************************
*
* FIELDS
*
**********************************************************************
*/
@NotNull
private volatile CalculatorDisplayViewState state = CalculatorDisplayViewStateImpl.newDefaultInstance();
@NotNull
private volatile CalculatorDisplayViewState state = CalculatorDisplayViewStateImpl.newDefaultInstance();
private volatile boolean viewStateChange = false;
private volatile boolean viewStateChange = false;
@NotNull
private final Object lock = new Object();
@NotNull
private final Object lock = new Object();
@NotNull
private final Handler uiHandler = new Handler();
@NotNull
private final Handler uiHandler = new Handler();
@NotNull
private final ExecutorService bgExecutor = Executors.newSingleThreadExecutor();
@NotNull
private final ExecutorService bgExecutor = Executors.newSingleThreadExecutor();
private volatile boolean initialized = false;
private volatile boolean initialized = false;
/*
**********************************************************************
*
* CONSTRUCTORS
*
**********************************************************************
*/
/*
**********************************************************************
*
* CONSTRUCTORS
*
**********************************************************************
*/
public AndroidCalculatorDisplayView(Context context) {
super(context);
}
public AndroidCalculatorDisplayView(Context context) {
super(context);
}
public AndroidCalculatorDisplayView(Context context, AttributeSet attrs) {
super(context, attrs);
public AndroidCalculatorDisplayView(Context context, AttributeSet attrs) {
super(context, attrs);
}
}
public AndroidCalculatorDisplayView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public AndroidCalculatorDisplayView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
/*
**********************************************************************
*
* METHODS
*
**********************************************************************
*/
/*
**********************************************************************
*
* METHODS
*
**********************************************************************
*/
@Override
public void setState(@NotNull final CalculatorDisplayViewState state) {
@Override
public void setState(@NotNull final CalculatorDisplayViewState state) {
uiHandler.post(new Runnable() {
@Override
public void run() {
uiHandler.post(new Runnable() {
@Override
public void run() {
synchronized (lock) {
try {
viewStateChange = true;
synchronized (lock) {
try {
viewStateChange = true;
final CharSequence text = prepareText(state.getStringResult(), state.isValid());
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);
AndroidCalculatorDisplayView.this.state = state;
if (state.isValid()) {
setTextColor(getResources().getColor(R.color.cpp_default_text_color));
setText(text);
adjustTextSize();
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));
} 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;
}
}
}
});
}
// 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;
}
}
@NotNull
@Override
public CalculatorDisplayViewState getState() {
synchronized (lock) {
return this.state;
}
}
@Nullable
private static CharSequence prepareText(@Nullable String text, boolean valid) {
CharSequence result;
@Nullable
private static CharSequence prepareText(@Nullable String text, boolean valid) {
CharSequence result;
if (valid && text != null) {
if (valid && text != null) {
//Log.d(this.getClass().getName(), text);
//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;
}
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;
}
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();
}
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) {
public synchronized void init(@NotNull Context context) {
this.init(context, true);
}
}
public synchronized void init(@NotNull Context context, boolean fromApp) {
if (!initialized) {
@@ -180,7 +180,7 @@ public class AndroidCalculatorDisplayView extends AutoResizeTextView implements
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
final CalculatorPreferences.Gui.Layout layout = CalculatorPreferences.Gui.getLayout(preferences);
if ( layout == CalculatorPreferences.Gui.Layout.main_calculator_mobile ) {
if (layout == CalculatorPreferences.Gui.Layout.main_calculator_mobile) {
setTextSize(TypedValue.COMPLEX_UNIT_SP, getResources().getDimension(R.dimen.cpp_display_text_size_mobile));
}

View File

@@ -32,195 +32,195 @@ import org.solovyev.common.collections.Collections;
*/
public class AndroidCalculatorEditorView extends EditText implements SharedPreferences.OnSharedPreferenceChangeListener, CalculatorEditorView {
@NotNull
private static final BooleanPreference colorDisplay = BooleanPreference.of("org.solovyev.android.calculator.CalculatorModel_color_display", true);
@NotNull
private static final BooleanPreference colorDisplay = BooleanPreference.of("org.solovyev.android.calculator.CalculatorModel_color_display", true);
private volatile boolean initialized = false;
private volatile boolean initialized = false;
private boolean highlightText = true;
private boolean highlightText = true;
@NotNull
private final static TextProcessor<TextHighlighter.Result, String> textHighlighter = new TextHighlighter(Color.WHITE, false);
@NotNull
private final static TextProcessor<TextHighlighter.Result, String> textHighlighter = new TextHighlighter(Color.WHITE, false);
@NotNull
private volatile CalculatorEditorViewState viewState = CalculatorEditorViewStateImpl.newDefaultInstance();
@NotNull
private volatile CalculatorEditorViewState viewState = CalculatorEditorViewStateImpl.newDefaultInstance();
private volatile boolean viewStateChange = false;
private volatile boolean viewStateChange = false;
@Nullable
private final Object viewLock = new Object();
@Nullable
private final Object viewLock = new Object();
@NotNull
private final Handler uiHandler = new Handler();
@NotNull
private final Handler uiHandler = new Handler();
public AndroidCalculatorEditorView(Context context) {
super(context);
}
public AndroidCalculatorEditorView(Context context) {
super(context);
}
public AndroidCalculatorEditorView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public AndroidCalculatorEditorView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public AndroidCalculatorEditorView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
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
@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 : Collections.asList(Thread.currentThread().getStackTrace())) {
if ("isCursorVisible".equals(stackTraceElement.getMethodName())) {
return true;
}
}
} catch (RuntimeException e) {
// just in case...
}
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 : Collections.asList(Thread.currentThread().getStackTrace())) {
if ("isCursorVisible".equals(stackTraceElement.getMethodName())) {
return true;
}
}
} catch (RuntimeException e) {
// just in case...
}
return false;
} else {
return false;
}
}
return false;
} else {
return false;
}
}
@Override
protected void onCreateContextMenu(ContextMenu menu) {
super.onCreateContextMenu(menu);
@Override
protected void onCreateContextMenu(ContextMenu menu) {
super.onCreateContextMenu(menu);
menu.removeItem(android.R.id.selectAll);
}
menu.removeItem(android.R.id.selectAll);
}
@Nullable
private CharSequence prepareText(@NotNull String text, boolean highlightText) {
CharSequence result;
@Nullable
private CharSequence prepareText(@NotNull String text, boolean highlightText) {
CharSequence result;
if (highlightText) {
if (highlightText) {
try {
final TextHighlighter.Result processesText = textHighlighter.process(text);
try {
final TextHighlighter.Result processesText = textHighlighter.process(text);
assert processesText.getOffset() == 0;
assert processesText.getOffset() == 0;
result = Html.fromHtml(processesText.toString());
} catch (CalculatorParseException e) {
// set raw text
result = text;
result = Html.fromHtml(processesText.toString());
} catch (CalculatorParseException e) {
// set raw text
result = text;
Log.e(this.getClass().getName(), e.getMessage(), e);
}
} else {
result = text;
}
Log.e(this.getClass().getName(), e.getMessage(), e);
}
} else {
result = text;
}
return result;
}
return result;
}
public boolean isHighlightText() {
return highlightText;
}
public boolean isHighlightText() {
return highlightText;
}
public void setHighlightText(boolean highlightText) {
this.highlightText = highlightText;
Locator.getInstance().getEditor().updateViewState();
}
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));
}
}
@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);
public synchronized void init(@NotNull Context context) {
if (!initialized) {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
preferences.registerOnSharedPreferenceChangeListener(this);
preferences.registerOnSharedPreferenceChangeListener(this);
this.addTextChangedListener(new TextWatcherImpl());
this.addTextChangedListener(new TextWatcherImpl());
onSharedPreferenceChanged(preferences, colorDisplay.getKey());
onSharedPreferenceChanged(preferences, colorDisplay.getKey());
initialized = true;
}
}
initialized = true;
}
}
@Override
public void setState(@NotNull final CalculatorEditorViewState viewState) {
if (viewLock != null) {
synchronized (viewLock) {
@Override
public void setState(@NotNull final CalculatorEditorViewState viewState) {
if (viewLock != null) {
synchronized (viewLock) {
final CharSequence text = prepareText(viewState.getText(), highlightText);
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);
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);
final int selection = CalculatorEditorImpl.correctSelection(viewState.getSelection(), editorView.getText());
editorView.setSelection(selection);
} 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);
if ( selStart == selEnd ) {
// only if cursor moving, if selection do nothing
Locator.getInstance().getEditor().setSelection(selStart);
} finally {
editorView.viewStateChange = false;
}
}
}
}
}
}
}
});
}
}
}
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));
}
}
}
}
@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);
private final class TextWatcherImpl implements TextWatcher {
if (selStart == selEnd) {
// only if cursor moving, if selection do nothing
Locator.getInstance().getEditor().setSelection(selStart);
}
}
}
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
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 onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
@Override
public void afterTextChanged(Editable s) {
handleTextChange(s);
}
}
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
handleTextChange(s);
}
}
}

View File

@@ -9,121 +9,121 @@ import java.util.HashMap;
import java.util.Map;
/**
* User: serso
* Date: 10/20/12
* Time: 12:05 AM
*/
* 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"),
/*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, "()"),
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),
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),
/*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, "^"),
/*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),
/*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);
/*equals*/
equals(R.id.cpp_button_equals, CalculatorSpecialButton.equals);
private final int buttonId;
private final int buttonId;
@NotNull
private final String onClickText;
@NotNull
private final String onClickText;
@Nullable
private final String onLongClickText;
@NotNull
private static Map<Integer, CalculatorButton> buttonsByIds = new HashMap<Integer, CalculatorButton>();
@NotNull
private static Map<Integer, CalculatorButton> buttonsByIds = new HashMap<Integer, CalculatorButton>();
CalculatorButton(int buttonId, @NotNull CalculatorSpecialButton onClickButton, @Nullable CalculatorSpecialButton onLongClickButton) {
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 CalculatorSpecialButton onClickButton) {
this(buttonId, onClickButton, null);
}
CalculatorButton(int buttonId, @NotNull String onClickText, @Nullable String onLongClickText) {
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);
}
CalculatorButton(int buttonId, @NotNull String onClickText) {
this(buttonId, onClickText, null);
}
public void onLongClick(@NotNull Context context) {
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);
}
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();
@Nullable
public static CalculatorButton getById(int buttonId) {
initButtonsByIdsMap();
return buttonsByIds.get(buttonId);
}
return buttonsByIds.get(buttonId);
}
private static void initButtonsByIdsMap() {
if ( buttonsByIds.isEmpty() ) {
// if not initialized
private static void initButtonsByIdsMap() {
if (buttonsByIds.isEmpty()) {
// if not initialized
final CalculatorButton[] calculatorButtons = values();
final CalculatorButton[] calculatorButtons = values();
final Map<Integer, CalculatorButton> localButtonsByIds = new HashMap<Integer, CalculatorButton>(calculatorButtons.length);
for (CalculatorButton calculatorButton : calculatorButtons) {
localButtonsByIds.put(calculatorButton.getButtonId(), calculatorButton);
}
final Map<Integer, CalculatorButton> localButtonsByIds = new HashMap<Integer, CalculatorButton>(calculatorButtons.length);
for (CalculatorButton calculatorButton : calculatorButtons) {
localButtonsByIds.put(calculatorButton.getButtonId(), calculatorButton);
}
buttonsByIds = localButtonsByIds;
}
}
buttonsByIds = localButtonsByIds;
}
}
public int getButtonId() {
return buttonId;
}
public int getButtonId() {
return buttonId;
}
}

View File

@@ -32,230 +32,230 @@ import org.solovyev.common.math.Point2d;
*/
public final class CalculatorButtons {
private 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 ) {
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);
final float textSize = root.getContext().getResources().getDimension(R.dimen.cpp_keyboard_button_text_size_mobile);
Views.processViewsOfType(root, DragButton.class, new Views.ViewProcessor<DragButton>() {
@Override
public void process(@NotNull DragButton button) {
button.setTextSize(TypedValue.COMPLEX_UNIT_DIP, textSize);
}
});
}
}
Views.processViewsOfType(root, DragButton.class, new Views.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());
}
}
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 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;
public static void toggleEqualsButton(@Nullable SharedPreferences preferences,
@NotNull Activity activity) {
preferences = preferences == null ? PreferenceManager.getDefaultSharedPreferences(activity) : preferences;
final boolean large = Views.isLayoutSizeAtLeast(Configuration.SCREENLAYOUT_SIZE_LARGE, activity.getResources().getConfiguration()) &&
CalculatorPreferences.Gui.getLayout(preferences) != CalculatorPreferences.Gui.Layout.main_calculator_mobile;
final boolean large = Views.isLayoutSizeAtLeast(Configuration.SCREENLAYOUT_SIZE_LARGE, activity.getResources().getConfiguration()) &&
CalculatorPreferences.Gui.getLayout(preferences) != CalculatorPreferences.Gui.Layout.main_calculator_mobile;
if (!large) {
if (Views.getScreenOrientation(activity) == Configuration.ORIENTATION_PORTRAIT
|| !CalculatorPreferences.Gui.autoOrientation.getPreference(preferences)) {
if (!large) {
if (Views.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);
}
}
}
}
}
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 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;
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);
}
if (dragDirection == DragDirection.left) {
getKeyboard().roundBracketsButtonPressed();
result = true;
} else {
result = new DigitButtonDragProcessor(getKeyboard()).processDragEvent(dragDirection, dragButton, startPoint2d, motionEvent);
}
return result;
}
}
return result;
}
}
@NotNull
private static CalculatorKeyboard getKeyboard() {
return Locator.getInstance().getKeyboard();
}
@NotNull
private static CalculatorKeyboard getKeyboard() {
return Locator.getInstance().getKeyboard();
}
static class VarsDragProcessor implements SimpleOnDragListener.DragProcessor {
static class VarsDragProcessor implements SimpleOnDragListener.DragProcessor {
@NotNull
private Context context;
@NotNull
private Context context;
VarsDragProcessor(@NotNull Context context) {
this.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;
@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, context);
result = true;
} else if ( dragDirection == DragDirection.down ) {
Locator.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.show_create_matrix_dialog, null, context);
result = true;
}
if (dragDirection == DragDirection.up) {
Locator.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.show_create_var_dialog, null, context);
result = true;
} else if (dragDirection == DragDirection.down) {
Locator.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.show_create_matrix_dialog, null, context);
result = true;
}
return result;
}
}
return result;
}
}
static class AngleUnitsChanger implements SimpleOnDragListener.DragProcessor {
static class AngleUnitsChanger implements SimpleOnDragListener.DragProcessor {
@NotNull
private final DigitButtonDragProcessor processor;
@NotNull
private final DigitButtonDragProcessor processor;
@NotNull
private final Context context;
@NotNull
private final Context context;
AngleUnitsChanger(@NotNull Context context) {
this.context = context;
this.processor = new DigitButtonDragProcessor(Locator.getInstance().getKeyboard());
}
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;
@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 {
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 AngleUnit angleUnits = AngleUnit.valueOf(directionText);
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
final AngleUnit oldAngleUnits = AndroidCalculatorEngine.Preferences.angleUnit.getPreference(preferences);
if (oldAngleUnits != angleUnits) {
Locator.getInstance().getPreferenceService().setAngleUnits(angleUnits);
}
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);
}
}
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;
}
}
return result;
}
}
static class NumeralBasesChanger implements SimpleOnDragListener.DragProcessor {
static class NumeralBasesChanger implements SimpleOnDragListener.DragProcessor {
@NotNull
private final Context context;
@NotNull
private final Context context;
NumeralBasesChanger(@NotNull Context context) {
this.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;
@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 {
if (dragButton instanceof NumeralBasesButton) {
final String directionText = ((NumeralBasesButton) dragButton).getText(dragDirection);
if (directionText != null) {
try {
final NumeralBase numeralBase = NumeralBase.valueOf(directionText);
final NumeralBase numeralBase = NumeralBase.valueOf(directionText);
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
final NumeralBase oldNumeralBase = AndroidCalculatorEngine.Preferences.numeralBase.getPreference(preferences);
if (oldNumeralBase != numeralBase) {
Locator.getInstance().getPreferenceService().setNumeralBase(numeralBase);
}
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);
}
}
}
result = true;
} catch (IllegalArgumentException e) {
Log.d(this.getClass().getName(), "Unsupported numeral base: " + directionText);
}
}
}
return result;
}
}
return result;
}
}
static class FunctionsDragProcessor implements SimpleOnDragListener.DragProcessor {
static class FunctionsDragProcessor implements SimpleOnDragListener.DragProcessor {
@NotNull
private Context context;
@NotNull
private Context context;
FunctionsDragProcessor(@NotNull Context context) {
this.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;
@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, context);
result = true;
}
if (dragDirection == DragDirection.up) {
Locator.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.show_create_function_dialog, null, context);
result = true;
}
return result;
}
}
return result;
}
}
}

View File

@@ -10,105 +10,105 @@ import org.solovyev.android.calculator.view.NumeralBaseConverterDialog;
import org.solovyev.android.menu.LabeledMenuItem;
/**
* User: Solovyev_S
* Date: 21.09.12
* Time: 10:55
*/
* 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();
}
},
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);
}
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);
}
},
@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);
}
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);
}
},
@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);
}
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);
}
},
@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);
}
}
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();
}
},
@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 expression = data.getResult();
assert expression != null;
plot(R.string.c_plot) {
@Override
public void onClick(@NotNull CalculatorDisplayViewState data, @NotNull Context context) {
final Generic expression = data.getResult();
assert expression != null;
final CalculatorPlotter plotter = Locator.getInstance().getPlotter();
plotter.plot(expression);
}
final CalculatorPlotter plotter = Locator.getInstance().getPlotter();
plotter.plot(expression);
}
@Override
protected boolean isItemVisibleFor(@NotNull Generic generic, @NotNull JsclOperation operation) {
return Locator.getInstance().getPlotter().isPlotPossibleFor(generic);
}
@Override
protected boolean isItemVisibleFor(@NotNull Generic generic, @NotNull JsclOperation operation) {
return Locator.getInstance().getPlotter().isPlotPossibleFor(generic);
}
};
};
private final int captionId;
private final int captionId;
CalculatorDisplayMenuItem(int captionId) {
this.captionId = 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());
}
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;
}
protected boolean isItemVisibleFor(@NotNull Generic generic, @NotNull JsclOperation operation) {
return true;
}
@NotNull
@Override
public String getCaption(@NotNull Context context) {
return context.getString(captionId);
}
@NotNull
@Override
public String getCaption(@NotNull Context context) {
return context.getString(captionId);
}
}

View File

@@ -16,38 +16,38 @@ import java.util.List;
*/
public class CalculatorDisplayOnClickListener implements View.OnClickListener {
@NotNull
private final FragmentActivity activity;
@NotNull
private final FragmentActivity activity;
public CalculatorDisplayOnClickListener(@NotNull FragmentActivity activity) {
this.activity = activity;
}
public CalculatorDisplayOnClickListener(@NotNull FragmentActivity activity) {
this.activity = activity;
}
@Override
public void onClick(View v) {
if (v instanceof CalculatorDisplayView) {
final CalculatorDisplay cd = Locator.getInstance().getDisplay();
@Override
public void onClick(View v) {
if (v instanceof CalculatorDisplayView) {
final CalculatorDisplay cd = Locator.getInstance().getDisplay();
final CalculatorDisplayViewState displayViewState = cd.getViewState();
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 (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()) {
ContextMenuBuilder.newInstance(activity, "display-menu", ListContextMenu.newInstance(filteredMenuItems)).build(displayViewState).show();
}
if (!filteredMenuItems.isEmpty()) {
ContextMenuBuilder.newInstance(activity, "display-menu", ListContextMenu.newInstance(filteredMenuItems)).build(displayViewState).show();
}
} else {
final String errorMessage = displayViewState.getErrorMessage();
if (errorMessage != null) {
Locator.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.show_evaluation_error, errorMessage, activity);
}
}
}
}
} else {
final String errorMessage = displayViewState.getErrorMessage();
if (errorMessage != null) {
Locator.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.show_evaluation_error, errorMessage, activity);
}
}
}
}
}

View File

@@ -4,17 +4,9 @@ import android.content.SharedPreferences;
import jscl.AngleUnit;
import jscl.NumeralBase;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.Android;
import org.solovyev.android.DeviceModel;
import org.solovyev.android.calculator.math.MathType;
import org.solovyev.android.calculator.model.AndroidCalculatorEngine;
import org.solovyev.android.calculator.plot.PlotLineColor;
import org.solovyev.android.prefs.BooleanPreference;
import org.solovyev.android.prefs.IntegerPreference;
import org.solovyev.android.prefs.LongPreference;
import org.solovyev.android.prefs.Preference;
import org.solovyev.android.prefs.R;
import org.solovyev.android.prefs.StringPreference;
import org.solovyev.android.prefs.*;
import org.solovyev.android.view.VibratorContainer;
import java.text.DecimalFormatSymbols;
@@ -31,191 +23,191 @@ import static org.solovyev.android.DeviceModel.samsung_galaxy_s_2;
*/
public final class CalculatorPreferences {
private CalculatorPreferences() {
throw new AssertionError();
}
private CalculatorPreferences() {
throw new AssertionError();
}
public static final Preference<Integer> appVersion = IntegerPreference.of("application.version", -1);
public static final Preference<Integer> appOpenedCounter = IntegerPreference.of("app_opened_counter", 0);
public static final Preference<Integer> appVersion = IntegerPreference.of("application.version", -1);
public static final Preference<Integer> appOpenedCounter = IntegerPreference.of("app_opened_counter", 0);
public static class OnscreenCalculator {
public static final Preference<Boolean> startOnBoot = BooleanPreference.of("onscreen_start_on_boot", false);
public static final Preference<Boolean> showAppIcon = BooleanPreference.of("onscreen_show_app_icon", true);
public static class OnscreenCalculator {
public static final Preference<Boolean> startOnBoot = BooleanPreference.of("onscreen_start_on_boot", false);
public static final Preference<Boolean> showAppIcon = BooleanPreference.of("onscreen_show_app_icon", true);
public static final Preference<Boolean> removeIconDialogShown = BooleanPreference.of("onscreen_remove_icon_dialog_shown", false);
}
public static class Calculations {
public static class Calculations {
public static final Preference<Boolean> calculateOnFly = BooleanPreference.of("calculations_calculate_on_fly", true);
public static final Preference<Boolean> showCalculationMessagesDialog = BooleanPreference.of("show_calculation_messages_dialog", true);
public static final Preference<Boolean> calculateOnFly = BooleanPreference.of("calculations_calculate_on_fly", true);
public static final Preference<Boolean> showCalculationMessagesDialog = BooleanPreference.of("show_calculation_messages_dialog", true);
public static final Preference<NumeralBase> preferredNumeralBase = StringPreference.ofEnum("preferred_numeral_base", AndroidCalculatorEngine.Preferences.numeralBase.getDefaultValue(), NumeralBase.class);
public static final Preference<AngleUnit> preferredAngleUnits = StringPreference.ofEnum("preferred_angle_units", AndroidCalculatorEngine.Preferences.angleUnit.getDefaultValue(), AngleUnit.class);
public static final Preference<Long> lastPreferredPreferencesCheck = LongPreference.of("preferred_preferences_check_time", 0L);
public static final Preference<NumeralBase> preferredNumeralBase = StringPreference.ofEnum("preferred_numeral_base", AndroidCalculatorEngine.Preferences.numeralBase.getDefaultValue(), NumeralBase.class);
public static final Preference<AngleUnit> preferredAngleUnits = StringPreference.ofEnum("preferred_angle_units", AndroidCalculatorEngine.Preferences.angleUnit.getDefaultValue(), AngleUnit.class);
public static final Preference<Long> lastPreferredPreferencesCheck = LongPreference.of("preferred_preferences_check_time", 0L);
}
}
public static class Gui {
public static class Gui {
public static final Preference<Theme> theme = StringPreference.ofEnum("org.solovyev.android.calculator.CalculatorActivity_calc_theme", Theme.metro_blue_theme, Theme.class);
public static final Preference<Layout> layout = StringPreference.ofEnum("org.solovyev.android.calculator.CalculatorActivity_calc_layout", Layout.main_calculator, Layout.class);
public static final Preference<Boolean> feedbackWindowShown = BooleanPreference.of("feedback_window_shown", false);
public static final Preference<Boolean> notesppAnnounceShown = BooleanPreference.of("notespp_announce_shown", false);
public static final Preference<Boolean> showReleaseNotes = BooleanPreference.of("org.solovyev.android.calculator.CalculatorActivity_show_release_notes", true);
public static final Preference<Boolean> usePrevAsBack = BooleanPreference.of("org.solovyev.android.calculator.CalculatorActivity_use_back_button_as_prev", false);
public static final Preference<Boolean> showEqualsButton = BooleanPreference.of("showEqualsButton", true);
public static final Preference<Boolean> autoOrientation = BooleanPreference.of("autoOrientation", true);
public static final Preference<Boolean> hideNumeralBaseDigits = BooleanPreference.of("hideNumeralBaseDigits", true);
public static final Preference<Theme> theme = StringPreference.ofEnum("org.solovyev.android.calculator.CalculatorActivity_calc_theme", Theme.metro_blue_theme, Theme.class);
public static final Preference<Layout> layout = StringPreference.ofEnum("org.solovyev.android.calculator.CalculatorActivity_calc_layout", Layout.main_calculator, Layout.class);
public static final Preference<Boolean> feedbackWindowShown = BooleanPreference.of("feedback_window_shown", false);
public static final Preference<Boolean> notesppAnnounceShown = BooleanPreference.of("notespp_announce_shown", false);
public static final Preference<Boolean> showReleaseNotes = BooleanPreference.of("org.solovyev.android.calculator.CalculatorActivity_show_release_notes", true);
public static final Preference<Boolean> usePrevAsBack = BooleanPreference.of("org.solovyev.android.calculator.CalculatorActivity_use_back_button_as_prev", false);
public static final Preference<Boolean> showEqualsButton = BooleanPreference.of("showEqualsButton", true);
public static final Preference<Boolean> autoOrientation = BooleanPreference.of("autoOrientation", true);
public static final Preference<Boolean> hideNumeralBaseDigits = BooleanPreference.of("hideNumeralBaseDigits", true);
@NotNull
public static Theme getTheme(@NotNull SharedPreferences preferences) {
return theme.getPreferenceNoError(preferences);
}
@NotNull
public static Theme getTheme(@NotNull SharedPreferences preferences) {
return theme.getPreferenceNoError(preferences);
}
@NotNull
public static Layout getLayout(@NotNull SharedPreferences preferences) {
return layout.getPreferenceNoError(preferences);
}
@NotNull
public static Layout getLayout(@NotNull SharedPreferences preferences) {
return layout.getPreferenceNoError(preferences);
}
public static enum Theme {
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);
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 ThemeType themeType;
@NotNull
private final Integer themeId;
@NotNull
private final Integer themeId;
Theme(@NotNull ThemeType themeType, @NotNull Integer themeId) {
this.themeType = themeType;
this.themeId = themeId;
}
Theme(@NotNull ThemeType themeType, @NotNull Integer themeId) {
this.themeType = themeType;
this.themeId = themeId;
}
@NotNull
public ThemeType getThemeType() {
return themeType;
}
@NotNull
public ThemeType getThemeType() {
return themeType;
}
@NotNull
public Integer getThemeId() {
return themeId;
}
}
@NotNull
public Integer getThemeId() {
return themeId;
}
}
public static enum ThemeType {
metro,
other
}
public static enum ThemeType {
metro,
other
}
public static enum Layout {
main_calculator(R.layout.main_calculator),
main_calculator_mobile(R.layout.main_calculator_mobile),
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),
// not used anymore
@Deprecated
main_cellphone(R.layout.main_calculator),
simple(R.layout.main_calculator);
simple(R.layout.main_calculator);
private final int layoutId;
private final int layoutId;
Layout(int layoutId) {
this.layoutId = layoutId;
}
Layout(int layoutId) {
this.layoutId = layoutId;
}
public int getLayoutId() {
return layoutId;
}
}
}
public int getLayoutId() {
return layoutId;
}
}
}
public static class Graph {
public static final Preference<Boolean> plotImag = BooleanPreference.of("graph_plot_imag", false);
}
public static class Graph {
public static final Preference<Boolean> plotImag = BooleanPreference.of("graph_plot_imag", false);
}
public static class History {
public static final Preference<Boolean> showIntermediateCalculations = BooleanPreference.of("history_show_intermediate_calculations", false);
}
public static class History {
public static final Preference<Boolean> showIntermediateCalculations = BooleanPreference.of("history_show_intermediate_calculations", false);
}
static void setDefaultValues(@NotNull SharedPreferences preferences) {
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 = " ";
}
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);
}
}
AndroidCalculatorEngine.Preferences.groupingSeparator.putPreference(preferences, groupingSeparator);
}
}
if (!AndroidCalculatorEngine.Preferences.angleUnit.isSet(preferences)) {
AndroidCalculatorEngine.Preferences.angleUnit.putDefault(preferences);
}
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.numeralBase.isSet(preferences)) {
AndroidCalculatorEngine.Preferences.numeralBase.putDefault(preferences);
}
if (!AndroidCalculatorEngine.Preferences.multiplicationSign.isSet(preferences)) {
if (isPhoneModel(samsung_galaxy_s) || isPhoneModel(samsung_galaxy_s_2)) {
// workaround ofr samsung galaxy s phones
AndroidCalculatorEngine.Preferences.multiplicationSign.putPreference(preferences, "*");
}
}
if (!AndroidCalculatorEngine.Preferences.multiplicationSign.isSet(preferences)) {
if (isPhoneModel(samsung_galaxy_s) || isPhoneModel(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, 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.plotImag);
applyDefaultPreference(preferences, History.showIntermediateCalculations);
applyDefaultPreference(preferences, Calculations.calculateOnFly);
applyDefaultPreference(preferences, Calculations.preferredAngleUnits);
applyDefaultPreference(preferences, Calculations.preferredNumeralBase);
applyDefaultPreference(preferences, Graph.plotImag);
applyDefaultPreference(preferences, History.showIntermediateCalculations);
applyDefaultPreference(preferences, Calculations.calculateOnFly);
applyDefaultPreference(preferences, Calculations.preferredAngleUnits);
applyDefaultPreference(preferences, Calculations.preferredNumeralBase);
applyDefaultPreference(preferences, OnscreenCalculator.showAppIcon);
applyDefaultPreference(preferences, OnscreenCalculator.startOnBoot);
applyDefaultPreference(preferences, OnscreenCalculator.showAppIcon);
applyDefaultPreference(preferences, OnscreenCalculator.startOnBoot);
// renew value after each application start
Calculations.showCalculationMessagesDialog.putDefault(preferences);
Calculations.lastPreferredPreferencesCheck.putDefault(preferences);
// 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.hapticFeedbackEnabled.isSet(preferences)) {
VibratorContainer.Preferences.hapticFeedbackEnabled.putPreference(preferences, true);
}
if (!VibratorContainer.Preferences.hapticFeedbackDuration.isSet(preferences)) {
VibratorContainer.Preferences.hapticFeedbackDuration.putPreference(preferences, 60L);
}
if (!VibratorContainer.Preferences.hapticFeedbackDuration.isSet(preferences)) {
VibratorContainer.Preferences.hapticFeedbackDuration.putPreference(preferences, 60L);
}
}
}
private static void applyDefaultPreference(@NotNull SharedPreferences preferences, @NotNull Preference<?> preference) {
preference.tryPutDefault(preferences);
}
private static void applyDefaultPreference(@NotNull SharedPreferences preferences, @NotNull Preference<?> preference) {
preference.tryPutDefault(preferences);
}
}

View File

@@ -14,39 +14,39 @@ import org.solovyev.android.menu.AMenuItem;
*/
enum ConversionMenuItem implements AMenuItem<CalculatorDisplayViewState> {
convert_to_bin(NumeralBase.bin),
convert_to_dec(NumeralBase.dec),
convert_to_hex(NumeralBase.hex);
convert_to_bin(NumeralBase.bin),
convert_to_dec(NumeralBase.dec),
convert_to_hex(NumeralBase.hex);
@NotNull
private final NumeralBase toNumeralBase;
@NotNull
private final NumeralBase toNumeralBase;
ConversionMenuItem(@NotNull NumeralBase toNumeralBase) {
this.toNumeralBase = toNumeralBase;
}
ConversionMenuItem(@NotNull NumeralBase toNumeralBase) {
this.toNumeralBase = toNumeralBase;
}
protected boolean isItemVisibleFor(@NotNull Generic generic, @NotNull JsclOperation operation) {
boolean result = false;
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);
}
}
}
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;
}
return result;
}
@Override
public void onClick(@NotNull CalculatorDisplayViewState data, @NotNull Context context) {
final Generic result = data.getResult();
@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);
}
}
if (result != null) {
Locator.getInstance().getCalculator().convert(result, this.toNumeralBase);
}
}
}

View File

@@ -20,17 +20,17 @@ import org.solovyev.common.math.Point2d;
*/
public class DigitButtonDragProcessor implements SimpleOnDragListener.DragProcessor {
@NotNull
private CalculatorKeyboard calculatorKeyboard;
@NotNull
private CalculatorKeyboard calculatorKeyboard;
public DigitButtonDragProcessor(@NotNull CalculatorKeyboard calculatorKeyboard) {
this.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));
calculatorKeyboard.buttonPressed(((DirectionDragButton) dragButton).getText(dragDirection));
return true;
}

View File

@@ -14,81 +14,81 @@ import org.solovyev.common.msg.MessageType;
*/
public class FixableMessage implements Parcelable {
public static final Creator<FixableMessage> CREATOR = new Creator<FixableMessage>() {
@Override
public FixableMessage createFromParcel(@NotNull Parcel in) {
return FixableMessage.fromParcel(in);
}
public static final Creator<FixableMessage> CREATOR = new Creator<FixableMessage>() {
@Override
public FixableMessage createFromParcel(@NotNull Parcel in) {
return FixableMessage.fromParcel(in);
}
@Override
public FixableMessage[] newArray(int size) {
return new FixableMessage[size];
}
};
@Override
public FixableMessage[] newArray(int size) {
return new FixableMessage[size];
}
};
@NotNull
private static FixableMessage fromParcel(@NotNull Parcel in) {
final String message = in.readString();
final MessageType messageType = (MessageType) in.readSerializable();
final FixableError fixableError = (FixableError) in.readSerializable();
@NotNull
private static FixableMessage fromParcel(@NotNull Parcel in) {
final String message = in.readString();
final MessageType messageType = (MessageType) in.readSerializable();
final FixableError fixableError = (FixableError) in.readSerializable();
return new FixableMessage(message, messageType, fixableError);
}
return new FixableMessage(message, messageType, fixableError);
}
@NotNull
private final String message;
@NotNull
private final String message;
@NotNull
private final MessageType messageType;
@NotNull
private final MessageType messageType;
@Nullable
private final FixableError fixableError;
@Nullable
private final FixableError fixableError;
public FixableMessage(@NotNull Message message) {
this.message = message.getLocalizedMessage();
public FixableMessage(@NotNull Message message) {
this.message = message.getLocalizedMessage();
int messageLevel = message.getMessageLevel().getMessageLevel();
if(messageLevel < MessageType.info.getMessageLevel()) {
if (messageLevel < MessageType.info.getMessageLevel()) {
this.messageType = MessageType.info;
} else if (messageLevel < MessageType.warning.getMessageLevel()) {
this.messageType = MessageType.warning;
} else {
this.messageType = MessageType.error;
}
this.fixableError = CalculatorFixableError.getErrorByMessageCode(message.getMessageCode());
}
this.fixableError = CalculatorFixableError.getErrorByMessageCode(message.getMessageCode());
}
public FixableMessage(@NotNull String message,
public FixableMessage(@NotNull String message,
@NotNull MessageType messageType,
@Nullable FixableError fixableError) {
this.message = message;
this.messageType = messageType;
this.fixableError = fixableError;
}
this.message = message;
this.messageType = messageType;
this.fixableError = fixableError;
}
@Override
public int describeContents() {
return 0;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(@NotNull Parcel out, int flags) {
out.writeString(message);
out.writeSerializable(messageType);
out.writeSerializable(fixableError);
}
@Override
public void writeToParcel(@NotNull Parcel out, int flags) {
out.writeString(message);
out.writeSerializable(messageType);
out.writeSerializable(fixableError);
}
@NotNull
public String getMessage() {
return message;
}
@NotNull
public String getMessage() {
return message;
}
@NotNull
public MessageType getMessageType() {
return messageType;
}
@NotNull
public MessageType getMessageType() {
return messageType;
}
@Nullable
public FixableError getFixableError() {
return fixableError;
}
@Nullable
public FixableError getFixableError() {
return fixableError;
}
}

View File

@@ -30,227 +30,226 @@ import java.util.List;
*/
public class FixableMessagesDialog extends SherlockActivity {
private static final String INPUT = "input";
private static final String INPUT = "input";
@NotNull
private Input input = new Input(Collections.<FixableMessage>emptyList(), false);
@NotNull
private Input input = new Input(Collections.<FixableMessage>emptyList(), false);
public FixableMessagesDialog() {
}
public FixableMessagesDialog() {
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cpp_fixable_messages_dialog);
setContentView(R.layout.cpp_fixable_messages_dialog);
final Intent intent = getIntent();
if (intent != null) {
parseIntent(intent);
}
final Intent intent = getIntent();
if (intent != null) {
parseIntent(intent);
}
final CheckBox doNotShowCalculationMessagesCheckbox = (CheckBox) findViewById(R.id.cpp_do_not_show_fixable_messages_checkbox);
if ( input.isShowCheckbox() ) {
final CheckBox doNotShowCalculationMessagesCheckbox = (CheckBox) findViewById(R.id.cpp_do_not_show_fixable_messages_checkbox);
if (input.isShowCheckbox()) {
doNotShowCalculationMessagesCheckbox.setVisibility(View.VISIBLE);
} else {
doNotShowCalculationMessagesCheckbox.setVisibility(View.GONE);
}
final Button closeButton = (Button) findViewById(R.id.close_button);
closeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (doNotShowCalculationMessagesCheckbox.isChecked()) {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(FixableMessagesDialog.this);
CalculatorPreferences.Calculations.showCalculationMessagesDialog.putPreference(prefs, false);
}
final Button closeButton = (Button) findViewById(R.id.close_button);
closeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (doNotShowCalculationMessagesCheckbox.isChecked()) {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(FixableMessagesDialog.this);
CalculatorPreferences.Calculations.showCalculationMessagesDialog.putPreference(prefs, false);
}
FixableMessagesDialog.this.finish();
}
});
}
FixableMessagesDialog.this.finish();
}
});
}
private void parseIntent(@NotNull Intent intent) {
final Input input = intent.getParcelableExtra(INPUT);
if (input != null) {
this.input = input;
onInputChanged();
}
}
private void parseIntent(@NotNull Intent intent) {
final Input input = intent.getParcelableExtra(INPUT);
if (input != null) {
this.input = input;
onInputChanged();
}
}
private void onInputChanged() {
final ViewGroup viewGroup = (ViewGroup) findViewById(R.id.cpp_fixable_messages_container);
viewGroup.removeAllViews();
private void onInputChanged() {
final ViewGroup viewGroup = (ViewGroup) findViewById(R.id.cpp_fixable_messages_container);
viewGroup.removeAllViews();
final LayoutInflater layoutInflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final LayoutInflater layoutInflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final List<FixableMessage> messages = input.getMessages();
for (final FixableMessage message : messages) {
final View view = layoutInflater.inflate(R.layout.cpp_fixable_messages_dialog_message, null);
final List<FixableMessage> messages = input.getMessages();
for (final FixableMessage message : messages) {
final View view = layoutInflater.inflate(R.layout.cpp_fixable_messages_dialog_message, null);
final TextView calculationMessagesTextView = (TextView) view.findViewById(R.id.cpp_fixable_messages_text_view);
calculationMessagesTextView.setText(message.getMessage());
final TextView calculationMessagesTextView = (TextView) view.findViewById(R.id.cpp_fixable_messages_text_view);
calculationMessagesTextView.setText(message.getMessage());
final Button fixButton = (Button) view.findViewById(R.id.cpp_fix_button);
final FixableError fixableError = message.getFixableError();
if (fixableError == null) {
fixButton.setVisibility(View.GONE);
fixButton.setOnClickListener(null);
} else {
fixButton.setVisibility(View.VISIBLE);
fixButton.setOnClickListener(new FixErrorOnClickListener(messages, message));
final Button fixButton = (Button) view.findViewById(R.id.cpp_fix_button);
final FixableError fixableError = message.getFixableError();
if (fixableError == null) {
fixButton.setVisibility(View.GONE);
fixButton.setOnClickListener(null);
} else {
fixButton.setVisibility(View.VISIBLE);
fixButton.setOnClickListener(new FixErrorOnClickListener(messages, message));
final CharSequence fixCaption = fixableError.getFixCaption();
if (!Strings.isEmpty(fixCaption)) {
fixButton.setText(fixCaption);
}
}
}
viewGroup.addView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
}
viewGroup.addView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
}
}
}
@Override
protected void onNewIntent(@NotNull Intent intent) {
super.onNewIntent(intent);
parseIntent(intent);
}
@Override
protected void onNewIntent(@NotNull Intent intent) {
super.onNewIntent(intent);
parseIntent(intent);
}
/*
**********************************************************************
*
* STATIC
*
**********************************************************************
*/
/*
**********************************************************************
*
* STATIC
*
**********************************************************************
*/
public static void showDialogForMessages(@NotNull List<Message> messages,
public static void showDialogForMessages(@NotNull List<Message> messages,
@NotNull Context context,
boolean showCheckbox) {
if (!messages.isEmpty()) {
final Intent intent = new Intent(context, FixableMessagesDialog.class);
if (!messages.isEmpty()) {
final Intent intent = new Intent(context, FixableMessagesDialog.class);
intent.putExtra(INPUT, Input.fromMessages(messages, showCheckbox));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(INPUT, Input.fromMessages(messages, showCheckbox));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
context.startActivity(intent);
}
}
public static void showDialog(@NotNull List<FixableMessage> messages,
public static void showDialog(@NotNull List<FixableMessage> messages,
@NotNull Context context,
boolean showCheckbox) {
if (!messages.isEmpty()) {
final Intent intent = new Intent(context, FixableMessagesDialog.class);
if (!messages.isEmpty()) {
final Intent intent = new Intent(context, FixableMessagesDialog.class);
intent.putExtra(INPUT, new Input(messages, showCheckbox));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(INPUT, new Input(messages, showCheckbox));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
context.startActivity(intent);
}
}
private static final class Input implements Parcelable {
private static final class Input implements Parcelable {
public static final Creator<Input> CREATOR = new Creator<Input>() {
@Override
public Input createFromParcel(@NotNull Parcel in) {
return Input.fromParcel(in);
}
public static final Creator<Input> CREATOR = new Creator<Input>() {
@Override
public Input createFromParcel(@NotNull Parcel in) {
return Input.fromParcel(in);
}
@Override
public Input[] newArray(int size) {
return new Input[size];
}
};
@Override
public Input[] newArray(int size) {
return new Input[size];
}
};
@NotNull
private static Input fromParcel(@NotNull Parcel in) {
final List<FixableMessage> messages = new ArrayList<FixableMessage>();
@NotNull
private static Input fromParcel(@NotNull Parcel in) {
final List<FixableMessage> messages = new ArrayList<FixableMessage>();
boolean showCheckbox = in.readInt() == 1;
in.readTypedList(messages, FixableMessage.CREATOR);
return new Input(messages, showCheckbox);
}
in.readTypedList(messages, FixableMessage.CREATOR);
return new Input(messages, showCheckbox);
}
@NotNull
private List<FixableMessage> messages = new ArrayList<FixableMessage>();
@NotNull
private List<FixableMessage> messages = new ArrayList<FixableMessage>();
private boolean showCheckbox;
private Input(@NotNull List<FixableMessage> messages, boolean showCheckbox) {
this.messages = messages;
private Input(@NotNull List<FixableMessage> messages, boolean showCheckbox) {
this.messages = messages;
this.showCheckbox = showCheckbox;
}
@NotNull
public List<FixableMessage> getMessages() {
return messages;
}
@NotNull
public List<FixableMessage> getMessages() {
return messages;
}
@Override
public int describeContents() {
return 0;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(@NotNull Parcel out, int flags) {
@Override
public void writeToParcel(@NotNull Parcel out, int flags) {
out.writeInt(showCheckbox ? 1 : 0);
out.writeTypedList(messages);
}
out.writeTypedList(messages);
}
@NotNull
public static Input fromMessages(@NotNull List<Message> messages, boolean showCheckbox) {
final List<FixableMessage> stringMessages = new ArrayList<FixableMessage>(messages.size());
for (Message message : messages) {
stringMessages.add(new FixableMessage(message));
}
@NotNull
public static Input fromMessages(@NotNull List<Message> messages, boolean showCheckbox) {
final List<FixableMessage> stringMessages = new ArrayList<FixableMessage>(messages.size());
for (Message message : messages) {
stringMessages.add(new FixableMessage(message));
}
return new Input(stringMessages, showCheckbox);
}
return new Input(stringMessages, showCheckbox);
}
public boolean isShowCheckbox() {
return showCheckbox;
}
}
private class FixErrorOnClickListener implements View.OnClickListener {
private class FixErrorOnClickListener implements View.OnClickListener {
@NotNull
private final List<FixableMessage> messages;
@NotNull
private final List<FixableMessage> messages;
@NotNull
private final FixableMessage currentMessage;
@NotNull
private final FixableMessage currentMessage;
public FixErrorOnClickListener(@NotNull List<FixableMessage> messages,
@NotNull FixableMessage message) {
this.messages = messages;
this.currentMessage = message;
}
public FixErrorOnClickListener(@NotNull List<FixableMessage> messages,
@NotNull FixableMessage message) {
this.messages = messages;
this.currentMessage = message;
}
@Override
public void onClick(View v) {
final List<FixableMessage> filteredMessages = new ArrayList<FixableMessage>(messages.size() - 1);
for (FixableMessage message : messages) {
if ( message.getFixableError() == null ) {
filteredMessages.add(message);
} else if ( message.getFixableError() != currentMessage.getFixableError() ) {
filteredMessages.add(message);
}
}
@Override
public void onClick(View v) {
final List<FixableMessage> filteredMessages = new ArrayList<FixableMessage>(messages.size() - 1);
for (FixableMessage message : messages) {
if (message.getFixableError() == null) {
filteredMessages.add(message);
} else if (message.getFixableError() != currentMessage.getFixableError()) {
filteredMessages.add(message);
}
}
currentMessage.getFixableError().fix();
currentMessage.getFixableError().fix();
if (!filteredMessages.isEmpty()) {
FixableMessagesDialog.this.input = new Input(filteredMessages, FixableMessagesDialog.this.input.showCheckbox);
onInputChanged();
} else {
FixableMessagesDialog.this.finish();
}
}
}
if (!filteredMessages.isEmpty()) {
FixableMessagesDialog.this.input = new Input(filteredMessages, FixableMessagesDialog.this.input.showCheckbox);
onInputChanged();
} else {
FixableMessagesDialog.this.finish();
}
}
}
}

View File

@@ -8,100 +8,100 @@ import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.jscl.JsclOperation;
/**
* User: serso
* Date: 11/18/12
* Time: 1:40 PM
*/
* 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);
}
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];
}
};
@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();
@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);
}
CalculatorDisplayViewState calculatorDisplayViewState;
if (valid) {
calculatorDisplayViewState = CalculatorDisplayViewStateImpl.newValidState(operation, null, stringResult, selection);
} else {
calculatorDisplayViewState = CalculatorDisplayViewStateImpl.newErrorState(operation, errorMessage);
}
return new ParcelableCalculatorDisplayViewState(calculatorDisplayViewState);
}
return new ParcelableCalculatorDisplayViewState(calculatorDisplayViewState);
}
@NotNull
private CalculatorDisplayViewState viewState;
@NotNull
private CalculatorDisplayViewState viewState;
public ParcelableCalculatorDisplayViewState(@NotNull CalculatorDisplayViewState viewState) {
this.viewState = viewState;
}
public ParcelableCalculatorDisplayViewState(@NotNull CalculatorDisplayViewState viewState) {
this.viewState = viewState;
}
@Override
@NotNull
public String getText() {
return viewState.getText();
}
@Override
@NotNull
public String getText() {
return viewState.getText();
}
@Override
public int getSelection() {
return viewState.getSelection();
}
@Override
public int getSelection() {
return viewState.getSelection();
}
@Override
@Nullable
public Generic getResult() {
return viewState.getResult();
}
@Override
@Nullable
public Generic getResult() {
return viewState.getResult();
}
@Override
public boolean isValid() {
return viewState.isValid();
}
@Override
public boolean isValid() {
return viewState.isValid();
}
@Override
@Nullable
public String getErrorMessage() {
return viewState.getErrorMessage();
}
@Override
@Nullable
public String getErrorMessage() {
return viewState.getErrorMessage();
}
@Override
@NotNull
public JsclOperation getOperation() {
return viewState.getOperation();
}
@Override
@NotNull
public JsclOperation getOperation() {
return viewState.getOperation();
}
@Override
@Nullable
public String getStringResult() {
return viewState.getStringResult();
}
@Override
@Nullable
public String getStringResult() {
return viewState.getStringResult();
}
@Override
public int describeContents() {
return 0;
}
@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());
}
@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

@@ -5,57 +5,57 @@ import android.os.Parcelable;
import org.jetbrains.annotations.NotNull;
/**
* User: serso
* Date: 11/18/12
* Time: 1:40 PM
*/
* 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);
}
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];
}
};
@Override
public ParcelableCalculatorEditorViewState[] newArray(int size) {
return new ParcelableCalculatorEditorViewState[size];
}
};
@NotNull
private CalculatorEditorViewState viewState;
@NotNull
private CalculatorEditorViewState viewState;
public ParcelableCalculatorEditorViewState(@NotNull CalculatorEditorViewState viewState) {
this.viewState = 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));
}
@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
@NotNull
public String getText() {
return viewState.getText();
}
@Override
public int getSelection() {
return viewState.getSelection();
}
@Override
public int getSelection() {
return viewState.getSelection();
}
@Override
public int describeContents() {
return 0;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(@NotNull Parcel out, int flags) {
out.writeString(viewState.getText());
out.writeInt(viewState.getSelection());
}
@Override
public void writeToParcel(@NotNull Parcel out, int flags) {
out.writeString(viewState.getText());
out.writeInt(viewState.getSelection());
}
}

View File

@@ -8,99 +8,99 @@ import org.solovyev.common.msg.MessageLevel;
import org.solovyev.common.msg.MessageType;
/**
* User: serso
* Date: 1/20/13
* Time: 1:04 PM
*/
* User: serso
* Date: 1/20/13
* Time: 1:04 PM
*/
public final class ParcelableDialogData implements DialogData, Parcelable {
/*
**********************************************************************
*
* STATIC
*
**********************************************************************
*/
/*
**********************************************************************
*
* STATIC
*
**********************************************************************
*/
public final static Creator<ParcelableDialogData> CREATOR = new Creator<ParcelableDialogData>() {
@Override
public ParcelableDialogData createFromParcel(@NotNull Parcel in) {
return fromParcel(in);
}
public final static Creator<ParcelableDialogData> CREATOR = new Creator<ParcelableDialogData>() {
@Override
public ParcelableDialogData createFromParcel(@NotNull Parcel in) {
return fromParcel(in);
}
@Override
public ParcelableDialogData[] newArray(int size) {
return new ParcelableDialogData[size];
}
};
@Override
public ParcelableDialogData[] newArray(int size) {
return new ParcelableDialogData[size];
}
};
/*
**********************************************************************
*
* FIELDS
*
**********************************************************************
*/
/*
**********************************************************************
*
* FIELDS
*
**********************************************************************
*/
@NotNull
private DialogData nestedData;
@NotNull
private DialogData nestedData;
/*
**********************************************************************
*
* CONSTRUCTORS
*
**********************************************************************
*/
/*
**********************************************************************
*
* CONSTRUCTORS
*
**********************************************************************
*/
public ParcelableDialogData(@NotNull DialogData nestedData) {
this.nestedData = nestedData;
}
public ParcelableDialogData(@NotNull DialogData nestedData) {
this.nestedData = nestedData;
}
@NotNull
public static ParcelableDialogData wrap(@NotNull DialogData nestedData) {
if (nestedData instanceof ParcelableDialogData) {
return ((ParcelableDialogData) nestedData);
} else {
return new ParcelableDialogData(nestedData);
}
}
@NotNull
public static ParcelableDialogData wrap(@NotNull DialogData nestedData) {
if (nestedData instanceof ParcelableDialogData) {
return ((ParcelableDialogData) nestedData);
} else {
return new ParcelableDialogData(nestedData);
}
}
@NotNull
public static ParcelableDialogData fromParcel(@NotNull Parcel in) {
final String message = in.readString();
final MessageType messageType = MessageType.values()[in.readInt()];
final String title = in.readString();
return wrap(StringDialogData.newInstance(message, messageType, title));
}
@NotNull
public static ParcelableDialogData fromParcel(@NotNull Parcel in) {
final String message = in.readString();
final MessageType messageType = MessageType.values()[in.readInt()];
final String title = in.readString();
return wrap(StringDialogData.newInstance(message, messageType, title));
}
@NotNull
@Override
public String getMessage() {
return nestedData.getMessage();
}
@NotNull
@Override
public String getMessage() {
return nestedData.getMessage();
}
@NotNull
@Override
public MessageLevel getMessageLevel() {
return nestedData.getMessageLevel();
}
@NotNull
@Override
public MessageLevel getMessageLevel() {
return nestedData.getMessageLevel();
}
@Nullable
@Override
public String getTitle() {
return nestedData.getTitle();
}
@Nullable
@Override
public String getTitle() {
return nestedData.getTitle();
}
@Override
public int describeContents() {
return 0;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(@NotNull Parcel out, int flags) {
out.writeString(this.getMessage());
out.writeInt(this.getMessageLevel().getMessageLevel());
out.writeString(this.getTitle());
}
@Override
public void writeToParcel(@NotNull Parcel out, int flags) {
out.writeString(this.getMessage());
out.writeInt(this.getMessageLevel().getMessageLevel());
out.writeString(this.getTitle());
}
}

View File

@@ -18,63 +18,63 @@ import java.util.Set;
*/
public class AndroidExternalListenersContainer implements CalculatorExternalListenersContainer, CalculatorEventListener {
/*
**********************************************************************
*
* CONSTANTS
*
**********************************************************************
*/
/*
**********************************************************************
*
* CONSTANTS
*
**********************************************************************
*/
public static final String EVENT_ID_EXTRA = "eventId";
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 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";
public static final String DISPLAY_STATE_EXTRA = "displayState";
private static final String TAG = "Calculator++ External Listener Helper";
private static final String TAG = "Calculator++ External Listener Helper";
@NotNull
private final Set<Class<?>> externalListeners = new HashSet<Class<?>>();
private final Set<Class<?>> externalListeners = new HashSet<Class<?>>();
@NotNull
private final CalculatorEventHolder lastEvent = new CalculatorEventHolder(CalculatorUtils.createFirstEventDataId());
@NotNull
private final CalculatorEventHolder lastEvent = new CalculatorEventHolder(CalculatorUtils.createFirstEventDataId());
public AndroidExternalListenersContainer(@NotNull Calculator calculator) {
calculator.addCalculatorEventListener(this);
}
public AndroidExternalListenersContainer(@NotNull Calculator calculator) {
calculator.addCalculatorEventListener(this);
}
public void onEditorStateChanged(@NotNull Context context,
@NotNull CalculatorEventData calculatorEventData,
@NotNull CalculatorEditorViewState editorViewState) {
public void onEditorStateChanged(@NotNull Context context,
@NotNull CalculatorEventData calculatorEventData,
@NotNull CalculatorEditorViewState editorViewState) {
for (Class<?> externalListener : getExternalListenersSync()) {
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");
}
}
for (Class<?> externalListener : getExternalListenersSync()) {
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 : getExternalListenersSync()) {
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");
}
}
private void onDisplayStateChanged(@NotNull Context context,
@NotNull CalculatorEventData calculatorEventData,
@NotNull CalculatorDisplayViewState displayViewState) {
for (Class<?> externalListener : getExternalListenersSync()) {
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");
}
}
@NotNull
private Set<Class<?>> getExternalListenersSync() {
@@ -84,43 +84,43 @@ public class AndroidExternalListenersContainer implements CalculatorExternalList
}
@Override
public void addExternalListener(@NotNull Class<?> externalCalculatorClass) {
public void addExternalListener(@NotNull Class<?> externalCalculatorClass) {
synchronized (externalListeners) {
externalListeners.add(externalCalculatorClass);
}
}
@Override
public boolean removeExternalListener(@NotNull Class<?> externalCalculatorClass) {
@Override
public boolean removeExternalListener(@NotNull Class<?> externalCalculatorClass) {
synchronized (externalListeners) {
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();
@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());
Locator.getInstance().getNotifier().showDebugMessage(TAG, "Editor state changed: " + newEditorState.getText());
onEditorStateChanged(App.getApplication(), calculatorEventData, newEditorState);
break;
onEditorStateChanged(App.getApplication(), calculatorEventData, newEditorState);
break;
case display_state_changed:
final CalculatorDisplayChangeEventData displayChangeData = (CalculatorDisplayChangeEventData) data;
final CalculatorDisplayViewState newDisplayState = displayChangeData.getNewValue();
case display_state_changed:
final CalculatorDisplayChangeEventData displayChangeData = (CalculatorDisplayChangeEventData) data;
final CalculatorDisplayViewState newDisplayState = displayChangeData.getNewValue();
Locator.getInstance().getNotifier().showDebugMessage(TAG, "Display state changed: " + newDisplayState.getText());
Locator.getInstance().getNotifier().showDebugMessage(TAG, "Display state changed: " + newDisplayState.getText());
onDisplayStateChanged(App.getApplication(), calculatorEventData, newDisplayState);
break;
}
}
}
onDisplayStateChanged(App.getApplication(), calculatorEventData, newDisplayState);
break;
}
}
}
}

View File

@@ -16,77 +16,77 @@ import org.solovyev.common.MutableObject;
*/
public class DefaultExternalCalculatorIntentHandler implements ExternalCalculatorIntentHandler {
private static final String TAG = ExternalCalculatorIntentHandler.class.getSimpleName();
private static final String TAG = ExternalCalculatorIntentHandler.class.getSimpleName();
@NotNull
private final MutableObject<Long> lastDisplayEventId = new MutableObject<Long>(0L);
@NotNull
private final MutableObject<Long> lastDisplayEventId = new MutableObject<Long>(0L);
@NotNull
private final MutableObject<Long> lastEditorEventId = new MutableObject<Long>(0L);
@NotNull
private final MutableObject<Long> lastEditorEventId = new MutableObject<Long>(0L);
@NotNull
private final ExternalCalculatorStateUpdater stateUpdater;
@NotNull
private final ExternalCalculatorStateUpdater stateUpdater;
public DefaultExternalCalculatorIntentHandler(@NotNull ExternalCalculatorStateUpdater stateUpdater) {
this.stateUpdater = stateUpdater;
}
public DefaultExternalCalculatorIntentHandler(@NotNull ExternalCalculatorStateUpdater stateUpdater) {
this.stateUpdater = stateUpdater;
}
@Override
public void onIntent(@NotNull Context context, @NotNull Intent intent) {
@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!");
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);
final Long eventId = intent.getLongExtra(AndroidExternalListenersContainer.EVENT_ID_EXTRA, 0L);
boolean updateEditor = false;
synchronized (lastEditorEventId) {
if (eventId > lastEditorEventId.getObject()) {
lastEditorEventId.setObject(eventId);
updateEditor = true;
}
}
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!");
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;
}
}
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()) ) {
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 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 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());
}
protected void onEditorStateChanged(@NotNull Context context, @NotNull CalculatorEditorViewState editorViewState) {
updateState(context, editorViewState, Locator.getInstance().getDisplay().getViewState());
}
}

View File

@@ -11,5 +11,5 @@ import org.jetbrains.annotations.NotNull;
*/
public interface ExternalCalculatorIntentHandler {
void onIntent(@NotNull Context context, @NotNull Intent intent);
void onIntent(@NotNull Context context, @NotNull Intent intent);
}

View File

@@ -12,7 +12,7 @@ import org.solovyev.android.calculator.CalculatorEditorViewState;
*/
public interface ExternalCalculatorStateUpdater {
void updateState(@NotNull Context context,
@NotNull CalculatorEditorViewState editorState,
@NotNull CalculatorDisplayViewState displayState);
void updateState(@NotNull Context context,
@NotNull CalculatorEditorViewState editorState,
@NotNull CalculatorDisplayViewState displayState);
}

View File

@@ -39,248 +39,248 @@ import java.util.List;
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 GROUPING_SEPARATOR_P_KEY = "org.solovyev.android.calculator.CalculatorActivity_calc_grouping_separator";
private static final String MULTIPLICATION_SIGN_P_KEY = "org.solovyev.android.calculator.CalculatorActivity_calc_multiplication_sign";
private static final String MULTIPLICATION_SIGN_DEFAULT = "×";
private static final String MULTIPLICATION_SIGN_P_KEY = "org.solovyev.android.calculator.CalculatorActivity_calc_multiplication_sign";
private static final String MULTIPLICATION_SIGN_DEFAULT = "×";
private static final String MAX_CALCULATION_TIME_P_KEY = "calculation.max_calculation_time";
private static final String MAX_CALCULATION_TIME_DEFAULT = "5";
private static final String MAX_CALCULATION_TIME_P_KEY = "calculation.max_calculation_time";
private static final String MAX_CALCULATION_TIME_DEFAULT = "5";
private static final String SCIENCE_NOTATION_P_KEY = "calculation.output.science_notation";
private static final boolean SCIENCE_NOTATION_DEFAULT = false;
private static final String SCIENCE_NOTATION_P_KEY = "calculation.output.science_notation";
private static final boolean SCIENCE_NOTATION_DEFAULT = false;
private static final String ROUND_RESULT_P_KEY = "org.solovyev.android.calculator.CalculatorModel_round_result";
private static final boolean ROUND_RESULT_DEFAULT = true;
private static final String ROUND_RESULT_P_KEY = "org.solovyev.android.calculator.CalculatorModel_round_result";
private static final boolean ROUND_RESULT_DEFAULT = true;
private static final String RESULT_PRECISION_P_KEY = "org.solovyev.android.calculator.CalculatorModel_result_precision";
private static final String RESULT_PRECISION_DEFAULT = "5";
private static final String RESULT_PRECISION_P_KEY = "org.solovyev.android.calculator.CalculatorModel_result_precision";
private static final String RESULT_PRECISION_DEFAULT = "5";
private static final String NUMERAL_BASES_P_KEY = "org.solovyev.android.calculator.CalculatorActivity_numeral_bases";
private static final String NUMERAL_BASES_DEFAULT = "dec";
private static final String NUMERAL_BASES_P_KEY = "org.solovyev.android.calculator.CalculatorActivity_numeral_bases";
private static final String NUMERAL_BASES_DEFAULT = "dec";
private static final String ANGLE_UNITS_P_KEY = "org.solovyev.android.calculator.CalculatorActivity_angle_units";
private static final String ANGLE_UNITS_DEFAULT = "deg";
private static final String ANGLE_UNITS_P_KEY = "org.solovyev.android.calculator.CalculatorActivity_angle_units";
private static final String ANGLE_UNITS_DEFAULT = "deg";
public static class Preferences {
public static final Preference<String> groupingSeparator = StringPreference.of(GROUPING_SEPARATOR_P_KEY, JsclMathEngine.GROUPING_SEPARATOR_DEFAULT);
public static final Preference<String> multiplicationSign = StringPreference.of(MULTIPLICATION_SIGN_P_KEY, MULTIPLICATION_SIGN_DEFAULT);
public static final Preference<Integer> precision = StringPreference.ofTypedValue(RESULT_PRECISION_P_KEY, RESULT_PRECISION_DEFAULT, NumberMapper.of(Integer.class));
public static final Preference<Boolean> roundResult = BooleanPreference.of(ROUND_RESULT_P_KEY, ROUND_RESULT_DEFAULT);
public static final Preference<NumeralBase> numeralBase = StringPreference.ofTypedValue(NUMERAL_BASES_P_KEY, NUMERAL_BASES_DEFAULT, EnumMapper.of(NumeralBase.class));
public static final Preference<AngleUnit> angleUnit = StringPreference.ofTypedValue(ANGLE_UNITS_P_KEY, ANGLE_UNITS_DEFAULT, EnumMapper.of(AngleUnit.class));
public static final Preference<Boolean> scienceNotation = BooleanPreference.of(SCIENCE_NOTATION_P_KEY, SCIENCE_NOTATION_DEFAULT);
public static final Preference<Integer> maxCalculationTime = StringPreference.ofTypedValue(MAX_CALCULATION_TIME_P_KEY, MAX_CALCULATION_TIME_DEFAULT, NumberMapper.of(Integer.class));
public static class Preferences {
public static final Preference<String> groupingSeparator = StringPreference.of(GROUPING_SEPARATOR_P_KEY, JsclMathEngine.GROUPING_SEPARATOR_DEFAULT);
public static final Preference<String> multiplicationSign = StringPreference.of(MULTIPLICATION_SIGN_P_KEY, MULTIPLICATION_SIGN_DEFAULT);
public static final Preference<Integer> precision = StringPreference.ofTypedValue(RESULT_PRECISION_P_KEY, RESULT_PRECISION_DEFAULT, NumberMapper.of(Integer.class));
public static final Preference<Boolean> roundResult = BooleanPreference.of(ROUND_RESULT_P_KEY, ROUND_RESULT_DEFAULT);
public static final Preference<NumeralBase> numeralBase = StringPreference.ofTypedValue(NUMERAL_BASES_P_KEY, NUMERAL_BASES_DEFAULT, EnumMapper.of(NumeralBase.class));
public static final Preference<AngleUnit> angleUnit = StringPreference.ofTypedValue(ANGLE_UNITS_P_KEY, ANGLE_UNITS_DEFAULT, EnumMapper.of(AngleUnit.class));
public static final Preference<Boolean> scienceNotation = BooleanPreference.of(SCIENCE_NOTATION_P_KEY, SCIENCE_NOTATION_DEFAULT);
public static final Preference<Integer> maxCalculationTime = StringPreference.ofTypedValue(MAX_CALCULATION_TIME_P_KEY, MAX_CALCULATION_TIME_DEFAULT, NumberMapper.of(Integer.class));
private static final List<String> preferenceKeys = new ArrayList<String>();
private static final List<String> preferenceKeys = new ArrayList<String>();
static {
preferenceKeys.add(groupingSeparator.getKey());
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());
}
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
public static List<String> getPreferenceKeys() {
return Collections.unmodifiableList(preferenceKeys);
}
}
@NotNull
private final Context context;
@NotNull
private final Context context;
@NotNull
private final CalculatorEngine calculatorEngine;
@NotNull
private final CalculatorEngine calculatorEngine;
@NotNull
private final Object lock;
@NotNull
private final Object lock;
public AndroidCalculatorEngine(@NotNull Application application) {
this.context = application;
public AndroidCalculatorEngine(@NotNull Application application) {
this.context = application;
PreferenceManager.getDefaultSharedPreferences(application).registerOnSharedPreferenceChangeListener(this);
PreferenceManager.getDefaultSharedPreferences(application).registerOnSharedPreferenceChangeListener(this);
this.lock = new Object();
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);
}
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<IConstant> getVarsRegistry() {
return calculatorEngine.getVarsRegistry();
}
@Override
@NotNull
public CalculatorMathRegistry<Function> getFunctionsRegistry() {
return calculatorEngine.getFunctionsRegistry();
}
@Override
@NotNull
public CalculatorMathRegistry<Function> getFunctionsRegistry() {
return calculatorEngine.getFunctionsRegistry();
}
@Override
@NotNull
public CalculatorMathRegistry<Operator> getOperatorsRegistry() {
return calculatorEngine.getOperatorsRegistry();
}
@Override
@NotNull
public CalculatorMathRegistry<Operator> getOperatorsRegistry() {
return calculatorEngine.getOperatorsRegistry();
}
@Override
@NotNull
public CalculatorMathRegistry<Operator> getPostfixFunctionsRegistry() {
return calculatorEngine.getPostfixFunctionsRegistry();
}
@Override
@NotNull
public CalculatorMathRegistry<Operator> getPostfixFunctionsRegistry() {
return calculatorEngine.getPostfixFunctionsRegistry();
}
@Override
@NotNull
public CalculatorMathEngine getMathEngine() {
return calculatorEngine.getMathEngine();
}
@Override
@NotNull
public CalculatorMathEngine getMathEngine() {
return calculatorEngine.getMathEngine();
}
@NotNull
@Override
public MathEngine getMathEngine0() {
return calculatorEngine.getMathEngine0();
}
@NotNull
@Override
public MathEngine getMathEngine0() {
return calculatorEngine.getMathEngine0();
}
@NotNull
@Override
public NumeralBase getNumeralBase() {
return calculatorEngine.getNumeralBase();
}
@NotNull
@Override
public NumeralBase getNumeralBase() {
return calculatorEngine.getNumeralBase();
}
@Override
public void init() {
synchronized (lock) {
reset();
}
}
@Override
public void init() {
synchronized (lock) {
reset();
}
}
@Override
public void reset() {
synchronized (lock) {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
@Override
public void reset() {
synchronized (lock) {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
softReset(preferences);
softReset(preferences);
calculatorEngine.reset();
}
}
calculatorEngine.reset();
}
}
@Override
public void softReset() {
synchronized (lock) {
softReset(PreferenceManager.getDefaultSharedPreferences(context));
@Override
public void softReset() {
synchronized (lock) {
softReset(PreferenceManager.getDefaultSharedPreferences(context));
calculatorEngine.softReset();
}
}
calculatorEngine.softReset();
}
}
@Override
public void setUseGroupingSeparator(boolean useGroupingSeparator) {
calculatorEngine.setUseGroupingSeparator(useGroupingSeparator);
}
@Override
public void setUseGroupingSeparator(boolean useGroupingSeparator) {
calculatorEngine.setUseGroupingSeparator(useGroupingSeparator);
}
@Override
public void setGroupingSeparator(char groupingSeparator) {
calculatorEngine.setGroupingSeparator(groupingSeparator);
}
@Override
public void setGroupingSeparator(char groupingSeparator) {
calculatorEngine.setGroupingSeparator(groupingSeparator);
}
@Override
public void setPrecision(@NotNull Integer precision) {
calculatorEngine.setPrecision(precision);
}
@Override
public void setPrecision(@NotNull Integer precision) {
calculatorEngine.setPrecision(precision);
}
@Override
public void setRoundResult(@NotNull Boolean round) {
calculatorEngine.setRoundResult(round);
}
@Override
public void setRoundResult(@NotNull Boolean round) {
calculatorEngine.setRoundResult(round);
}
@NotNull
@Override
public AngleUnit getAngleUnits() {
return calculatorEngine.getAngleUnits();
}
@NotNull
@Override
public AngleUnit getAngleUnits() {
return calculatorEngine.getAngleUnits();
}
@Override
public void setAngleUnits(@NotNull AngleUnit angleUnits) {
calculatorEngine.setAngleUnits(angleUnits);
}
@Override
public void setAngleUnits(@NotNull AngleUnit angleUnits) {
calculatorEngine.setAngleUnits(angleUnits);
}
@Override
public void setNumeralBase(@NotNull NumeralBase numeralBase) {
calculatorEngine.setNumeralBase(numeralBase);
}
@Override
public void setNumeralBase(@NotNull NumeralBase numeralBase) {
calculatorEngine.setNumeralBase(numeralBase);
}
@Override
public void setMultiplicationSign(@NotNull String multiplicationSign) {
calculatorEngine.setMultiplicationSign(multiplicationSign);
}
@Override
public void setMultiplicationSign(@NotNull String multiplicationSign) {
calculatorEngine.setMultiplicationSign(multiplicationSign);
}
@Override
public void setScienceNotation(@NotNull Boolean scienceNotation) {
calculatorEngine.setScienceNotation(scienceNotation);
}
@Override
public void setScienceNotation(@NotNull Boolean scienceNotation) {
calculatorEngine.setScienceNotation(scienceNotation);
}
@Override
public void setTimeout(@NotNull Integer timeout) {
calculatorEngine.setTimeout(timeout);
}
@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));
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 (Strings.isEmpty(groupingSeparator)) {
this.setUseGroupingSeparator(false);
} else {
this.setUseGroupingSeparator(true);
setGroupingSeparator(groupingSeparator.charAt(0));
}
}
final String groupingSeparator = Preferences.groupingSeparator.getPreference(preferences);
if (Strings.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 NumeralBase getNumeralBaseFromPrefs(@NotNull SharedPreferences preferences) {
return Preferences.numeralBase.getPreference(preferences);
}
@NotNull
public AngleUnit getAngleUnitsFromPrefs(@NotNull SharedPreferences preferences) {
return Preferences.angleUnit.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);
}
//for tests only
public void setDecimalGroupSymbols(@NotNull DecimalFormatSymbols decimalGroupSymbols) {
this.calculatorEngine.setDecimalGroupSymbols(decimalGroupSymbols);
}
@Override
@NotNull
public String getMultiplicationSign() {
return calculatorEngine.getMultiplicationSign();
}
@Override
@NotNull
public String getMultiplicationSign() {
return calculatorEngine.getMultiplicationSign();
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if ( Preferences.getPreferenceKeys().contains(key) ) {
this.softReset();
}
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (Preferences.getPreferenceKeys().contains(key)) {
this.softReset();
}
}
}

View File

@@ -23,77 +23,77 @@ import java.io.StringWriter;
*/
public class AndroidMathEntityDao<T extends MathPersistenceEntity> implements MathEntityDao<T> {
@NotNull
private static final String TAG = AndroidMathEntityDao.class.getSimpleName();
@NotNull
private static final String TAG = AndroidMathEntityDao.class.getSimpleName();
@Nullable
private final Integer preferenceStringId;
@Nullable
private final Integer preferenceStringId;
@NotNull
private final Context context;
@NotNull
private final Context context;
@Nullable
private final Class<? extends MathEntityPersistenceContainer<T>> persistenceContainerClass;
@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;
}
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();
@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);
}
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.putString(context.getString(preferenceStringId), sw.toString());
editor.commit();
}
}
editor.commit();
}
}
@Nullable
@Override
public MathEntityPersistenceContainer<T> load() {
if (persistenceContainerClass != null && preferenceStringId != null) {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
@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);
}
}
}
}
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;
}
return null;
}
@Nullable
public String getDescription(@NotNull String descriptionId) {
final Resources resources = context.getResources();
@Nullable
public String getDescription(@NotNull String descriptionId) {
final Resources resources = context.getResources();
final int stringId = resources.getIdentifier(descriptionId, "string", App.getApplication().getClass().getPackage().getName());
try {
return resources.getString(stringId);
} catch (Resources.NotFoundException e) {
return null;
}
}
final int stringId = resources.getIdentifier(descriptionId, "string", App.getApplication().getClass().getPackage().getName());
try {
return resources.getString(stringId);
} catch (Resources.NotFoundException e) {
return null;
}
}
}

View File

@@ -6,7 +6,7 @@ import android.preference.PreferenceManager;
import jscl.math.Generic;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.*;
import org.solovyev.android.calculator.CalculatorPreferences;
import java.util.List;
@@ -17,93 +17,93 @@ import java.util.List;
*/
public class AndroidCalculatorPlotter implements CalculatorPlotter, SharedPreferences.OnSharedPreferenceChangeListener {
@NotNull
private final CalculatorPlotter plotter;
@NotNull
private final CalculatorPlotter plotter;
public AndroidCalculatorPlotter(@NotNull Context context,
@NotNull CalculatorPlotter plotter) {
this.plotter = plotter;
public AndroidCalculatorPlotter(@NotNull Context context,
@NotNull CalculatorPlotter plotter) {
this.plotter = plotter;
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
preferences.registerOnSharedPreferenceChangeListener(this);
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
preferences.registerOnSharedPreferenceChangeListener(this);
onSharedPreferenceChanged(preferences, CalculatorPreferences.Graph.plotImag.getKey());
}
onSharedPreferenceChanged(preferences, CalculatorPreferences.Graph.plotImag.getKey());
}
@Override
@NotNull
public PlotData getPlotData() {
return plotter.getPlotData();
}
@Override
@NotNull
public PlotData getPlotData() {
return plotter.getPlotData();
}
@Override
public boolean addFunction(@NotNull Generic expression) {
return plotter.addFunction(expression);
}
@Override
public boolean addFunction(@NotNull Generic expression) {
return plotter.addFunction(expression);
}
@Override
public boolean addFunction(@NotNull PlotFunction plotFunction) {
return plotter.addFunction(plotFunction);
}
@Override
public boolean addFunction(@NotNull PlotFunction plotFunction) {
return plotter.addFunction(plotFunction);
}
@Override
public boolean addFunction(@NotNull XyFunction xyFunction) {
return plotter.addFunction(xyFunction);
}
@Override
public boolean addFunction(@NotNull XyFunction xyFunction) {
return plotter.addFunction(xyFunction);
}
@Override
public boolean addFunction(@NotNull XyFunction xyFunction, @NotNull PlotLineDef functionLineDef) {
return plotter.addFunction(xyFunction, functionLineDef);
}
@Override
public boolean addFunction(@NotNull XyFunction xyFunction, @NotNull PlotLineDef functionLineDef) {
return plotter.addFunction(xyFunction, functionLineDef);
}
@Override
public boolean updateFunction(@NotNull PlotFunction newFunction) {
return plotter.updateFunction(newFunction);
}
@Override
public boolean updateFunction(@NotNull PlotFunction newFunction) {
return plotter.updateFunction(newFunction);
}
@Override
public boolean updateFunction(@NotNull XyFunction xyFunction, @NotNull PlotLineDef functionLineDef) {
return plotter.updateFunction(xyFunction, functionLineDef);
}
@Override
public boolean updateFunction(@NotNull XyFunction xyFunction, @NotNull PlotLineDef functionLineDef) {
return plotter.updateFunction(xyFunction, functionLineDef);
}
@Override
public boolean removeFunction(@NotNull PlotFunction plotFunction) {
return plotter.removeFunction(plotFunction);
}
@Override
public boolean removeFunction(@NotNull PlotFunction plotFunction) {
return plotter.removeFunction(plotFunction);
}
@Override
public boolean removeFunction(@NotNull XyFunction xyFunction) {
return plotter.removeFunction(xyFunction);
}
@Override
public boolean removeFunction(@NotNull XyFunction xyFunction) {
return plotter.removeFunction(xyFunction);
}
@NotNull
@Override
public PlotFunction pin(@NotNull PlotFunction plotFunction) {
return plotter.pin(plotFunction);
}
@NotNull
@Override
public PlotFunction pin(@NotNull PlotFunction plotFunction) {
return plotter.pin(plotFunction);
}
@NotNull
@Override
public PlotFunction unpin(@NotNull PlotFunction plotFunction) {
return plotter.unpin(plotFunction);
}
@NotNull
@Override
public PlotFunction unpin(@NotNull PlotFunction plotFunction) {
return plotter.unpin(plotFunction);
}
@NotNull
@Override
public PlotFunction show(@NotNull PlotFunction plotFunction) {
return plotter.show(plotFunction);
}
@NotNull
@Override
public PlotFunction show(@NotNull PlotFunction plotFunction) {
return plotter.show(plotFunction);
}
@NotNull
@Override
public PlotFunction hide(@NotNull PlotFunction plotFunction) {
return plotter.hide(plotFunction);
}
@NotNull
@Override
public PlotFunction hide(@NotNull PlotFunction plotFunction) {
return plotter.hide(plotFunction);
}
@Override
public void clearAllFunctions() {
plotter.clearAllFunctions();
}
@Override
public void clearAllFunctions() {
plotter.clearAllFunctions();
}
@Nullable
@Override
@@ -112,66 +112,66 @@ public class AndroidCalculatorPlotter implements CalculatorPlotter, SharedPrefer
}
@Override
@NotNull
public List<PlotFunction> getFunctions() {
return plotter.getFunctions();
}
@NotNull
public List<PlotFunction> getFunctions() {
return plotter.getFunctions();
}
@Override
@NotNull
public List<PlotFunction> getVisibleFunctions() {
return plotter.getVisibleFunctions();
}
@Override
@NotNull
public List<PlotFunction> getVisibleFunctions() {
return plotter.getVisibleFunctions();
}
@Override
public void plot() {
plotter.plot();
}
@Override
public void plot() {
plotter.plot();
}
@Override
public void plot(@NotNull Generic expression) {
plotter.plot(expression);
}
@Override
public void plot(@NotNull Generic expression) {
plotter.plot(expression);
}
@Override
public boolean is2dPlotPossible() {
return plotter.is2dPlotPossible();
}
@Override
public boolean is2dPlotPossible() {
return plotter.is2dPlotPossible();
}
@Override
public boolean isPlotPossibleFor(@NotNull Generic expression) {
return plotter.isPlotPossibleFor(expression);
}
@Override
public boolean isPlotPossibleFor(@NotNull Generic expression) {
return plotter.isPlotPossibleFor(expression);
}
@Override
public void setPlot3d(boolean plot3d) {
plotter.setPlot3d(plot3d);
}
@Override
public void setPlot3d(boolean plot3d) {
plotter.setPlot3d(plot3d);
}
@Override
public void removeAllUnpinned() {
plotter.removeAllUnpinned();
}
@Override
public void removeAllUnpinned() {
plotter.removeAllUnpinned();
}
@Override
public void setPlotImag(boolean plotImag) {
plotter.setPlotImag(plotImag);
}
@Override
public void setPlotImag(boolean plotImag) {
plotter.setPlotImag(plotImag);
}
@Override
public void savePlotBoundaries(@NotNull PlotBoundaries plotBoundaries) {
plotter.savePlotBoundaries(plotBoundaries);
}
@Override
public void savePlotBoundaries(@NotNull PlotBoundaries plotBoundaries) {
plotter.savePlotBoundaries(plotBoundaries);
}
@Override
public void setPlotBoundaries(@NotNull PlotBoundaries plotBoundaries) {
plotter.setPlotBoundaries(plotBoundaries);
}
@Override
public void setPlotBoundaries(@NotNull PlotBoundaries plotBoundaries) {
plotter.setPlotBoundaries(plotBoundaries);
}
@Override
public void onSharedPreferenceChanged(SharedPreferences preferences, String key) {
if (CalculatorPreferences.Graph.plotImag.getKey().equals(key)) {
setPlotImag(CalculatorPreferences.Graph.plotImag.getPreference(preferences));
}
}
@Override
public void onSharedPreferenceChanged(SharedPreferences preferences, String key) {
if (CalculatorPreferences.Graph.plotImag.getKey().equals(key)) {
setPlotImag(CalculatorPreferences.Graph.plotImag.getPreference(preferences));
}
}
}

View File

@@ -12,52 +12,52 @@ import org.jetbrains.annotations.Nullable;
*/
public enum AndroidPlotLineStyle {
solid(PlotLineStyle.solid) {
@Override
public void applyToPaint(@NotNull Paint paint) {
paint.setPathEffect(null);
}
},
solid(PlotLineStyle.solid) {
@Override
public void applyToPaint(@NotNull Paint paint) {
paint.setPathEffect(null);
}
},
dashed(PlotLineStyle.dashed) {
@Override
public void applyToPaint(@NotNull Paint paint) {
paint.setPathEffect(new DashPathEffect(new float[]{10, 20}, 0));
}
},
dashed(PlotLineStyle.dashed) {
@Override
public void applyToPaint(@NotNull Paint paint) {
paint.setPathEffect(new DashPathEffect(new float[]{10, 20}, 0));
}
},
dotted(PlotLineStyle.dotted) {
@Override
public void applyToPaint(@NotNull Paint paint) {
paint.setPathEffect(new DashPathEffect(new float[]{5, 1}, 0));
}
},
dotted(PlotLineStyle.dotted) {
@Override
public void applyToPaint(@NotNull Paint paint) {
paint.setPathEffect(new DashPathEffect(new float[]{5, 1}, 0));
}
},
dash_dotted(PlotLineStyle.dash_dotted) {
@Override
public void applyToPaint(@NotNull Paint paint) {
paint.setPathEffect(new DashPathEffect(new float[]{10, 20, 5, 1}, 0));
}
};
dash_dotted(PlotLineStyle.dash_dotted) {
@Override
public void applyToPaint(@NotNull Paint paint) {
paint.setPathEffect(new DashPathEffect(new float[]{10, 20, 5, 1}, 0));
}
};
@NotNull
private final PlotLineStyle plotLineStyle;
@NotNull
private final PlotLineStyle plotLineStyle;
AndroidPlotLineStyle(@NotNull PlotLineStyle plotLineStyle) {
this.plotLineStyle = plotLineStyle;
}
AndroidPlotLineStyle(@NotNull PlotLineStyle plotLineStyle) {
this.plotLineStyle = plotLineStyle;
}
public abstract void applyToPaint(@NotNull Paint paint);
public abstract void applyToPaint(@NotNull Paint paint);
@Nullable
public static AndroidPlotLineStyle valueOf(@NotNull PlotLineStyle plotLineStyle) {
for (AndroidPlotLineStyle androidPlotLineStyle : values()) {
if ( androidPlotLineStyle.plotLineStyle == plotLineStyle ) {
return androidPlotLineStyle;
}
}
@Nullable
public static AndroidPlotLineStyle valueOf(@NotNull PlotLineStyle plotLineStyle) {
for (AndroidPlotLineStyle androidPlotLineStyle : values()) {
if (androidPlotLineStyle.plotLineStyle == plotLineStyle) {
return androidPlotLineStyle;
}
}
return null;
}
return null;
}
}

View File

@@ -25,74 +25,74 @@ import java.util.Arrays;
*/
public class NumeralBaseConverterDialog {
@Nullable
private String initialFromValue;
@Nullable
private String initialFromValue;
public NumeralBaseConverterDialog(@Nullable String initialFromValue) {
this.initialFromValue = initialFromValue;
}
public NumeralBaseConverterDialog(@Nullable 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()));
public void show(@NotNull Context context) {
final UnitConverterViewBuilder b = new UnitConverterViewBuilder();
b.setFromUnitTypes(Arrays.asList(CalculatorNumeralBase.values()));
b.setToUnitTypes(Arrays.asList(CalculatorNumeralBase.values()));
if (!Strings.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())));
}
if (!Strings.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());
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();
}
}
});
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();
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;
}
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();
}
}
}));
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.Builder alertBuilder = new AlertDialog.Builder(context);
alertBuilder.setView(b.build(context));
alertBuilder.setTitle(R.string.c_conversion_tool);
final AlertDialog alertDialog = alertBuilder.create();
final AlertDialog alertDialog = alertBuilder.create();
final WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(alertDialog.getWindow().getAttributes());
final WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(alertDialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.FILL_PARENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
lp.width = WindowManager.LayoutParams.FILL_PARENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
alertDialogHolder.setObject(alertDialog);
alertDialog.show();
alertDialog.getWindow().setAttributes(lp);
}
alertDialogHolder.setObject(alertDialog);
alertDialog.show();
alertDialog.getWindow().setAttributes(lp);
}
}

View File

@@ -34,10 +34,10 @@ public class TextHighlighter implements TextProcessor<TextHighlighter.Result, St
@NotNull
private final CharSequence charSequence;
@Nullable
private String string;
@Nullable
private String string;
private final int offset;
private final int offset;
public Result(@NotNull CharSequence charSequence, int offset) {
this.charSequence = charSequence;
@@ -61,18 +61,18 @@ public class TextHighlighter implements TextProcessor<TextHighlighter.Result, St
@Override
public String toString() {
if (string == null) {
string = charSequence.toString();
}
return string;
if (string == null) {
string = charSequence.toString();
}
return string;
}
@NotNull
public CharSequence getCharSequence() {
return charSequence;
}
@NotNull
public CharSequence getCharSequence() {
return charSequence;
}
public int getOffset() {
public int getOffset() {
return offset;
}
}
@@ -209,9 +209,9 @@ public class TextHighlighter implements TextProcessor<TextHighlighter.Result, St
for (; i < s.length(); i++) {
char ch = s.charAt(i);
String strCh = String.valueOf(ch);
String strCh = String.valueOf(ch);
if (MathType.open_group_symbol.getTokens().contains(strCh)) {
if (MathType.open_group_symbol.getTokens().contains(strCh)) {
result.append(ch);
result.append("</font>");
i = processBracketGroup(result, s, i + 1, numberOfOpenings + 1, maxNumberOfGroups);

View File

@@ -25,196 +25,195 @@ import java.util.List;
*/
public class UnitConverterViewBuilder implements ViewBuilder<View> {
@NotNull
private List<? extends UnitType<String>> fromUnitTypes = Collections.emptyList();
@NotNull
private List<? extends UnitType<String>> fromUnitTypes = Collections.emptyList();
@NotNull
private List<? extends UnitType<String>> toUnitTypes = Collections.emptyList();
@NotNull
private List<? extends UnitType<String>> toUnitTypes = Collections.emptyList();
@Nullable
private Unit<String> fromValue;
@Nullable
private Unit<String> fromValue;
@NotNull
private UnitConverter<String> converter = UnitConverter.Dummy.getInstance();
@NotNull
private UnitConverter<String> converter = UnitConverter.Dummy.getInstance();
@Nullable
private View.OnClickListener okButtonOnClickListener;
@Nullable
private View.OnClickListener okButtonOnClickListener;
@Nullable
private CustomButtonData customButtonData;
@Nullable
private CustomButtonData customButtonData;
public void setFromUnitTypes(@NotNull List<? extends UnitType<String>> fromUnitTypes) {
this.fromUnitTypes = fromUnitTypes;
}
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 setToUnitTypes(@NotNull List<? extends UnitType<String>> toUnitTypes) {
this.toUnitTypes = toUnitTypes;
}
public void setFromValue(@Nullable Unit<String> fromValue) {
this.fromValue = fromValue;
}
public void setFromValue(@Nullable Unit<String> fromValue) {
this.fromValue = fromValue;
}
public void setConverter(@NotNull UnitConverter<String> converter) {
this.converter = converter;
}
public void setConverter(@NotNull UnitConverter<String> converter) {
this.converter = converter;
}
public void setOkButtonOnClickListener(@Nullable View.OnClickListener okButtonOnClickListener) {
this.okButtonOnClickListener = okButtonOnClickListener;
}
public void setOkButtonOnClickListener(@Nullable View.OnClickListener okButtonOnClickListener) {
this.okButtonOnClickListener = okButtonOnClickListener;
}
public void setCustomButtonData(@Nullable CustomButtonData customButtonData) {
this.customButtonData = customButtonData;
}
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);
@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) {
}
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 onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
doConversion(main, context, UnitConverterViewBuilder.this.converter);
}
});
@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);
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());
if (fromValue != null) {
fromEditText.setText(fromValue.getValue());
int i = fromUnitTypes.indexOf(fromValue.getUnitType());
if ( i >= 0 ) {
fromSpinner.setSelection(i);
}
}
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 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 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 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));
}
});
}
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;
}
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);
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);
}
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);
}
@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);
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 EditText toEditText = (EditText) main.findViewById(R.id.units_to);
final String from = fromEditText.getText().toString();
try {
toEditText.setText(Conversions.doConversion(converter, from, getFromUnitType(main), getToUnitType(main)));
} catch (ConversionException e) {
toEditText.setText(context.getString(R.string.c_error));
}
}
final String from = fromEditText.getText().toString();
try {
toEditText.setText(Conversions.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 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 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 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();
}
@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 {
public static class CustomButtonData {
@NotNull
private String text;
@NotNull
private String text;
@NotNull
private CustomButtonOnClickListener clickListener;
@NotNull
private CustomButtonOnClickListener clickListener;
public CustomButtonData(@NotNull String text, @NotNull CustomButtonOnClickListener clickListener) {
this.text = text;
this.clickListener = 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);
}
public static interface CustomButtonOnClickListener {
void onClick(@NotNull Unit<String> fromUnits, @NotNull Unit<String> toUnits);
}
}