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

@@ -33,223 +33,223 @@ import java.util.List;
*/
public abstract class AbstractCalculatorHelper implements SharedPreferences.OnSharedPreferenceChangeListener {
@NotNull
private CalculatorPreferences.Gui.Layout layout;
@NotNull
private CalculatorPreferences.Gui.Layout layout;
@NotNull
private CalculatorPreferences.Gui.Theme theme;
@NotNull
private CalculatorPreferences.Gui.Theme theme;
@Nullable
private Vibrator vibrator;
@Nullable
private Vibrator vibrator;
@NotNull
private final JListeners<DragPreferencesChangeListener> dpclRegister = Listeners.newHardRefListeners();
@NotNull
private final JListeners<DragPreferencesChangeListener> dpclRegister = Listeners.newHardRefListeners();
@NotNull
private String logTag = "CalculatorActivity";
@NotNull
private String logTag = "CalculatorActivity";
protected AbstractCalculatorHelper() {
}
protected AbstractCalculatorHelper() {
}
protected AbstractCalculatorHelper(@NotNull String logTag) {
this.logTag = logTag;
}
protected AbstractCalculatorHelper(@NotNull String logTag) {
this.logTag = logTag;
}
protected void onCreate(@NotNull Activity activity) {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity);
protected void onCreate(@NotNull Activity activity) {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity);
vibrator = (Vibrator) activity.getSystemService(Activity.VIBRATOR_SERVICE);
layout = CalculatorPreferences.Gui.layout.getPreferenceNoError(preferences);
theme = CalculatorPreferences.Gui.theme.getPreferenceNoError(preferences);
vibrator = (Vibrator) activity.getSystemService(Activity.VIBRATOR_SERVICE);
layout = CalculatorPreferences.Gui.layout.getPreferenceNoError(preferences);
theme = CalculatorPreferences.Gui.theme.getPreferenceNoError(preferences);
preferences.registerOnSharedPreferenceChangeListener(this);
preferences.registerOnSharedPreferenceChangeListener(this);
// let's disable locking of screen for monkeyrunner
if (CalculatorApplication.isMonkeyRunner(activity)) {
final KeyguardManager km = (KeyguardManager) activity.getSystemService(Context.KEYGUARD_SERVICE);
km.newKeyguardLock(activity.getClass().getName()).disableKeyguard();
}
}
// let's disable locking of screen for monkeyrunner
if (CalculatorApplication.isMonkeyRunner(activity)) {
final KeyguardManager km = (KeyguardManager) activity.getSystemService(Context.KEYGUARD_SERVICE);
km.newKeyguardLock(activity.getClass().getName()).disableKeyguard();
}
}
public void logDebug(@NotNull String message) {
Log.d(logTag, message);
}
public void logDebug(@NotNull String message) {
Log.d(logTag, message);
}
public void logError(@NotNull String message) {
Log.e(logTag, message);
}
public void logError(@NotNull String message) {
Log.e(logTag, message);
}
public void processButtons(@NotNull final Activity activity, @NotNull View root) {
dpclRegister.removeListeners();
public void processButtons(@NotNull final Activity activity, @NotNull View root) {
dpclRegister.removeListeners();
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity);
final SimpleOnDragListener.Preferences dragPreferences = SimpleOnDragListener.getPreferences(preferences, activity);
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity);
final SimpleOnDragListener.Preferences dragPreferences = SimpleOnDragListener.getPreferences(preferences, activity);
setOnDragListeners(root, dragPreferences, preferences);
setOnDragListeners(root, dragPreferences, preferences);
final OnDragListener historyOnDragListener = new OnDragListenerVibrator(newOnDragListener(new HistoryDragProcessor<CalculatorHistoryState>(getCalculator()), dragPreferences), vibrator, preferences);
final DragButton historyButton = getButton(root, R.id.cpp_button_history);
if (historyButton != null) {
historyButton.setOnDragListener(historyOnDragListener);
}
final OnDragListener historyOnDragListener = new OnDragListenerVibrator(newOnDragListener(new HistoryDragProcessor<CalculatorHistoryState>(getCalculator()), dragPreferences), vibrator, preferences);
final DragButton historyButton = getButton(root, R.id.cpp_button_history);
if (historyButton != null) {
historyButton.setOnDragListener(historyOnDragListener);
}
final DragButton subtractionButton = getButton(root, R.id.cpp_button_subtraction);
if (subtractionButton != null) {
subtractionButton.setOnDragListener(new OnDragListenerVibrator(newOnDragListener(new SimpleOnDragListener.DragProcessor() {
@Override
public boolean processDragEvent(@NotNull DragDirection dragDirection, @NotNull DragButton dragButton, @NotNull Point2d startPoint2d, @NotNull MotionEvent motionEvent) {
if (dragDirection == DragDirection.down) {
Locator.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.show_operators, null);
return true;
}
return false;
}
}, dragPreferences), vibrator, preferences));
}
final DragButton subtractionButton = getButton(root, R.id.cpp_button_subtraction);
if (subtractionButton != null) {
subtractionButton.setOnDragListener(new OnDragListenerVibrator(newOnDragListener(new SimpleOnDragListener.DragProcessor() {
@Override
public boolean processDragEvent(@NotNull DragDirection dragDirection, @NotNull DragButton dragButton, @NotNull Point2d startPoint2d, @NotNull MotionEvent motionEvent) {
if (dragDirection == DragDirection.down) {
Locator.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.show_operators, null);
return true;
}
return false;
}
}, dragPreferences), vibrator, preferences));
}
final OnDragListener toPositionOnDragListener = new OnDragListenerVibrator(new SimpleOnDragListener(new CursorDragProcessor(), dragPreferences), vibrator, preferences);
final OnDragListener toPositionOnDragListener = new OnDragListenerVibrator(new SimpleOnDragListener(new CursorDragProcessor(), dragPreferences), vibrator, preferences);
final DragButton rightButton = getButton(root, R.id.cpp_button_right);
if (rightButton != null) {
rightButton.setOnDragListener(toPositionOnDragListener);
}
final DragButton rightButton = getButton(root, R.id.cpp_button_right);
if (rightButton != null) {
rightButton.setOnDragListener(toPositionOnDragListener);
}
final DragButton leftButton = getButton(root, R.id.cpp_button_left);
if (leftButton != null) {
leftButton.setOnDragListener(toPositionOnDragListener);
}
final DragButton leftButton = getButton(root, R.id.cpp_button_left);
if (leftButton != null) {
leftButton.setOnDragListener(toPositionOnDragListener);
}
final DragButton equalsButton = getButton(root, R.id.cpp_button_equals);
if (equalsButton != null) {
equalsButton.setOnDragListener(new OnDragListenerVibrator(newOnDragListener(new EqualsDragProcessor(), dragPreferences), vibrator, preferences));
}
final DragButton equalsButton = getButton(root, R.id.cpp_button_equals);
if (equalsButton != null) {
equalsButton.setOnDragListener(new OnDragListenerVibrator(newOnDragListener(new EqualsDragProcessor(), dragPreferences), vibrator, preferences));
}
final AngleUnitsButton angleUnitsButton = (AngleUnitsButton) getButton(root, R.id.cpp_button_6);
if (angleUnitsButton != null) {
angleUnitsButton.setOnDragListener(new OnDragListenerVibrator(newOnDragListener(new CalculatorButtons.AngleUnitsChanger(activity), dragPreferences), vibrator, preferences));
}
final AngleUnitsButton angleUnitsButton = (AngleUnitsButton) getButton(root, R.id.cpp_button_6);
if (angleUnitsButton != null) {
angleUnitsButton.setOnDragListener(new OnDragListenerVibrator(newOnDragListener(new CalculatorButtons.AngleUnitsChanger(activity), dragPreferences), vibrator, preferences));
}
final NumeralBasesButton clearButton = (NumeralBasesButton) getButton(root, R.id.cpp_button_clear);
if (clearButton != null) {
clearButton.setOnDragListener(new OnDragListenerVibrator(newOnDragListener(new CalculatorButtons.NumeralBasesChanger(activity), dragPreferences), vibrator, preferences));
}
final NumeralBasesButton clearButton = (NumeralBasesButton) getButton(root, R.id.cpp_button_clear);
if (clearButton != null) {
clearButton.setOnDragListener(new OnDragListenerVibrator(newOnDragListener(new CalculatorButtons.NumeralBasesChanger(activity), dragPreferences), vibrator, preferences));
}
final DragButton varsButton = getButton(root, R.id.cpp_button_vars);
if (varsButton != null) {
varsButton.setOnDragListener(new OnDragListenerVibrator(newOnDragListener(new CalculatorButtons.VarsDragProcessor(activity), dragPreferences), vibrator, preferences));
}
final DragButton varsButton = getButton(root, R.id.cpp_button_vars);
if (varsButton != null) {
varsButton.setOnDragListener(new OnDragListenerVibrator(newOnDragListener(new CalculatorButtons.VarsDragProcessor(activity), dragPreferences), vibrator, preferences));
}
final DragButton functionsButton = getButton(root, R.id.cpp_button_functions);
if (functionsButton != null) {
functionsButton.setOnDragListener(new OnDragListenerVibrator(newOnDragListener(new CalculatorButtons.FunctionsDragProcessor(activity), dragPreferences), vibrator, preferences));
}
final DragButton functionsButton = getButton(root, R.id.cpp_button_functions);
if (functionsButton != null) {
functionsButton.setOnDragListener(new OnDragListenerVibrator(newOnDragListener(new CalculatorButtons.FunctionsDragProcessor(activity), dragPreferences), vibrator, preferences));
}
final DragButton roundBracketsButton = getButton(root, R.id.cpp_button_round_brackets);
if (roundBracketsButton != null) {
roundBracketsButton.setOnDragListener(new OnDragListenerVibrator(newOnDragListener(new CalculatorButtons.RoundBracketsDragProcessor(), dragPreferences), vibrator, preferences));
}
final DragButton roundBracketsButton = getButton(root, R.id.cpp_button_round_brackets);
if (roundBracketsButton != null) {
roundBracketsButton.setOnDragListener(new OnDragListenerVibrator(newOnDragListener(new CalculatorButtons.RoundBracketsDragProcessor(), dragPreferences), vibrator, preferences));
}
if (layout == CalculatorPreferences.Gui.Layout.simple) {
toggleButtonDirectionText(root, R.id.cpp_button_1, false, DragDirection.up, DragDirection.down);
toggleButtonDirectionText(root, R.id.cpp_button_2, false, DragDirection.up, DragDirection.down);
toggleButtonDirectionText(root, R.id.cpp_button_3, false, DragDirection.up, DragDirection.down);
if (layout == CalculatorPreferences.Gui.Layout.simple) {
toggleButtonDirectionText(root, R.id.cpp_button_1, false, DragDirection.up, DragDirection.down);
toggleButtonDirectionText(root, R.id.cpp_button_2, false, DragDirection.up, DragDirection.down);
toggleButtonDirectionText(root, R.id.cpp_button_3, false, DragDirection.up, DragDirection.down);
toggleButtonDirectionText(root, R.id.cpp_button_6, false, DragDirection.up, DragDirection.down);
toggleButtonDirectionText(root, R.id.cpp_button_7, false, DragDirection.left, DragDirection.up, DragDirection.down);
toggleButtonDirectionText(root, R.id.cpp_button_8, false, DragDirection.left, DragDirection.up, DragDirection.down);
toggleButtonDirectionText(root, R.id.cpp_button_6, false, DragDirection.up, DragDirection.down);
toggleButtonDirectionText(root, R.id.cpp_button_7, false, DragDirection.left, DragDirection.up, DragDirection.down);
toggleButtonDirectionText(root, R.id.cpp_button_8, false, DragDirection.left, DragDirection.up, DragDirection.down);
toggleButtonDirectionText(root, R.id.cpp_button_clear, false, DragDirection.left, DragDirection.up, DragDirection.down);
toggleButtonDirectionText(root, R.id.cpp_button_clear, false, DragDirection.left, DragDirection.up, DragDirection.down);
toggleButtonDirectionText(root, R.id.cpp_button_4, false, DragDirection.down);
toggleButtonDirectionText(root, R.id.cpp_button_5, false, DragDirection.down);
toggleButtonDirectionText(root, R.id.cpp_button_4, false, DragDirection.down);
toggleButtonDirectionText(root, R.id.cpp_button_5, false, DragDirection.down);
toggleButtonDirectionText(root, R.id.cpp_button_9, false, DragDirection.left);
toggleButtonDirectionText(root, R.id.cpp_button_9, false, DragDirection.left);
toggleButtonDirectionText(root, R.id.cpp_button_multiplication, false, DragDirection.left);
toggleButtonDirectionText(root, R.id.cpp_button_plus, false, DragDirection.down, DragDirection.up);
}
toggleButtonDirectionText(root, R.id.cpp_button_multiplication, false, DragDirection.left);
toggleButtonDirectionText(root, R.id.cpp_button_plus, false, DragDirection.down, DragDirection.up);
}
CalculatorButtons.processButtons(theme, layout, root);
CalculatorButtons.toggleEqualsButton(preferences, activity);
CalculatorButtons.initMultiplicationButton(root);
NumeralBaseButtons.toggleNumericDigits(activity, preferences);
}
CalculatorButtons.processButtons(theme, layout, root);
CalculatorButtons.toggleEqualsButton(preferences, activity);
CalculatorButtons.initMultiplicationButton(root);
NumeralBaseButtons.toggleNumericDigits(activity, preferences);
}
private void toggleButtonDirectionText(@NotNull View root, int id, boolean showDirectionText, @NotNull DragDirection... dragDirections) {
final View v = getButton(root, id);
if (v instanceof DirectionDragButton ) {
final DirectionDragButton button = (DirectionDragButton)v;
for (DragDirection dragDirection : dragDirections) {
button.showDirectionText(showDirectionText, dragDirection);
}
}
}
private void toggleButtonDirectionText(@NotNull View root, int id, boolean showDirectionText, @NotNull DragDirection... dragDirections) {
final View v = getButton(root, id);
if (v instanceof DirectionDragButton) {
final DirectionDragButton button = (DirectionDragButton) v;
for (DragDirection dragDirection : dragDirections) {
button.showDirectionText(showDirectionText, dragDirection);
}
}
}
@NotNull
private Calculator getCalculator() {
return Locator.getInstance().getCalculator();
}
@NotNull
private Calculator getCalculator() {
return Locator.getInstance().getCalculator();
}
private void setOnDragListeners(@NotNull View root, @NotNull SimpleOnDragListener.Preferences dragPreferences, @NotNull SharedPreferences preferences) {
final OnDragListener onDragListener = new OnDragListenerVibrator(newOnDragListener(new DigitButtonDragProcessor(getKeyboard()), dragPreferences), vibrator, preferences);
private void setOnDragListeners(@NotNull View root, @NotNull SimpleOnDragListener.Preferences dragPreferences, @NotNull SharedPreferences preferences) {
final OnDragListener onDragListener = new OnDragListenerVibrator(newOnDragListener(new DigitButtonDragProcessor(getKeyboard()), dragPreferences), vibrator, preferences);
final List<Integer> dragButtonIds = new ArrayList<Integer>();
final List<Integer> dragButtonIds = new ArrayList<Integer>();
for (Field field : R.id.class.getDeclaredFields()) {
int modifiers = field.getModifiers();
if (Modifier.isFinal(modifiers) && Modifier.isStatic(modifiers)) {
try {
int viewId = field.getInt(R.id.class);
final View view = root.findViewById(viewId);
if (view instanceof DragButton) {
dragButtonIds.add(viewId);
}
} catch (IllegalAccessException e) {
Log.e(R.id.class.getName(), e.getMessage());
}
}
}
for (Field field : R.id.class.getDeclaredFields()) {
int modifiers = field.getModifiers();
if (Modifier.isFinal(modifiers) && Modifier.isStatic(modifiers)) {
try {
int viewId = field.getInt(R.id.class);
final View view = root.findViewById(viewId);
if (view instanceof DragButton) {
dragButtonIds.add(viewId);
}
} catch (IllegalAccessException e) {
Log.e(R.id.class.getName(), e.getMessage());
}
}
}
for (Integer dragButtonId : dragButtonIds) {
final DragButton button = getButton(root, dragButtonId);
if (button != null) {
button.setOnDragListener(onDragListener);
}
}
}
for (Integer dragButtonId : dragButtonIds) {
final DragButton button = getButton(root, dragButtonId);
if (button != null) {
button.setOnDragListener(onDragListener);
}
}
}
@NotNull
private CalculatorKeyboard getKeyboard() {
return Locator.getInstance().getKeyboard();
}
@NotNull
private CalculatorKeyboard getKeyboard() {
return Locator.getInstance().getKeyboard();
}
@Nullable
private <T extends DragButton> T getButton(@NotNull View root, int buttonId) {
return (T) root.findViewById(buttonId);
}
@Nullable
private <T extends DragButton> T getButton(@NotNull View root, int buttonId) {
return (T) root.findViewById(buttonId);
}
@NotNull
private SimpleOnDragListener newOnDragListener(@NotNull SimpleOnDragListener.DragProcessor dragProcessor,
@NotNull SimpleOnDragListener.Preferences dragPreferences) {
final SimpleOnDragListener onDragListener = new SimpleOnDragListener(dragProcessor, dragPreferences);
dpclRegister.addListener(onDragListener);
return onDragListener;
}
@NotNull
private SimpleOnDragListener newOnDragListener(@NotNull SimpleOnDragListener.DragProcessor dragProcessor,
@NotNull SimpleOnDragListener.Preferences dragPreferences) {
final SimpleOnDragListener onDragListener = new SimpleOnDragListener(dragProcessor, dragPreferences);
dpclRegister.addListener(onDragListener);
return onDragListener;
}
@Override
public void onSharedPreferenceChanged(SharedPreferences preferences, String key) {
if (key != null && key.startsWith("org.solovyev.android.calculator.DragButtonCalibrationActivity")) {
final SimpleOnDragListener.Preferences dragPreferences = SimpleOnDragListener.getPreferences(preferences, CalculatorApplication.getInstance());
for (DragPreferencesChangeListener dragPreferencesChangeListener : dpclRegister.getListeners()) {
dragPreferencesChangeListener.onDragPreferencesChange(dragPreferences);
}
}
}
@Override
public void onSharedPreferenceChanged(SharedPreferences preferences, String key) {
if (key != null && key.startsWith("org.solovyev.android.calculator.DragButtonCalibrationActivity")) {
final SimpleOnDragListener.Preferences dragPreferences = SimpleOnDragListener.getPreferences(preferences, CalculatorApplication.getInstance());
for (DragPreferencesChangeListener dragPreferencesChangeListener : dpclRegister.getListeners()) {
dragPreferencesChangeListener.onDragPreferencesChange(dragPreferences);
}
}
}
public void onDestroy(@NotNull Activity activity) {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity);
public void onDestroy(@NotNull Activity activity) {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity);
preferences.unregisterOnSharedPreferenceChangeListener(this);
}
preferences.unregisterOnSharedPreferenceChangeListener(this);
}
}

View File

@@ -23,93 +23,93 @@ import java.util.List;
*/
public class AndroidCalculator implements Calculator, CalculatorEventListener, SharedPreferences.OnSharedPreferenceChangeListener {
@NotNull
private final CalculatorImpl calculator = new CalculatorImpl();
@NotNull
private final CalculatorImpl calculator = new CalculatorImpl();
@NotNull
private final Application context;
@NotNull
private final Application context;
public AndroidCalculator(@NotNull Application application) {
this.context = application;
this.calculator.addCalculatorEventListener(this);
public AndroidCalculator(@NotNull Application application) {
this.context = application;
this.calculator.addCalculatorEventListener(this);
PreferenceManager.getDefaultSharedPreferences(application).registerOnSharedPreferenceChangeListener(this);
}
PreferenceManager.getDefaultSharedPreferences(application).registerOnSharedPreferenceChangeListener(this);
}
public void init(@NotNull final Activity activity) {
setEditor(activity);
setDisplay(activity);
}
public void init(@NotNull final Activity activity) {
setEditor(activity);
setDisplay(activity);
}
public void setDisplay(@NotNull Activity activity) {
final AndroidCalculatorDisplayView displayView = (AndroidCalculatorDisplayView) activity.findViewById(R.id.calculator_display);
setDisplay(activity, displayView);
}
public void setDisplay(@NotNull Activity activity) {
final AndroidCalculatorDisplayView displayView = (AndroidCalculatorDisplayView) activity.findViewById(R.id.calculator_display);
setDisplay(activity, displayView);
}
public void setDisplay(@NotNull Context context, @NotNull AndroidCalculatorDisplayView displayView) {
displayView.init(context);
Locator.getInstance().getDisplay().setView(displayView);
}
public void setDisplay(@NotNull Context context, @NotNull AndroidCalculatorDisplayView displayView) {
displayView.init(context);
Locator.getInstance().getDisplay().setView(displayView);
}
public void setEditor(@NotNull Activity activity) {
final AndroidCalculatorEditorView editorView = (AndroidCalculatorEditorView) activity.findViewById(R.id.calculator_editor);
setEditor(activity, editorView);
}
public void setEditor(@NotNull Activity activity) {
final AndroidCalculatorEditorView editorView = (AndroidCalculatorEditorView) activity.findViewById(R.id.calculator_editor);
setEditor(activity, editorView);
}
public void setEditor(@NotNull Context context, @NotNull AndroidCalculatorEditorView editorView) {
editorView.init(context);
Locator.getInstance().getEditor().setView(editorView);
}
public void setEditor(@NotNull Context context, @NotNull AndroidCalculatorEditorView editorView) {
editorView.init(context);
Locator.getInstance().getEditor().setView(editorView);
}
/*
**********************************************************************
*
* DELEGATED TO CALCULATOR
*
**********************************************************************
*/
/*
**********************************************************************
*
* DELEGATED TO CALCULATOR
*
**********************************************************************
*/
@Override
@NotNull
public CalculatorEventData evaluate(@NotNull JsclOperation operation, @NotNull String expression) {
return calculator.evaluate(operation, expression);
}
@Override
@NotNull
public CalculatorEventData evaluate(@NotNull JsclOperation operation, @NotNull String expression) {
return calculator.evaluate(operation, expression);
}
@Override
@NotNull
public CalculatorEventData evaluate(@NotNull JsclOperation operation, @NotNull String expression, @NotNull Long sequenceId) {
return calculator.evaluate(operation, expression, sequenceId);
}
@Override
@NotNull
public CalculatorEventData evaluate(@NotNull JsclOperation operation, @NotNull String expression, @NotNull Long sequenceId) {
return calculator.evaluate(operation, expression, sequenceId);
}
@Override
public boolean isConversionPossible(@NotNull Generic generic, @NotNull NumeralBase from, @NotNull NumeralBase to) {
return calculator.isConversionPossible(generic, from, to);
}
@Override
public boolean isConversionPossible(@NotNull Generic generic, @NotNull NumeralBase from, @NotNull NumeralBase to) {
return calculator.isConversionPossible(generic, from, to);
}
@Override
@NotNull
public CalculatorEventData convert(@NotNull Generic generic, @NotNull NumeralBase to) {
return calculator.convert(generic, to);
}
@Override
@NotNull
public CalculatorEventData convert(@NotNull Generic generic, @NotNull NumeralBase to) {
return calculator.convert(generic, to);
}
@Override
@NotNull
public CalculatorEventData fireCalculatorEvent(@NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
return calculator.fireCalculatorEvent(calculatorEventType, data);
}
@Override
@NotNull
public CalculatorEventData fireCalculatorEvent(@NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
return calculator.fireCalculatorEvent(calculatorEventType, data);
}
@NotNull
@Override
public CalculatorEventData fireCalculatorEvent(@NotNull CalculatorEventType calculatorEventType, @Nullable Object data, @NotNull Object source) {
return calculator.fireCalculatorEvent(calculatorEventType, data, source);
}
@NotNull
@Override
public CalculatorEventData fireCalculatorEvent(@NotNull CalculatorEventType calculatorEventType, @Nullable Object data, @NotNull Object source) {
return calculator.fireCalculatorEvent(calculatorEventType, data, source);
}
@Override
@NotNull
public CalculatorEventData fireCalculatorEvent(@NotNull CalculatorEventType calculatorEventType, @Nullable Object data, @NotNull Long sequenceId) {
return calculator.fireCalculatorEvent(calculatorEventType, data, sequenceId);
}
@Override
@NotNull
public CalculatorEventData fireCalculatorEvent(@NotNull CalculatorEventType calculatorEventType, @Nullable Object data, @NotNull Long sequenceId) {
return calculator.fireCalculatorEvent(calculatorEventType, data, sequenceId);
}
@NotNull
@Override
@@ -118,113 +118,113 @@ public class AndroidCalculator implements Calculator, CalculatorEventListener, S
}
@Override
public void init() {
this.calculator.init();
public void init() {
this.calculator.init();
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
this.calculator.setCalculateOnFly(CalculatorPreferences.Calculations.calculateOnFly.getPreference(prefs));
}
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
this.calculator.setCalculateOnFly(CalculatorPreferences.Calculations.calculateOnFly.getPreference(prefs));
}
@Override
public void addCalculatorEventListener(@NotNull CalculatorEventListener calculatorEventListener) {
calculator.addCalculatorEventListener(calculatorEventListener);
}
@Override
public void addCalculatorEventListener(@NotNull CalculatorEventListener calculatorEventListener) {
calculator.addCalculatorEventListener(calculatorEventListener);
}
@Override
public void removeCalculatorEventListener(@NotNull CalculatorEventListener calculatorEventListener) {
calculator.removeCalculatorEventListener(calculatorEventListener);
}
@Override
public void removeCalculatorEventListener(@NotNull CalculatorEventListener calculatorEventListener) {
calculator.removeCalculatorEventListener(calculatorEventListener);
}
@Override
public void fireCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
calculator.fireCalculatorEvent(calculatorEventData, calculatorEventType, data);
}
@Override
public void fireCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
calculator.fireCalculatorEvent(calculatorEventData, calculatorEventType, data);
}
@Override
public void fireCalculatorEvents(@NotNull List<CalculatorEvent> calculatorEvents) {
calculator.fireCalculatorEvents(calculatorEvents);
}
@Override
public void fireCalculatorEvents(@NotNull List<CalculatorEvent> calculatorEvents) {
calculator.fireCalculatorEvents(calculatorEvents);
}
@Override
public void doHistoryAction(@NotNull HistoryAction historyAction) {
calculator.doHistoryAction(historyAction);
}
@Override
public void doHistoryAction(@NotNull HistoryAction historyAction) {
calculator.doHistoryAction(historyAction);
}
@Override
public void setCurrentHistoryState(@NotNull CalculatorHistoryState editorHistoryState) {
calculator.setCurrentHistoryState(editorHistoryState);
}
@Override
public void setCurrentHistoryState(@NotNull CalculatorHistoryState editorHistoryState) {
calculator.setCurrentHistoryState(editorHistoryState);
}
@Override
@NotNull
public CalculatorHistoryState getCurrentHistoryState() {
return calculator.getCurrentHistoryState();
}
@Override
@NotNull
public CalculatorHistoryState getCurrentHistoryState() {
return calculator.getCurrentHistoryState();
}
@Override
public void evaluate() {
calculator.evaluate();
}
@Override
public void evaluate() {
calculator.evaluate();
}
@Override
public void evaluate(@NotNull Long sequenceId) {
calculator.evaluate(sequenceId);
}
@Override
public void evaluate(@NotNull Long sequenceId) {
calculator.evaluate(sequenceId);
}
@Override
public void simplify() {
calculator.simplify();
}
@Override
public void simplify() {
calculator.simplify();
}
@Override
public void onCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
switch (calculatorEventType) {
case calculation_messages:
CalculatorActivityLauncher.showCalculationMessagesDialog(CalculatorApplication.getInstance(), (List<Message>) data);
break;
case show_history:
CalculatorActivityLauncher.showHistory(CalculatorApplication.getInstance());
break;
case show_history_detached:
CalculatorActivityLauncher.showHistory(CalculatorApplication.getInstance(), true);
break;
case show_functions:
CalculatorActivityLauncher.showFunctions(CalculatorApplication.getInstance());
break;
case show_functions_detached:
CalculatorActivityLauncher.showFunctions(CalculatorApplication.getInstance(), true);
break;
case show_operators:
CalculatorActivityLauncher.showOperators(CalculatorApplication.getInstance());
break;
case show_operators_detached:
CalculatorActivityLauncher.showOperators(CalculatorApplication.getInstance(), true);
break;
case show_vars:
CalculatorActivityLauncher.showVars(CalculatorApplication.getInstance());
break;
case show_vars_detached:
CalculatorActivityLauncher.showVars(CalculatorApplication.getInstance(), true);
break;
case show_settings:
CalculatorActivityLauncher.showSettings(CalculatorApplication.getInstance());
break;
case show_settings_detached:
CalculatorActivityLauncher.showSettings(CalculatorApplication.getInstance(), true);
break;
case show_like_dialog:
CalculatorActivityLauncher.likeButtonPressed(CalculatorApplication.getInstance());
break;
case open_app:
CalculatorActivityLauncher.openApp(CalculatorApplication.getInstance());
break;
}
}
@Override
public void onCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
switch (calculatorEventType) {
case calculation_messages:
CalculatorActivityLauncher.showCalculationMessagesDialog(CalculatorApplication.getInstance(), (List<Message>) data);
break;
case show_history:
CalculatorActivityLauncher.showHistory(CalculatorApplication.getInstance());
break;
case show_history_detached:
CalculatorActivityLauncher.showHistory(CalculatorApplication.getInstance(), true);
break;
case show_functions:
CalculatorActivityLauncher.showFunctions(CalculatorApplication.getInstance());
break;
case show_functions_detached:
CalculatorActivityLauncher.showFunctions(CalculatorApplication.getInstance(), true);
break;
case show_operators:
CalculatorActivityLauncher.showOperators(CalculatorApplication.getInstance());
break;
case show_operators_detached:
CalculatorActivityLauncher.showOperators(CalculatorApplication.getInstance(), true);
break;
case show_vars:
CalculatorActivityLauncher.showVars(CalculatorApplication.getInstance());
break;
case show_vars_detached:
CalculatorActivityLauncher.showVars(CalculatorApplication.getInstance(), true);
break;
case show_settings:
CalculatorActivityLauncher.showSettings(CalculatorApplication.getInstance());
break;
case show_settings_detached:
CalculatorActivityLauncher.showSettings(CalculatorApplication.getInstance(), true);
break;
case show_like_dialog:
CalculatorActivityLauncher.likeButtonPressed(CalculatorApplication.getInstance());
break;
case open_app:
CalculatorActivityLauncher.openApp(CalculatorApplication.getInstance());
break;
}
}
@Override
public void onSharedPreferenceChanged(@NotNull SharedPreferences prefs, @NotNull String key) {
if ( CalculatorPreferences.Calculations.calculateOnFly.getKey().equals(key) ) {
this.calculator.setCalculateOnFly(CalculatorPreferences.Calculations.calculateOnFly.getPreference(prefs));
}
}
@Override
public void onSharedPreferenceChanged(@NotNull SharedPreferences prefs, @NotNull String key) {
if (CalculatorPreferences.Calculations.calculateOnFly.getKey().equals(key)) {
this.calculator.setCalculateOnFly(CalculatorPreferences.Calculations.calculateOnFly.getPreference(prefs));
}
}
}

View File

@@ -12,32 +12,32 @@ import org.jetbrains.annotations.NotNull;
*/
public class AndroidCalculatorClipboard implements CalculatorClipboard {
@NotNull
private final Context context;
@NotNull
private final Context context;
public AndroidCalculatorClipboard(@NotNull Application application) {
this.context = application;
}
public AndroidCalculatorClipboard(@NotNull Application application) {
this.context = application;
}
@Override
public String getText() {
final ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
if ( clipboard.hasText() ) {
return String.valueOf(clipboard.getText());
} else {
return null;
}
}
@Override
public String getText() {
final ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
if (clipboard.hasText()) {
return String.valueOf(clipboard.getText());
} else {
return null;
}
}
@Override
public void setText(@NotNull String text) {
final ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setText(text);
}
@Override
public void setText(@NotNull String text) {
final ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setText(text);
}
@Override
public void setText(@NotNull CharSequence text) {
final ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setText(text);
}
@Override
public void setText(@NotNull CharSequence text) {
final ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setText(text);
}
}

View File

@@ -17,70 +17,70 @@ import org.solovyev.android.view.VibratorContainer;
*/
public class AndroidCalculatorKeyboard implements CalculatorKeyboard {
@NotNull
private final CalculatorKeyboard calculatorKeyboard;
@NotNull
private final CalculatorKeyboard calculatorKeyboard;
@NotNull
private final Context context;
@NotNull
private final Context context;
private VibratorContainer vibrator;
private VibratorContainer vibrator;
public AndroidCalculatorKeyboard(@NotNull Application application,
@NotNull CalculatorKeyboard calculatorKeyboard) {
this.context = application;
this.calculatorKeyboard = calculatorKeyboard;
}
public AndroidCalculatorKeyboard(@NotNull Application application,
@NotNull CalculatorKeyboard calculatorKeyboard) {
this.context = application;
this.calculatorKeyboard = calculatorKeyboard;
}
@Override
public void buttonPressed(@Nullable String text) {
vibrate();
calculatorKeyboard.buttonPressed(text);
}
@Override
public void buttonPressed(@Nullable String text) {
vibrate();
calculatorKeyboard.buttonPressed(text);
}
private void vibrate() {
if (this.vibrator == null) {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
final Vibrator vibrator = (Vibrator) context.getSystemService(Activity.VIBRATOR_SERVICE);
private void vibrate() {
if (this.vibrator == null) {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
final Vibrator vibrator = (Vibrator) context.getSystemService(Activity.VIBRATOR_SERVICE);
this.vibrator = new VibratorContainer(vibrator, preferences, 0.5f);
}
this.vibrator = new VibratorContainer(vibrator, preferences, 0.5f);
}
this.vibrator.vibrate();
}
this.vibrator.vibrate();
}
@Override
public void roundBracketsButtonPressed() {
vibrate();
calculatorKeyboard.roundBracketsButtonPressed();
}
@Override
public void roundBracketsButtonPressed() {
vibrate();
calculatorKeyboard.roundBracketsButtonPressed();
}
@Override
public void pasteButtonPressed() {
vibrate();
calculatorKeyboard.pasteButtonPressed();
}
@Override
public void pasteButtonPressed() {
vibrate();
calculatorKeyboard.pasteButtonPressed();
}
@Override
public void clearButtonPressed() {
vibrate();
calculatorKeyboard.clearButtonPressed();
}
@Override
public void clearButtonPressed() {
vibrate();
calculatorKeyboard.clearButtonPressed();
}
@Override
public void copyButtonPressed() {
vibrate();
calculatorKeyboard.copyButtonPressed();
}
@Override
public void copyButtonPressed() {
vibrate();
calculatorKeyboard.copyButtonPressed();
}
@Override
public void moveCursorLeft() {
vibrate();
calculatorKeyboard.moveCursorLeft();
}
@Override
public void moveCursorLeft() {
vibrate();
calculatorKeyboard.moveCursorLeft();
}
@Override
public void moveCursorRight() {
vibrate();
calculatorKeyboard.moveCursorRight();
}
@Override
public void moveCursorRight() {
vibrate();
calculatorKeyboard.moveCursorRight();
}
}

View File

@@ -11,31 +11,31 @@ import org.jetbrains.annotations.Nullable;
*/
public class AndroidCalculatorLogger implements CalculatorLogger {
@NotNull
private static final String TAG = "Calculatorpp";
@NotNull
private static final String TAG = "Calculatorpp";
@Override
public void debug(@Nullable String tag, @NotNull String message) {
Log.d(getTag(tag), message);
}
@Override
public void debug(@Nullable String tag, @NotNull String message) {
Log.d(getTag(tag), message);
}
@NotNull
private String getTag(@Nullable String tag) {
return tag != null ? TAG + "/" + tag : TAG;
}
@NotNull
private String getTag(@Nullable String tag) {
return tag != null ? TAG + "/" + tag : TAG;
}
@Override
public void debug(@Nullable String tag, @Nullable String message, @NotNull Throwable e) {
Log.d(getTag(tag), message, e);
}
@Override
public void debug(@Nullable String tag, @Nullable String message, @NotNull Throwable e) {
Log.d(getTag(tag), message, e);
}
@Override
public void error(@Nullable String tag, @Nullable String message, @NotNull Throwable e) {
Log.e(getTag(tag), message, e);
}
@Override
public void error(@Nullable String tag, @Nullable String message, @NotNull Throwable e) {
Log.e(getTag(tag), message, e);
}
@Override
public void error(@Nullable String tag, @Nullable String message) {
Log.e(getTag(tag), message);
}
@Override
public void error(@Nullable String tag, @Nullable String message) {
Log.e(getTag(tag), message);
}
}

View File

@@ -19,58 +19,58 @@ import java.util.List;
*/
public class AndroidCalculatorNotifier implements CalculatorNotifier {
@NotNull
private final Application application;
@NotNull
private final Application application;
@NotNull
private final Handler uiHandler = new Handler();
@NotNull
private final Handler uiHandler = new Handler();
private final boolean showDebugMessages;
private final boolean showDebugMessages;
public AndroidCalculatorNotifier(@NotNull Application application) {
this(application, false);
}
public AndroidCalculatorNotifier(@NotNull Application application) {
this(application, false);
}
public AndroidCalculatorNotifier(@NotNull Application application, boolean showDebugMessages) {
assert Threads.isUiThread();
public AndroidCalculatorNotifier(@NotNull Application application, boolean showDebugMessages) {
assert Threads.isUiThread();
this.application = application;
this.showDebugMessages = showDebugMessages;
}
this.application = application;
this.showDebugMessages = showDebugMessages;
}
@Override
public void showMessage(@NotNull Message message) {
showMessageInUiThread(message.getLocalizedMessage());
}
@Override
public void showMessage(@NotNull Message message) {
showMessageInUiThread(message.getLocalizedMessage());
}
@Override
public void showMessage(@NotNull Integer messageCode, @NotNull MessageType messageType, @NotNull List<Object> parameters) {
showMessage(new AndroidMessage(messageCode, messageType, application, parameters));
}
@Override
public void showMessage(@NotNull Integer messageCode, @NotNull MessageType messageType, @NotNull List<Object> parameters) {
showMessage(new AndroidMessage(messageCode, messageType, application, parameters));
}
@Override
public void showMessage(@NotNull Integer messageCode, @NotNull MessageType messageType, @Nullable Object... parameters) {
showMessage(new AndroidMessage(messageCode, messageType, application, parameters));
}
@Override
public void showMessage(@NotNull Integer messageCode, @NotNull MessageType messageType, @Nullable Object... parameters) {
showMessage(new AndroidMessage(messageCode, messageType, application, parameters));
}
@Override
public void showDebugMessage(@Nullable final String tag, @NotNull final String message) {
if (showDebugMessages) {
showMessageInUiThread(tag == null ? message : tag + ": " + message);
}
}
@Override
public void showDebugMessage(@Nullable final String tag, @NotNull final String message) {
if (showDebugMessages) {
showMessageInUiThread(tag == null ? message : tag + ": " + message);
}
}
private void showMessageInUiThread(@NotNull final String message) {
if (Threads.isUiThread()) {
Toast.makeText(application, message, Toast.LENGTH_SHORT).show();
} else {
uiHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(application,message, Toast.LENGTH_SHORT).show();
}
});
}
}
private void showMessageInUiThread(@NotNull final String message) {
if (Threads.isUiThread()) {
Toast.makeText(application, message, Toast.LENGTH_SHORT).show();
} else {
uiHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(application, message, Toast.LENGTH_SHORT).show();
}
});
}
}
}

View File

@@ -20,75 +20,75 @@ import java.util.List;
*/
public class AndroidCalculatorPreferenceService implements CalculatorPreferenceService {
// one hour
private static final Long PREFERRED_PREFS_INTERVAL_TIME = 1000L * 60L * 60L;
// one hour
private static final Long PREFERRED_PREFS_INTERVAL_TIME = 1000L * 60L * 60L;
@NotNull
private final Application application;
@NotNull
private final Application application;
public AndroidCalculatorPreferenceService(@NotNull Application application) {
this.application = application;
}
public AndroidCalculatorPreferenceService(@NotNull Application application) {
this.application = application;
}
@Override
public void checkPreferredPreferences(boolean force) {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(application);
@Override
public void checkPreferredPreferences(boolean force) {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(application);
final Long currentTime = System.currentTimeMillis();
final Long currentTime = System.currentTimeMillis();
if ( force || ( CalculatorPreferences.Calculations.showCalculationMessagesDialog.getPreference(prefs) && isTimeForCheck(currentTime, prefs))) {
final NumeralBase preferredNumeralBase = CalculatorPreferences.Calculations.preferredNumeralBase.getPreference(prefs);
final NumeralBase numeralBase = AndroidCalculatorEngine.Preferences.numeralBase.getPreference(prefs);
if (force || (CalculatorPreferences.Calculations.showCalculationMessagesDialog.getPreference(prefs) && isTimeForCheck(currentTime, prefs))) {
final NumeralBase preferredNumeralBase = CalculatorPreferences.Calculations.preferredNumeralBase.getPreference(prefs);
final NumeralBase numeralBase = AndroidCalculatorEngine.Preferences.numeralBase.getPreference(prefs);
final AngleUnit preferredAngleUnits = CalculatorPreferences.Calculations.preferredAngleUnits.getPreference(prefs);
final AngleUnit angleUnits = AndroidCalculatorEngine.Preferences.angleUnit.getPreference(prefs);
final AngleUnit preferredAngleUnits = CalculatorPreferences.Calculations.preferredAngleUnits.getPreference(prefs);
final AngleUnit angleUnits = AndroidCalculatorEngine.Preferences.angleUnit.getPreference(prefs);
final List<FixableMessage> messages = new ArrayList<FixableMessage>(2);
if ( numeralBase != preferredNumeralBase ) {
messages.add(new FixableMessage(application.getString(R.string.preferred_numeral_base_message, preferredNumeralBase.name(), numeralBase.name()), MessageType.warning, CalculatorFixableError.preferred_numeral_base));
}
final List<FixableMessage> messages = new ArrayList<FixableMessage>(2);
if (numeralBase != preferredNumeralBase) {
messages.add(new FixableMessage(application.getString(R.string.preferred_numeral_base_message, preferredNumeralBase.name(), numeralBase.name()), MessageType.warning, CalculatorFixableError.preferred_numeral_base));
}
if ( angleUnits != preferredAngleUnits ) {
messages.add(new FixableMessage(application.getString(R.string.preferred_angle_units_message, preferredAngleUnits.name(), angleUnits.name()), MessageType.warning, CalculatorFixableError.preferred_angle_units));
}
if (angleUnits != preferredAngleUnits) {
messages.add(new FixableMessage(application.getString(R.string.preferred_angle_units_message, preferredAngleUnits.name(), angleUnits.name()), MessageType.warning, CalculatorFixableError.preferred_angle_units));
}
FixableMessagesDialog.showDialog(messages, application, true);
FixableMessagesDialog.showDialog(messages, application, true);
CalculatorPreferences.Calculations.lastPreferredPreferencesCheck.putPreference(prefs, currentTime);
}
}
CalculatorPreferences.Calculations.lastPreferredPreferencesCheck.putPreference(prefs, currentTime);
}
}
private boolean isTimeForCheck(@NotNull Long currentTime, @NotNull SharedPreferences preferences) {
final Long lastPreferredPreferencesCheckTime = CalculatorPreferences.Calculations.lastPreferredPreferencesCheck.getPreference(preferences);
private boolean isTimeForCheck(@NotNull Long currentTime, @NotNull SharedPreferences preferences) {
final Long lastPreferredPreferencesCheckTime = CalculatorPreferences.Calculations.lastPreferredPreferencesCheck.getPreference(preferences);
return currentTime - lastPreferredPreferencesCheckTime > PREFERRED_PREFS_INTERVAL_TIME;
}
return currentTime - lastPreferredPreferencesCheckTime > PREFERRED_PREFS_INTERVAL_TIME;
}
@Override
public void setPreferredAngleUnits() {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(application);
setAngleUnits(CalculatorPreferences.Calculations.preferredAngleUnits.getPreference(preferences));
}
@Override
public void setPreferredAngleUnits() {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(application);
setAngleUnits(CalculatorPreferences.Calculations.preferredAngleUnits.getPreference(preferences));
}
@Override
public void setAngleUnits(@NotNull AngleUnit angleUnit) {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(application);
AndroidCalculatorEngine.Preferences.angleUnit.putPreference(preferences, angleUnit);
@Override
public void setAngleUnits(@NotNull AngleUnit angleUnit) {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(application);
AndroidCalculatorEngine.Preferences.angleUnit.putPreference(preferences, angleUnit);
Locator.getInstance().getNotifier().showMessage(new AndroidMessage(R.string.c_angle_units_changed_to, MessageType.info, application, angleUnit.name()));
}
Locator.getInstance().getNotifier().showMessage(new AndroidMessage(R.string.c_angle_units_changed_to, MessageType.info, application, angleUnit.name()));
}
@Override
public void setPreferredNumeralBase() {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(application);
setNumeralBase(CalculatorPreferences.Calculations.preferredNumeralBase.getPreference(preferences));
}
@Override
public void setPreferredNumeralBase() {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(application);
setNumeralBase(CalculatorPreferences.Calculations.preferredNumeralBase.getPreference(preferences));
}
@Override
public void setNumeralBase(@NotNull NumeralBase numeralBase) {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(application);
AndroidCalculatorEngine.Preferences.numeralBase.putPreference(preferences, numeralBase);
@Override
public void setNumeralBase(@NotNull NumeralBase numeralBase) {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(application);
AndroidCalculatorEngine.Preferences.numeralBase.putPreference(preferences, numeralBase);
Locator.getInstance().getNotifier().showMessage(new AndroidMessage(R.string.c_numeral_base_changed_to, MessageType.info, application, numeralBase.name()));
}
Locator.getInstance().getNotifier().showMessage(new AndroidMessage(R.string.c_numeral_base_changed_to, MessageType.info, application, numeralBase.name()));
}
}

View File

@@ -10,30 +10,30 @@ import org.jetbrains.annotations.Nullable;
*/
public enum AndroidFunctionCategory {
trigonometric(R.string.c_fun_category_trig),
hyperbolic_trigonometric(R.string.c_fun_category_hyper_trig),
comparison(R.string.c_fun_category_comparison),
my(R.string.c_fun_category_my),
common(R.string.c_fun_category_common);
trigonometric(R.string.c_fun_category_trig),
hyperbolic_trigonometric(R.string.c_fun_category_hyper_trig),
comparison(R.string.c_fun_category_comparison),
my(R.string.c_fun_category_my),
common(R.string.c_fun_category_common);
private final int captionId;
private final int captionId;
AndroidFunctionCategory(int captionId) {
this.captionId = captionId;
}
AndroidFunctionCategory(int captionId) {
this.captionId = captionId;
}
public int getCaptionId() {
return captionId;
}
public int getCaptionId() {
return captionId;
}
@Nullable
public static AndroidFunctionCategory valueOf( @NotNull FunctionCategory functionCategory ) {
for (AndroidFunctionCategory androidFunctionCategory : values()) {
if ( androidFunctionCategory.name().equals(functionCategory.name()) ) {
return androidFunctionCategory;
}
}
@Nullable
public static AndroidFunctionCategory valueOf(@NotNull FunctionCategory functionCategory) {
for (AndroidFunctionCategory androidFunctionCategory : values()) {
if (androidFunctionCategory.name().equals(functionCategory.name())) {
return androidFunctionCategory;
}
}
return null;
}
return null;
}
}

View File

@@ -18,92 +18,92 @@ import java.util.List;
*/
public enum AndroidNumeralBase {
bin(CalculatorNumeralBase.bin) {
@NotNull
@Override
public List<Integer> getButtonIds() {
return Arrays.asList(R.id.cpp_button_0, R.id.cpp_button_1);
}
},
bin(CalculatorNumeralBase.bin) {
@NotNull
@Override
public List<Integer> getButtonIds() {
return Arrays.asList(R.id.cpp_button_0, R.id.cpp_button_1);
}
},
oct(CalculatorNumeralBase.oct) {
@NotNull
@Override
public List<Integer> getButtonIds() {
final List<Integer> result = new ArrayList<Integer>(bin.getButtonIds());
result.addAll(Arrays.asList(R.id.cpp_button_2, R.id.cpp_button_3, R.id.cpp_button_4, R.id.cpp_button_5, R.id.cpp_button_6, R.id.cpp_button_7));
return result;
}
},
oct(CalculatorNumeralBase.oct) {
@NotNull
@Override
public List<Integer> getButtonIds() {
final List<Integer> result = new ArrayList<Integer>(bin.getButtonIds());
result.addAll(Arrays.asList(R.id.cpp_button_2, R.id.cpp_button_3, R.id.cpp_button_4, R.id.cpp_button_5, R.id.cpp_button_6, R.id.cpp_button_7));
return result;
}
},
dec(CalculatorNumeralBase.dec) {
@NotNull
@Override
public List<Integer> getButtonIds() {
final List<Integer> result = new ArrayList<Integer>(oct.getButtonIds());
result.addAll(Arrays.asList(R.id.cpp_button_8, R.id.cpp_button_9));
return result;
}
},
dec(CalculatorNumeralBase.dec) {
@NotNull
@Override
public List<Integer> getButtonIds() {
final List<Integer> result = new ArrayList<Integer>(oct.getButtonIds());
result.addAll(Arrays.asList(R.id.cpp_button_8, R.id.cpp_button_9));
return result;
}
},
hex(CalculatorNumeralBase.hex) {
hex(CalculatorNumeralBase.hex) {
@NotNull
private List<Integer> specialHexButtonIds = Arrays.asList(R.id.cpp_button_1, R.id.cpp_button_2, R.id.cpp_button_3, R.id.cpp_button_4, R.id.cpp_button_5, R.id.cpp_button_6);
@NotNull
private List<Integer> specialHexButtonIds = Arrays.asList(R.id.cpp_button_1, R.id.cpp_button_2, R.id.cpp_button_3, R.id.cpp_button_4, R.id.cpp_button_5, R.id.cpp_button_6);
@NotNull
@Override
public List<Integer> getButtonIds() {
return dec.getButtonIds();
}
@NotNull
@Override
public List<Integer> getButtonIds() {
return dec.getButtonIds();
}
@Override
protected void toggleButton(boolean show, @NotNull DirectionDragButton button) {
super.toggleButton(show, button);
if (specialHexButtonIds.contains(button.getId())) {
button.showDirectionText(show, DragDirection.left);
button.invalidate();
}
}
};
@Override
protected void toggleButton(boolean show, @NotNull DirectionDragButton button) {
super.toggleButton(show, button);
if (specialHexButtonIds.contains(button.getId())) {
button.showDirectionText(show, DragDirection.left);
button.invalidate();
}
}
};
@NotNull
private final CalculatorNumeralBase calculatorNumeralBase;
@NotNull
private final CalculatorNumeralBase calculatorNumeralBase;
private AndroidNumeralBase(@NotNull CalculatorNumeralBase calculatorNumeralBase) {
this.calculatorNumeralBase = calculatorNumeralBase;
}
private AndroidNumeralBase(@NotNull CalculatorNumeralBase calculatorNumeralBase) {
this.calculatorNumeralBase = calculatorNumeralBase;
}
@NotNull
public abstract List<Integer> getButtonIds();
@NotNull
public abstract List<Integer> getButtonIds();
public void toggleButtons(boolean show, @NotNull Activity activity) {
for (Integer buttonId : getButtonIds()) {
final DirectionDragButton button = (DirectionDragButton) activity.findViewById(buttonId);
if (button != null) {
toggleButton(show, button);
}
}
}
public void toggleButtons(boolean show, @NotNull Activity activity) {
for (Integer buttonId : getButtonIds()) {
final DirectionDragButton button = (DirectionDragButton) activity.findViewById(buttonId);
if (button != null) {
toggleButton(show, button);
}
}
}
protected void toggleButton(boolean show, @NotNull DirectionDragButton button) {
button.setShowText(show);
button.invalidate();
}
protected void toggleButton(boolean show, @NotNull DirectionDragButton button) {
button.setShowText(show);
button.invalidate();
}
@NotNull
public NumeralBase getNumeralBase() {
return calculatorNumeralBase.getNumeralBase();
}
@NotNull
public NumeralBase getNumeralBase() {
return calculatorNumeralBase.getNumeralBase();
}
@NotNull
public static AndroidNumeralBase valueOf(@NotNull NumeralBase nb) {
for (AndroidNumeralBase androidNumeralBase : values()) {
if (androidNumeralBase.calculatorNumeralBase.getNumeralBase() == nb) {
return androidNumeralBase;
}
}
@NotNull
public static AndroidNumeralBase valueOf(@NotNull NumeralBase nb) {
for (AndroidNumeralBase androidNumeralBase : values()) {
if (androidNumeralBase.calculatorNumeralBase.getNumeralBase() == nb) {
return androidNumeralBase;
}
}
throw new IllegalArgumentException(nb + " is not supported numeral base!");
}
throw new IllegalArgumentException(nb + " is not supported numeral base!");
}
}

View File

@@ -10,29 +10,29 @@ import org.jetbrains.annotations.Nullable;
*/
public enum AndroidOperatorCategory {
derivatives(R.string.derivatives),
other(R.string.other),
my(R.string.c_fun_category_my),
common(R.string.c_fun_category_common);
derivatives(R.string.derivatives),
other(R.string.other),
my(R.string.c_fun_category_my),
common(R.string.c_fun_category_common);
private final int captionId;
private final int captionId;
AndroidOperatorCategory(int captionId) {
this.captionId = captionId;
}
AndroidOperatorCategory(int captionId) {
this.captionId = captionId;
}
public int getCaptionId() {
return captionId;
}
public int getCaptionId() {
return captionId;
}
@Nullable
public static AndroidOperatorCategory valueOf(@NotNull OperatorCategory operatorCategory) {
for (AndroidOperatorCategory androidOperatorCategory : values()) {
if ( androidOperatorCategory.name().equals(operatorCategory.name()) ) {
return androidOperatorCategory;
}
}
@Nullable
public static AndroidOperatorCategory valueOf(@NotNull OperatorCategory operatorCategory) {
for (AndroidOperatorCategory androidOperatorCategory : values()) {
if (androidOperatorCategory.name().equals(operatorCategory.name())) {
return androidOperatorCategory;
}
}
return null;
}
return null;
}
}

View File

@@ -10,27 +10,27 @@ import org.jetbrains.annotations.Nullable;
*/
public enum AndroidVarCategory {
system(R.string.c_var_system),
my(R.string.c_var_my);
system(R.string.c_var_system),
my(R.string.c_var_my);
private final int captionId;
private final int captionId;
AndroidVarCategory(int captionId) {
this.captionId = captionId;
}
AndroidVarCategory(int captionId) {
this.captionId = captionId;
}
public int getCaptionId() {
return captionId;
}
public int getCaptionId() {
return captionId;
}
@Nullable
public static AndroidVarCategory valueOf(@NotNull VarCategory varCategory) {
for (AndroidVarCategory androidVarCategory : values()) {
if ( androidVarCategory.name().equals(varCategory.name()) ) {
return androidVarCategory;
}
}
@Nullable
public static AndroidVarCategory valueOf(@NotNull VarCategory varCategory) {
for (AndroidVarCategory androidVarCategory : values()) {
if (androidVarCategory.name().equals(varCategory.name())) {
return androidVarCategory;
}
}
return null;
}
return null;
}
}

View File

@@ -36,140 +36,140 @@ import org.solovyev.common.text.Strings;
public class CalculatorActivity extends SherlockFragmentActivity implements SharedPreferences.OnSharedPreferenceChangeListener, CalculatorEventListener {
@NotNull
public static final String TAG = CalculatorActivity.class.getSimpleName();
@NotNull
public static final String TAG = CalculatorActivity.class.getSimpleName();
private boolean useBackAsPrev;
@NotNull
private CalculatorActivityHelper activityHelper;
@NotNull
private CalculatorActivityHelper activityHelper;
/**
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final CalculatorPreferences.Gui.Layout layout = CalculatorPreferences.Gui.layout.getPreferenceNoError(preferences);
final CalculatorPreferences.Gui.Layout layout = CalculatorPreferences.Gui.layout.getPreferenceNoError(preferences);
activityHelper = CalculatorApplication.getInstance().createActivityHelper(layout.getLayoutId(), TAG);
activityHelper.logDebug("onCreate");
activityHelper.onCreate(this, savedInstanceState);
activityHelper = CalculatorApplication.getInstance().createActivityHelper(layout.getLayoutId(), TAG);
activityHelper.logDebug("onCreate");
activityHelper.onCreate(this, savedInstanceState);
super.onCreate(savedInstanceState);
activityHelper.logDebug("super.onCreate");
super.onCreate(savedInstanceState);
activityHelper.logDebug("super.onCreate");
if (isMultiPane()) {
activityHelper.addTab(this, CalculatorFragmentType.history, null, R.id.main_second_pane);
activityHelper.addTab(this, CalculatorFragmentType.saved_history, null, R.id.main_second_pane);
activityHelper.addTab(this, CalculatorFragmentType.variables, null, R.id.main_second_pane);
activityHelper.addTab(this, CalculatorFragmentType.functions, null, R.id.main_second_pane);
activityHelper.addTab(this, CalculatorFragmentType.operators, null, R.id.main_second_pane);
activityHelper.addTab(this, CalculatorPlotActivity.getPlotterFragmentType(), null, R.id.main_second_pane);
activityHelper.addTab(this, CalculatorFragmentType.faq, null, R.id.main_second_pane);
} else {
getSupportActionBar().hide();
}
if (isMultiPane()) {
activityHelper.addTab(this, CalculatorFragmentType.history, null, R.id.main_second_pane);
activityHelper.addTab(this, CalculatorFragmentType.saved_history, null, R.id.main_second_pane);
activityHelper.addTab(this, CalculatorFragmentType.variables, null, R.id.main_second_pane);
activityHelper.addTab(this, CalculatorFragmentType.functions, null, R.id.main_second_pane);
activityHelper.addTab(this, CalculatorFragmentType.operators, null, R.id.main_second_pane);
activityHelper.addTab(this, CalculatorPlotActivity.getPlotterFragmentType(), null, R.id.main_second_pane);
activityHelper.addTab(this, CalculatorFragmentType.faq, null, R.id.main_second_pane);
} else {
getSupportActionBar().hide();
}
FragmentUtils.createFragment(this, CalculatorEditorFragment.class, R.id.editorContainer, "editor");
FragmentUtils.createFragment(this, CalculatorDisplayFragment.class, R.id.displayContainer, "display");
FragmentUtils.createFragment(this, CalculatorKeyboardFragment.class, R.id.keyboardContainer, "keyboard");
FragmentUtils.createFragment(this, CalculatorEditorFragment.class, R.id.editorContainer, "editor");
FragmentUtils.createFragment(this, CalculatorDisplayFragment.class, R.id.displayContainer, "display");
FragmentUtils.createFragment(this, CalculatorKeyboardFragment.class, R.id.keyboardContainer, "keyboard");
this.useBackAsPrev = CalculatorPreferences.Gui.usePrevAsBack.getPreference(preferences);
firstTimeInit(preferences, this);
this.useBackAsPrev = CalculatorPreferences.Gui.usePrevAsBack.getPreference(preferences);
firstTimeInit(preferences, this);
toggleOrientationChange(preferences);
toggleOrientationChange(preferences);
preferences.registerOnSharedPreferenceChangeListener(this);
preferences.registerOnSharedPreferenceChangeListener(this);
Locator.getInstance().getPreferenceService().checkPreferredPreferences(false);
Locator.getInstance().getPreferenceService().checkPreferredPreferences(false);
if ( CalculatorApplication.isMonkeyRunner(this) ) {
Locator.getInstance().getKeyboard().buttonPressed("123");
Locator.getInstance().getKeyboard().buttonPressed("+");
Locator.getInstance().getKeyboard().buttonPressed("321");
}
}
if (CalculatorApplication.isMonkeyRunner(this)) {
Locator.getInstance().getKeyboard().buttonPressed("123");
Locator.getInstance().getKeyboard().buttonPressed("+");
Locator.getInstance().getKeyboard().buttonPressed("321");
}
}
private boolean isMultiPane() {
return findViewById(R.id.main_second_pane) != null;
}
private boolean isMultiPane() {
return findViewById(R.id.main_second_pane) != null;
}
@NotNull
private AndroidCalculator getCalculator() {
return ((AndroidCalculator) Locator.getInstance().getCalculator());
}
@NotNull
private AndroidCalculator getCalculator() {
return ((AndroidCalculator) Locator.getInstance().getCalculator());
}
private static void firstTimeInit(@NotNull SharedPreferences preferences, @NotNull Context context) {
final Integer appOpenedCounter = CalculatorPreferences.appOpenedCounter.getPreference(preferences);
if (appOpenedCounter != null) {
CalculatorPreferences.appOpenedCounter.putPreference(preferences, appOpenedCounter + 1);
}
private static void firstTimeInit(@NotNull SharedPreferences preferences, @NotNull Context context) {
final Integer appOpenedCounter = CalculatorPreferences.appOpenedCounter.getPreference(preferences);
if (appOpenedCounter != null) {
CalculatorPreferences.appOpenedCounter.putPreference(preferences, appOpenedCounter + 1);
}
final Integer savedVersion = CalculatorPreferences.appVersion.getPreference(preferences);
final Integer savedVersion = CalculatorPreferences.appVersion.getPreference(preferences);
final int appVersion = Android.getAppVersionCode(context);
final int appVersion = Android.getAppVersionCode(context);
CalculatorPreferences.appVersion.putPreference(preferences, appVersion);
CalculatorPreferences.appVersion.putPreference(preferences, appVersion);
if (!CalculatorApplication.isMonkeyRunner(context)) {
if (!CalculatorApplication.isMonkeyRunner(context)) {
boolean dialogShown = false;
if (Objects.areEqual(savedVersion, CalculatorPreferences.appVersion.getDefaultValue())) {
// new start
final AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(R.string.c_first_start_text);
builder.setPositiveButton(android.R.string.ok, null);
builder.setTitle(R.string.c_first_start_text_title);
builder.create().show();
dialogShown = true;
} else {
if (savedVersion < appVersion) {
final boolean showReleaseNotes = CalculatorPreferences.Gui.showReleaseNotes.getPreference(preferences);
if (showReleaseNotes) {
final String releaseNotes = CalculatorReleaseNotesFragment.getReleaseNotes(context, savedVersion + 1);
if (!Strings.isEmpty(releaseNotes)) {
final AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(Html.fromHtml(releaseNotes));
builder.setPositiveButton(android.R.string.ok, null);
builder.setTitle(R.string.c_release_notes);
builder.create().show();
dialogShown = true;
}
}
}
}
boolean dialogShown = false;
if (Objects.areEqual(savedVersion, CalculatorPreferences.appVersion.getDefaultValue())) {
// new start
final AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(R.string.c_first_start_text);
builder.setPositiveButton(android.R.string.ok, null);
builder.setTitle(R.string.c_first_start_text_title);
builder.create().show();
dialogShown = true;
} else {
if (savedVersion < appVersion) {
final boolean showReleaseNotes = CalculatorPreferences.Gui.showReleaseNotes.getPreference(preferences);
if (showReleaseNotes) {
final String releaseNotes = CalculatorReleaseNotesFragment.getReleaseNotes(context, savedVersion + 1);
if (!Strings.isEmpty(releaseNotes)) {
final AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(Html.fromHtml(releaseNotes));
builder.setPositiveButton(android.R.string.ok, null);
builder.setTitle(R.string.c_release_notes);
builder.create().show();
dialogShown = true;
}
}
}
}
//Log.d(this.getClass().getName(), "Application was opened " + appOpenedCounter + " time!");
if (!dialogShown) {
if (appOpenedCounter != null && appOpenedCounter > 10) {
dialogShown = showSpecialWindow(preferences, CalculatorPreferences.Gui.feedbackWindowShown, R.layout.feedback, R.id.feedbackText, context);
}
}
}
}
//Log.d(this.getClass().getName(), "Application was opened " + appOpenedCounter + " time!");
if (!dialogShown) {
if (appOpenedCounter != null && appOpenedCounter > 10) {
dialogShown = showSpecialWindow(preferences, CalculatorPreferences.Gui.feedbackWindowShown, R.layout.feedback, R.id.feedbackText, context);
}
}
}
}
private static boolean showSpecialWindow(@NotNull SharedPreferences preferences, @NotNull Preference<Boolean> specialWindowShownPref, int layoutId, int textViewId, @NotNull Context context) {
boolean result = false;
private static boolean showSpecialWindow(@NotNull SharedPreferences preferences, @NotNull Preference<Boolean> specialWindowShownPref, int layoutId, int textViewId, @NotNull Context context) {
boolean result = false;
final Boolean specialWindowShown = specialWindowShownPref.getPreference(preferences);
if ( specialWindowShown != null && !specialWindowShown ) {
final LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
final View view = layoutInflater.inflate(layoutId, null);
final Boolean specialWindowShown = specialWindowShownPref.getPreference(preferences);
if (specialWindowShown != null && !specialWindowShown) {
final LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
final View view = layoutInflater.inflate(layoutId, null);
final TextView feedbackTextView = (TextView) view.findViewById(textViewId);
feedbackTextView.setMovementMethod(LinkMovementMethod.getInstance());
final TextView feedbackTextView = (TextView) view.findViewById(textViewId);
feedbackTextView.setMovementMethod(LinkMovementMethod.getInstance());
final AlertDialog.Builder builder = new AlertDialog.Builder(context).setView(view);
builder.setPositiveButton(android.R.string.ok, null);
builder.create().show();
final AlertDialog.Builder builder = new AlertDialog.Builder(context).setView(view);
builder.setPositiveButton(android.R.string.ok, null);
builder.create().show();
result = true;
specialWindowShownPref.putPreference(preferences, true);
}
result = true;
specialWindowShownPref.putPreference(preferences, true);
}
return result;
}
return result;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
@@ -182,157 +182,157 @@ public class CalculatorActivity extends SherlockFragmentActivity implements Shar
return super.onKeyDown(keyCode, event);
}
@SuppressWarnings({"UnusedDeclaration"})
public void equalsButtonClickHandler(@NotNull View v) {
buttonPressed(CalculatorSpecialButton.equals);
}
@SuppressWarnings({"UnusedDeclaration"})
public void equalsButtonClickHandler(@NotNull View v) {
buttonPressed(CalculatorSpecialButton.equals);
}
@Override
protected void onPause() {
this.activityHelper.onPause(this);
@Override
protected void onPause() {
this.activityHelper.onPause(this);
super.onPause();
}
super.onPause();
}
@Override
@Override
protected void onResume() {
super.onResume();
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final CalculatorPreferences.Gui.Layout newLayout = CalculatorPreferences.Gui.layout.getPreference(preferences);
if ( newLayout != activityHelper.getLayout() ) {
Activities.restartActivity(this);
}
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final CalculatorPreferences.Gui.Layout newLayout = CalculatorPreferences.Gui.layout.getPreference(preferences);
if (newLayout != activityHelper.getLayout()) {
Activities.restartActivity(this);
}
this.activityHelper.onResume(this);
this.activityHelper.onResume(this);
}
@Override
protected void onDestroy() {
activityHelper.onDestroy(this);
activityHelper.onDestroy(this);
PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(this);
PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(this);
super.onDestroy();
super.onDestroy();
}
@Override
public void onSharedPreferenceChanged(SharedPreferences preferences, @Nullable String key) {
if ( CalculatorPreferences.Gui.usePrevAsBack.getKey().equals(key) ) {
if (CalculatorPreferences.Gui.usePrevAsBack.getKey().equals(key)) {
useBackAsPrev = CalculatorPreferences.Gui.usePrevAsBack.getPreference(preferences);
}
if ( CalculatorPreferences.Gui.autoOrientation.getKey().equals(key) ) {
toggleOrientationChange(preferences);
}
if (CalculatorPreferences.Gui.autoOrientation.getKey().equals(key)) {
toggleOrientationChange(preferences);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
activityHelper.onSaveInstanceState(this, outState);
}
activityHelper.onSaveInstanceState(this, outState);
}
private void toggleOrientationChange(@Nullable SharedPreferences preferences) {
preferences = preferences == null ? PreferenceManager.getDefaultSharedPreferences(this) : preferences;
if (CalculatorPreferences.Gui.autoOrientation.getPreference(preferences)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
private void toggleOrientationChange(@Nullable SharedPreferences preferences) {
preferences = preferences == null ? PreferenceManager.getDefaultSharedPreferences(this) : preferences;
if (CalculatorPreferences.Gui.autoOrientation.getPreference(preferences)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
/*
**********************************************************************
*
* BUTTON HANDLERS
*
**********************************************************************
*/
/*
**********************************************************************
*
* BUTTON HANDLERS
*
**********************************************************************
*/
@SuppressWarnings({"UnusedDeclaration"})
public void elementaryButtonClickHandler(@NotNull View v) {
throw new UnsupportedOperationException("Not implemented yet!");
}
@SuppressWarnings({"UnusedDeclaration"})
public void elementaryButtonClickHandler(@NotNull View v) {
throw new UnsupportedOperationException("Not implemented yet!");
}
@SuppressWarnings({"UnusedDeclaration"})
public void historyButtonClickHandler(@NotNull View v) {
buttonPressed(CalculatorSpecialButton.history);
}
@SuppressWarnings({"UnusedDeclaration"})
public void historyButtonClickHandler(@NotNull View v) {
buttonPressed(CalculatorSpecialButton.history);
}
@SuppressWarnings({"UnusedDeclaration"})
public void eraseButtonClickHandler(@NotNull View v) {
buttonPressed(CalculatorSpecialButton.erase);
}
@SuppressWarnings({"UnusedDeclaration"})
public void eraseButtonClickHandler(@NotNull View v) {
buttonPressed(CalculatorSpecialButton.erase);
}
@SuppressWarnings({"UnusedDeclaration"})
public void simplifyButtonClickHandler(@NotNull View v) {
throw new UnsupportedOperationException("Not implemented yet!");
}
@SuppressWarnings({"UnusedDeclaration"})
public void simplifyButtonClickHandler(@NotNull View v) {
throw new UnsupportedOperationException("Not implemented yet!");
}
@SuppressWarnings({"UnusedDeclaration"})
public void pasteButtonClickHandler(@NotNull View v) {
buttonPressed(CalculatorSpecialButton.paste);
}
@SuppressWarnings({"UnusedDeclaration"})
public void pasteButtonClickHandler(@NotNull View v) {
buttonPressed(CalculatorSpecialButton.paste);
}
@SuppressWarnings({"UnusedDeclaration"})
public void copyButtonClickHandler(@NotNull View v) {
buttonPressed(CalculatorSpecialButton.copy);
}
@SuppressWarnings({"UnusedDeclaration"})
public void copyButtonClickHandler(@NotNull View v) {
buttonPressed(CalculatorSpecialButton.copy);
}
@NotNull
private static CalculatorKeyboard getKeyboard() {
return Locator.getInstance().getKeyboard();
}
@NotNull
private static CalculatorKeyboard getKeyboard() {
return Locator.getInstance().getKeyboard();
}
@SuppressWarnings({"UnusedDeclaration"})
public void clearButtonClickHandler(@NotNull View v) {
buttonPressed(CalculatorSpecialButton.clear);
}
@SuppressWarnings({"UnusedDeclaration"})
public void clearButtonClickHandler(@NotNull View v) {
buttonPressed(CalculatorSpecialButton.clear);
}
@SuppressWarnings({"UnusedDeclaration"})
public void digitButtonClickHandler(@NotNull View v) {
Log.d(String.valueOf(v.getId()), "digitButtonClickHandler() for: " + v.getId() + ". Pressed: " + v.isPressed());
@SuppressWarnings({"UnusedDeclaration"})
public void digitButtonClickHandler(@NotNull View v) {
Log.d(String.valueOf(v.getId()), "digitButtonClickHandler() for: " + v.getId() + ". Pressed: " + v.isPressed());
if (v instanceof Button) {
buttonPressed(((Button)v).getText().toString());
}
}
if (v instanceof Button) {
buttonPressed(((Button) v).getText().toString());
}
}
private void buttonPressed(@NotNull CalculatorSpecialButton button) {
buttonPressed(button.getActionCode());
}
private void buttonPressed(@NotNull CalculatorSpecialButton button) {
buttonPressed(button.getActionCode());
}
private void buttonPressed(@NotNull String text) {
getKeyboard().buttonPressed(text);
}
private void buttonPressed(@NotNull String text) {
getKeyboard().buttonPressed(text);
}
@SuppressWarnings({"UnusedDeclaration"})
public void functionsButtonClickHandler(@NotNull View v) {
buttonPressed(CalculatorSpecialButton.functions);
}
@SuppressWarnings({"UnusedDeclaration"})
public void functionsButtonClickHandler(@NotNull View v) {
buttonPressed(CalculatorSpecialButton.functions);
}
@SuppressWarnings({"UnusedDeclaration"})
public void operatorsButtonClickHandler(@NotNull View v) {
buttonPressed(CalculatorSpecialButton.operators);
}
@SuppressWarnings({"UnusedDeclaration"})
public void operatorsButtonClickHandler(@NotNull View v) {
buttonPressed(CalculatorSpecialButton.operators);
}
@SuppressWarnings({"UnusedDeclaration"})
public void varsButtonClickHandler(@NotNull View v) {
buttonPressed(CalculatorSpecialButton.vars);
}
@SuppressWarnings({"UnusedDeclaration"})
public void varsButtonClickHandler(@NotNull View v) {
buttonPressed(CalculatorSpecialButton.vars);
}
@SuppressWarnings({"UnusedDeclaration"})
public void likeButtonClickHandler(@NotNull View v) {
buttonPressed(CalculatorSpecialButton.like);
}
@SuppressWarnings({"UnusedDeclaration"})
public void likeButtonClickHandler(@NotNull View v) {
buttonPressed(CalculatorSpecialButton.like);
}
@Override
public void onCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
switch (calculatorEventType) {
case plot_graph:
Threads.tryRunOnUiThread(this, new Runnable() {
@Override
public void onCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
switch (calculatorEventType) {
case plot_graph:
Threads.tryRunOnUiThread(this, new Runnable() {
@Override
public void run() {
if (isMultiPane()) {
@@ -349,7 +349,7 @@ public class CalculatorActivity extends SherlockFragmentActivity implements Shar
}
}
});
break;
}
}
break;
}
}
}

View File

@@ -15,52 +15,57 @@ import org.jetbrains.annotations.Nullable;
*/
public interface CalculatorActivityHelper {
void onCreate(@NotNull SherlockFragmentActivity activity, @Nullable Bundle savedInstanceState);
void onCreate(@NotNull Activity activity, @Nullable Bundle savedInstanceState);
void onCreate(@NotNull SherlockFragmentActivity activity, @Nullable Bundle savedInstanceState);
void onSaveInstanceState(@NotNull SherlockFragmentActivity activity, @NotNull Bundle outState);
void onSaveInstanceState(@NotNull Activity activity, @NotNull Bundle outState);
void onCreate(@NotNull Activity activity, @Nullable Bundle savedInstanceState);
int getLayoutId();
void onSaveInstanceState(@NotNull SherlockFragmentActivity activity, @NotNull Bundle outState);
@NotNull
CalculatorPreferences.Gui.Theme getTheme();
void onSaveInstanceState(@NotNull Activity activity, @NotNull Bundle outState);
@NotNull
CalculatorPreferences.Gui.Layout getLayout();
int getLayoutId();
void onResume(@NotNull SherlockFragmentActivity activity);
void onResume(@NotNull Activity activity);
@NotNull
CalculatorPreferences.Gui.Theme getTheme();
void onPause(@NotNull Activity activity);
void onPause(@NotNull SherlockFragmentActivity activity);
@NotNull
CalculatorPreferences.Gui.Layout getLayout();
void onDestroy(@NotNull SherlockFragmentActivity activity);
void onDestroy(@NotNull Activity activity);
void onResume(@NotNull SherlockFragmentActivity activity);
void addTab(@NotNull SherlockFragmentActivity activity,
@NotNull String tag,
@NotNull Class<? extends Fragment> fragmentClass,
@Nullable Bundle fragmentArgs,
int captionResId,
int parentViewId);
void onResume(@NotNull Activity activity);
void addTab(@NotNull SherlockFragmentActivity activity,
@NotNull CalculatorFragmentType fragmentType,
@Nullable Bundle fragmentArgs,
int parentViewId);
void onPause(@NotNull Activity activity);
void setFragment(@NotNull SherlockFragmentActivity activity,
@NotNull CalculatorFragmentType fragmentType,
@Nullable Bundle fragmentArgs,
int parentViewId);
void onPause(@NotNull SherlockFragmentActivity activity);
void onDestroy(@NotNull SherlockFragmentActivity activity);
void onDestroy(@NotNull Activity activity);
void addTab(@NotNull SherlockFragmentActivity activity,
@NotNull String tag,
@NotNull Class<? extends Fragment> fragmentClass,
@Nullable Bundle fragmentArgs,
int captionResId,
int parentViewId);
void addTab(@NotNull SherlockFragmentActivity activity,
@NotNull CalculatorFragmentType fragmentType,
@Nullable Bundle fragmentArgs,
int parentViewId);
void setFragment(@NotNull SherlockFragmentActivity activity,
@NotNull CalculatorFragmentType fragmentType,
@Nullable Bundle fragmentArgs,
int parentViewId);
void logDebug(@NotNull String message);
void logDebug(@NotNull String message);
void processButtons(@NotNull Activity activity, @NotNull View root);
void processButtons(@NotNull Activity activity, @NotNull View root);
void logError(@NotNull String message);
void logError(@NotNull String message);
void selectTab(@NotNull SherlockFragmentActivity activity, @NotNull CalculatorFragmentType fragmentType);
void selectTab(@NotNull SherlockFragmentActivity activity, @NotNull CalculatorFragmentType fragmentType);
}

View File

@@ -29,298 +29,298 @@ import org.solovyev.android.sherlock.tabs.ActionBarFragmentTabListener;
*/
public class CalculatorActivityHelperImpl extends AbstractCalculatorHelper implements CalculatorActivityHelper {
/*
**********************************************************************
*
* CONSTANTS
*
**********************************************************************
*/
/*
**********************************************************************
*
* CONSTANTS
*
**********************************************************************
*/
/*
**********************************************************************
*
* FIELDS
*
**********************************************************************
*/
/*
**********************************************************************
*
* FIELDS
*
**********************************************************************
*/
private int layoutId;
private int layoutId;
private boolean homeIcon = false;
private boolean homeIcon = false;
@NotNull
private CalculatorPreferences.Gui.Theme theme;
@NotNull
private CalculatorPreferences.Gui.Theme theme;
@NotNull
private CalculatorPreferences.Gui.Layout layout;
@NotNull
private CalculatorPreferences.Gui.Layout layout;
private int selectedNavigationIndex = 0;
private int selectedNavigationIndex = 0;
public CalculatorActivityHelperImpl(int layoutId, @NotNull String logTag) {
super(logTag);
this.layoutId = layoutId;
}
public CalculatorActivityHelperImpl(int layoutId, @NotNull String logTag) {
super(logTag);
this.layoutId = layoutId;
}
public CalculatorActivityHelperImpl(int layoutId, boolean homeIcon) {
this.layoutId = layoutId;
this.homeIcon = homeIcon;
}
public CalculatorActivityHelperImpl(int layoutId, boolean homeIcon) {
this.layoutId = layoutId;
this.homeIcon = homeIcon;
}
@Override
public void onCreate(@NotNull Activity activity, @Nullable Bundle savedInstanceState) {
super.onCreate(activity);
@Override
public void onCreate(@NotNull Activity activity, @Nullable Bundle savedInstanceState) {
super.onCreate(activity);
if (activity instanceof CalculatorEventListener) {
Locator.getInstance().getCalculator().addCalculatorEventListener((CalculatorEventListener) activity);
}
if (activity instanceof CalculatorEventListener) {
Locator.getInstance().getCalculator().addCalculatorEventListener((CalculatorEventListener) activity);
}
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity);
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity);
this.theme = CalculatorPreferences.Gui.getTheme(preferences);
activity.setTheme(this.theme.getThemeId());
this.theme = CalculatorPreferences.Gui.getTheme(preferences);
activity.setTheme(this.theme.getThemeId());
this.layout = CalculatorPreferences.Gui.getLayout(preferences);
this.layout = CalculatorPreferences.Gui.getLayout(preferences);
activity.setContentView(layoutId);
activity.setContentView(layoutId);
final View root = activity.findViewById(R.id.main_layout);
if (root != null) {
processButtons(activity, root);
addHelpInfo(activity, root);
} else {
Log.e(CalculatorActivityHelperImpl.class.getSimpleName(), "Root is null for " + activity.getClass().getName());
}
}
final View root = activity.findViewById(R.id.main_layout);
if (root != null) {
processButtons(activity, root);
addHelpInfo(activity, root);
} else {
Log.e(CalculatorActivityHelperImpl.class.getSimpleName(), "Root is null for " + activity.getClass().getName());
}
}
@Override
public void onCreate(@NotNull final SherlockFragmentActivity activity, @Nullable Bundle savedInstanceState) {
this.onCreate((Activity) activity, savedInstanceState);
@Override
public void onCreate(@NotNull final SherlockFragmentActivity activity, @Nullable Bundle savedInstanceState) {
this.onCreate((Activity) activity, savedInstanceState);
final ActionBar actionBar = activity.getSupportActionBar();
actionBar.setDisplayUseLogoEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(homeIcon);
actionBar.setHomeButtonEnabled(false);
actionBar.setDisplayShowHomeEnabled(true);
final ActionBar actionBar = activity.getSupportActionBar();
actionBar.setDisplayUseLogoEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(homeIcon);
actionBar.setHomeButtonEnabled(false);
actionBar.setDisplayShowHomeEnabled(true);
toggleTitle(activity, true);
toggleTitle(activity, true);
actionBar.setIcon(R.drawable.ab_icon);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
}
actionBar.setIcon(R.drawable.ab_icon);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
}
private void toggleTitle(@NotNull SherlockFragmentActivity activity, boolean showTitle) {
final ActionBar actionBar = activity.getSupportActionBar();
private void toggleTitle(@NotNull SherlockFragmentActivity activity, boolean showTitle) {
final ActionBar actionBar = activity.getSupportActionBar();
if (activity instanceof CalculatorActivity) {
if (Views.getScreenOrientation(activity) == Configuration.ORIENTATION_PORTRAIT) {
actionBar.setDisplayShowTitleEnabled(true);
} else {
actionBar.setDisplayShowTitleEnabled(false);
}
} else {
actionBar.setDisplayShowTitleEnabled(showTitle);
}
}
if (activity instanceof CalculatorActivity) {
if (Views.getScreenOrientation(activity) == Configuration.ORIENTATION_PORTRAIT) {
actionBar.setDisplayShowTitleEnabled(true);
} else {
actionBar.setDisplayShowTitleEnabled(false);
}
} else {
actionBar.setDisplayShowTitleEnabled(showTitle);
}
}
public void restoreSavedTab(@NotNull SherlockFragmentActivity activity) {
final ActionBar actionBar = activity.getSupportActionBar();
if (selectedNavigationIndex >= 0 && selectedNavigationIndex < actionBar.getTabCount()) {
actionBar.setSelectedNavigationItem(selectedNavigationIndex);
}
}
public void restoreSavedTab(@NotNull SherlockFragmentActivity activity) {
final ActionBar actionBar = activity.getSupportActionBar();
if (selectedNavigationIndex >= 0 && selectedNavigationIndex < actionBar.getTabCount()) {
actionBar.setSelectedNavigationItem(selectedNavigationIndex);
}
}
@Override
public void onSaveInstanceState(@NotNull SherlockFragmentActivity activity, @NotNull Bundle outState) {
onSaveInstanceState((Activity) activity, outState);
}
@Override
public void onSaveInstanceState(@NotNull SherlockFragmentActivity activity, @NotNull Bundle outState) {
onSaveInstanceState((Activity) activity, outState);
}
@Override
public void onSaveInstanceState(@NotNull Activity activity, @NotNull Bundle outState) {
}
@Override
public void onSaveInstanceState(@NotNull Activity activity, @NotNull Bundle outState) {
}
@Override
public void onResume(@NotNull Activity activity) {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity);
@Override
public void onResume(@NotNull Activity activity) {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity);
final CalculatorPreferences.Gui.Theme newTheme = CalculatorPreferences.Gui.theme.getPreference(preferences);
if (!theme.equals(newTheme)) {
Activities.restartActivity(activity);
}
}
final CalculatorPreferences.Gui.Theme newTheme = CalculatorPreferences.Gui.theme.getPreference(preferences);
if (!theme.equals(newTheme)) {
Activities.restartActivity(activity);
}
}
@Override
public void onPause(@NotNull Activity activity) {
}
@Override
public void onPause(@NotNull Activity activity) {
}
@Override
public void onPause(@NotNull SherlockFragmentActivity activity) {
onPause((Activity) activity);
@Override
public void onPause(@NotNull SherlockFragmentActivity activity) {
onPause((Activity) activity);
final int selectedNavigationIndex = activity.getSupportActionBar().getSelectedNavigationIndex();
if (selectedNavigationIndex >= 0) {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity);
final SharedPreferences.Editor editor = preferences.edit();
editor.putInt(getSavedTabPreferenceName(activity), selectedNavigationIndex);
editor.commit();
}
final int selectedNavigationIndex = activity.getSupportActionBar().getSelectedNavigationIndex();
if (selectedNavigationIndex >= 0) {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity);
final SharedPreferences.Editor editor = preferences.edit();
editor.putInt(getSavedTabPreferenceName(activity), selectedNavigationIndex);
editor.commit();
}
}
}
@NotNull
private String getSavedTabPreferenceName(@NotNull Activity activity) {
return "tab_" + activity.getClass().getSimpleName();
}
@NotNull
private String getSavedTabPreferenceName(@NotNull Activity activity) {
return "tab_" + activity.getClass().getSimpleName();
}
@Override
public void onDestroy(@NotNull Activity activity) {
super.onDestroy(activity);
@Override
public void onDestroy(@NotNull Activity activity) {
super.onDestroy(activity);
if (activity instanceof CalculatorEventListener) {
Locator.getInstance().getCalculator().removeCalculatorEventListener((CalculatorEventListener) activity);
}
}
if (activity instanceof CalculatorEventListener) {
Locator.getInstance().getCalculator().removeCalculatorEventListener((CalculatorEventListener) activity);
}
}
@Override
public void onDestroy(@NotNull SherlockFragmentActivity activity) {
this.onDestroy((Activity) activity);
}
@Override
public void onDestroy(@NotNull SherlockFragmentActivity activity) {
this.onDestroy((Activity) activity);
}
@Override
public void addTab(@NotNull SherlockFragmentActivity activity,
@NotNull String tag,
@NotNull Class<? extends Fragment> fragmentClass,
@Nullable Bundle fragmentArgs,
int captionResId,
int parentViewId) {
final ActionBar actionBar = activity.getSupportActionBar();
@Override
public void addTab(@NotNull SherlockFragmentActivity activity,
@NotNull String tag,
@NotNull Class<? extends Fragment> fragmentClass,
@Nullable Bundle fragmentArgs,
int captionResId,
int parentViewId) {
final ActionBar actionBar = activity.getSupportActionBar();
final ActionBar.Tab tab = actionBar.newTab();
tab.setTag(tag);
tab.setText(captionResId);
final ActionBar.Tab tab = actionBar.newTab();
tab.setTag(tag);
tab.setText(captionResId);
final ActionBarFragmentTabListener listener = new ActionBarFragmentTabListener(activity, tag, fragmentClass, fragmentArgs, parentViewId);
tab.setTabListener(listener);
actionBar.addTab(tab);
}
final ActionBarFragmentTabListener listener = new ActionBarFragmentTabListener(activity, tag, fragmentClass, fragmentArgs, parentViewId);
tab.setTabListener(listener);
actionBar.addTab(tab);
}
@Override
public void addTab(@NotNull SherlockFragmentActivity activity, @NotNull CalculatorFragmentType fragmentType, @Nullable Bundle fragmentArgs, int parentViewId) {
addTab(activity, fragmentType.getFragmentTag(), fragmentType.getFragmentClass(), fragmentArgs, fragmentType.getDefaultTitleResId(), parentViewId);
}
@Override
public void addTab(@NotNull SherlockFragmentActivity activity, @NotNull CalculatorFragmentType fragmentType, @Nullable Bundle fragmentArgs, int parentViewId) {
addTab(activity, fragmentType.getFragmentTag(), fragmentType.getFragmentClass(), fragmentArgs, fragmentType.getDefaultTitleResId(), parentViewId);
}
@Override
public void setFragment(@NotNull SherlockFragmentActivity activity, @NotNull CalculatorFragmentType fragmentType, @Nullable Bundle fragmentArgs, int parentViewId) {
final FragmentManager fm = activity.getSupportFragmentManager();
@Override
public void setFragment(@NotNull SherlockFragmentActivity activity, @NotNull CalculatorFragmentType fragmentType, @Nullable Bundle fragmentArgs, int parentViewId) {
final FragmentManager fm = activity.getSupportFragmentManager();
Fragment fragment = fm.findFragmentByTag(fragmentType.getFragmentTag());
if (fragment == null) {
fragment = Fragment.instantiate(activity, fragmentType.getFragmentClass().getName(), fragmentArgs);
final FragmentTransaction ft = fm.beginTransaction();
ft.add(parentViewId, fragment, fragmentType.getFragmentTag());
ft.commit();
} else {
if ( fragment.isDetached() ) {
final FragmentTransaction ft = fm.beginTransaction();
ft.attach(fragment);
ft.commit();
}
Fragment fragment = fm.findFragmentByTag(fragmentType.getFragmentTag());
if (fragment == null) {
fragment = Fragment.instantiate(activity, fragmentType.getFragmentClass().getName(), fragmentArgs);
final FragmentTransaction ft = fm.beginTransaction();
ft.add(parentViewId, fragment, fragmentType.getFragmentTag());
ft.commit();
} else {
if (fragment.isDetached()) {
final FragmentTransaction ft = fm.beginTransaction();
ft.attach(fragment);
ft.commit();
}
}
}
}
}
@Override
public void selectTab(@NotNull SherlockFragmentActivity activity, @NotNull CalculatorFragmentType fragmentType) {
final ActionBar actionBar = activity.getSupportActionBar();
for (int i = 0; i < actionBar.getTabCount(); i++) {
final ActionBar.Tab tab = actionBar.getTabAt(i);
if ( tab != null && CalculatorFragmentType.plotter.getFragmentTag().equals(tab.getTag()) ) {
actionBar.setSelectedNavigationItem(i);
break;
}
}
}
@Override
public void selectTab(@NotNull SherlockFragmentActivity activity, @NotNull CalculatorFragmentType fragmentType) {
final ActionBar actionBar = activity.getSupportActionBar();
for (int i = 0; i < actionBar.getTabCount(); i++) {
final ActionBar.Tab tab = actionBar.getTabAt(i);
if (tab != null && CalculatorFragmentType.plotter.getFragmentTag().equals(tab.getTag())) {
actionBar.setSelectedNavigationItem(i);
break;
}
}
}
@Override
public int getLayoutId() {
return layoutId;
}
@Override
public int getLayoutId() {
return layoutId;
}
@Override
@NotNull
public CalculatorPreferences.Gui.Theme getTheme() {
return theme;
}
@Override
@NotNull
public CalculatorPreferences.Gui.Theme getTheme() {
return theme;
}
@Override
@NotNull
public CalculatorPreferences.Gui.Layout getLayout() {
return layout;
}
@Override
@NotNull
public CalculatorPreferences.Gui.Layout getLayout() {
return layout;
}
@Override
public void onResume(@NotNull SherlockFragmentActivity activity) {
onResume((Activity) activity);
@Override
public void onResume(@NotNull SherlockFragmentActivity activity) {
onResume((Activity) activity);
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity);
selectedNavigationIndex = preferences.getInt(getSavedTabPreferenceName(activity), -1);
restoreSavedTab(activity);
}
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity);
selectedNavigationIndex = preferences.getInt(getSavedTabPreferenceName(activity), -1);
restoreSavedTab(activity);
}
private void addHelpInfo(@NotNull Activity activity, @NotNull View root) {
if ( CalculatorApplication.isMonkeyRunner(activity) ) {
if ( root instanceof ViewGroup) {
final TextView helperTextView = new TextView(activity);
private void addHelpInfo(@NotNull Activity activity, @NotNull View root) {
if (CalculatorApplication.isMonkeyRunner(activity)) {
if (root instanceof ViewGroup) {
final TextView helperTextView = new TextView(activity);
final DisplayMetrics dm = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
final DisplayMetrics dm = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
helperTextView.setTextSize(15);
helperTextView.setTextColor(Color.WHITE);
helperTextView.setTextSize(15);
helperTextView.setTextColor(Color.WHITE);
final Configuration c = activity.getResources().getConfiguration();
final Configuration c = activity.getResources().getConfiguration();
final StringBuilder helpText = new StringBuilder();
helpText.append("Size: ");
if (Views.isLayoutSizeAtLeast(Configuration.SCREENLAYOUT_SIZE_XLARGE, c)) {
helpText.append("xlarge");
} else if (Views.isLayoutSizeAtLeast(Configuration.SCREENLAYOUT_SIZE_LARGE, c)) {
helpText.append("large");
} else if (Views.isLayoutSizeAtLeast(Configuration.SCREENLAYOUT_SIZE_NORMAL, c)) {
helpText.append("normal");
} else if (Views.isLayoutSizeAtLeast(Configuration.SCREENLAYOUT_SIZE_SMALL, c)) {
helpText.append("small");
} else {
helpText.append("unknown");
}
final StringBuilder helpText = new StringBuilder();
helpText.append("Size: ");
if (Views.isLayoutSizeAtLeast(Configuration.SCREENLAYOUT_SIZE_XLARGE, c)) {
helpText.append("xlarge");
} else if (Views.isLayoutSizeAtLeast(Configuration.SCREENLAYOUT_SIZE_LARGE, c)) {
helpText.append("large");
} else if (Views.isLayoutSizeAtLeast(Configuration.SCREENLAYOUT_SIZE_NORMAL, c)) {
helpText.append("normal");
} else if (Views.isLayoutSizeAtLeast(Configuration.SCREENLAYOUT_SIZE_SMALL, c)) {
helpText.append("small");
} else {
helpText.append("unknown");
}
helpText.append(" (").append(dm.widthPixels).append("x").append(dm.heightPixels).append(")");
helpText.append(" (").append(dm.widthPixels).append("x").append(dm.heightPixels).append(")");
helpText.append(" Density: ");
switch(dm.densityDpi){
case DisplayMetrics.DENSITY_LOW:
helpText.append("ldpi");
break;
case DisplayMetrics.DENSITY_MEDIUM:
helpText.append("mdpi");
break;
case DisplayMetrics.DENSITY_HIGH:
helpText.append("hdpi");
break;
case DisplayMetrics.DENSITY_XHIGH:
helpText.append("xhdpi");
break;
case DisplayMetrics.DENSITY_TV:
helpText.append("tv");
break;
}
helpText.append(" Density: ");
switch (dm.densityDpi) {
case DisplayMetrics.DENSITY_LOW:
helpText.append("ldpi");
break;
case DisplayMetrics.DENSITY_MEDIUM:
helpText.append("mdpi");
break;
case DisplayMetrics.DENSITY_HIGH:
helpText.append("hdpi");
break;
case DisplayMetrics.DENSITY_XHIGH:
helpText.append("xhdpi");
break;
case DisplayMetrics.DENSITY_TV:
helpText.append("tv");
break;
}
helpText.append(" (").append(dm.densityDpi).append(")");
helpText.append(" (").append(dm.densityDpi).append(")");
helperTextView.setText(helpText);
helperTextView.setText(helpText);
((ViewGroup) root).addView(helperTextView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
}
}
}
((ViewGroup) root).addView(helperTextView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
}
}
}
}

View File

@@ -38,17 +38,17 @@ import java.util.List;
*/
public final class CalculatorActivityLauncher implements CalculatorEventListener {
public CalculatorActivityLauncher() {
}
public CalculatorActivityLauncher() {
}
public static void showHistory(@NotNull final Context context) {
showHistory(context, false);
}
public static void showHistory(@NotNull final Context context) {
showHistory(context, false);
}
public static void showHistory(@NotNull final Context context, boolean detached) {
final Intent intent = new Intent(context, CalculatorHistoryActivity.class);
Android.addIntentFlags(intent, detached, context);
context.startActivity(intent);
final Intent intent = new Intent(context, CalculatorHistoryActivity.class);
Android.addIntentFlags(intent, detached, context);
context.startActivity(intent);
}
public static void showHelp(@NotNull final Context context) {
@@ -56,220 +56,221 @@ public final class CalculatorActivityLauncher implements CalculatorEventListener
}
public static void showSettings(@NotNull final Context context) {
showSettings(context, false);
}
public static void showSettings(@NotNull final Context context, boolean detached) {
final Intent intent = new Intent(context, CalculatorPreferencesActivity.class);
Android.addIntentFlags(intent, detached, context);
context.startActivity(intent);
showSettings(context, false);
}
public static void showAbout(@NotNull final Context context) {
public static void showSettings(@NotNull final Context context, boolean detached) {
final Intent intent = new Intent(context, CalculatorPreferencesActivity.class);
Android.addIntentFlags(intent, detached, context);
context.startActivity(intent);
}
public static void showAbout(@NotNull final Context context) {
context.startActivity(new Intent(context, CalculatorAboutActivity.class));
}
public static void showFunctions(@NotNull final Context context) {
showFunctions(context, false);
}
showFunctions(context, false);
}
public static void showFunctions(@NotNull final Context context, boolean detached) {
final Intent intent = new Intent(context, CalculatorFunctionsActivity.class);
Android.addIntentFlags(intent, detached, context);
context.startActivity(intent);
final Intent intent = new Intent(context, CalculatorFunctionsActivity.class);
Android.addIntentFlags(intent, detached, context);
context.startActivity(intent);
}
public static void showOperators(@NotNull final Context context) {
showOperators(context, false);
}
showOperators(context, false);
}
public static void showOperators(@NotNull final Context context, boolean detached) {
final Intent intent = new Intent(context, CalculatorOperatorsActivity.class);
Android.addIntentFlags(intent, detached, context);
context.startActivity(intent);
final Intent intent = new Intent(context, CalculatorOperatorsActivity.class);
Android.addIntentFlags(intent, detached, context);
context.startActivity(intent);
}
public static void showVars(@NotNull final Context context) {
showVars(context, false);
}
public static void showVars(@NotNull final Context context, boolean detached) {
final Intent intent = new Intent(context, CalculatorVarsActivity.class);
Android.addIntentFlags(intent, detached, context);
context.startActivity(intent);
showVars(context, false);
}
public static void plotGraph(@NotNull final Context context){
public static void showVars(@NotNull final Context context, boolean detached) {
final Intent intent = new Intent(context, CalculatorVarsActivity.class);
Android.addIntentFlags(intent, detached, context);
context.startActivity(intent);
}
public static void plotGraph(@NotNull final Context context) {
final Intent intent = new Intent();
intent.setClass(context, CalculatorPlotActivity.class);
Android.addIntentFlags(intent, false, context);
Android.addIntentFlags(intent, false, context);
context.startActivity(intent);
}
public static void tryCreateVar(@NotNull final Context context) {
final CalculatorDisplay display = Locator.getInstance().getDisplay();
final CalculatorDisplayViewState viewState = display.getViewState();
if (viewState.isValid() ) {
final CalculatorDisplay display = Locator.getInstance().getDisplay();
final CalculatorDisplayViewState viewState = display.getViewState();
if (viewState.isValid()) {
final String varValue = viewState.getText();
if (!Strings.isEmpty(varValue)) {
if (CalculatorVarsFragment.isValidValue(varValue)) {
if (context instanceof SherlockFragmentActivity) {
VarEditDialogFragment.showDialog(VarEditDialogFragment.Input.newFromValue(varValue), ((SherlockFragmentActivity) context).getSupportFragmentManager());
} else {
final Intent intent = new Intent(context, CalculatorVarsActivity.class);
intent.putExtra(CalculatorVarsFragment.CREATE_VAR_EXTRA_STRING, varValue);
Android.addIntentFlags(intent, false, context);
context.startActivity(intent);
}
} else {
getNotifier().showMessage(R.string.c_value_is_not_a_number, MessageType.error);
if (context instanceof SherlockFragmentActivity) {
VarEditDialogFragment.showDialog(VarEditDialogFragment.Input.newFromValue(varValue), ((SherlockFragmentActivity) context).getSupportFragmentManager());
} else {
final Intent intent = new Intent(context, CalculatorVarsActivity.class);
intent.putExtra(CalculatorVarsFragment.CREATE_VAR_EXTRA_STRING, varValue);
Android.addIntentFlags(intent, false, context);
context.startActivity(intent);
}
} else {
getNotifier().showMessage(R.string.c_value_is_not_a_number, MessageType.error);
}
} else {
getNotifier().showMessage(R.string.empty_var_error, MessageType.error);
getNotifier().showMessage(R.string.empty_var_error, MessageType.error);
}
} else {
getNotifier().showMessage(R.string.not_valid_result, MessageType.error);
getNotifier().showMessage(R.string.not_valid_result, MessageType.error);
}
}
public static void tryCreateFunction(@NotNull final Context context) {
final CalculatorDisplay display = Locator.getInstance().getDisplay();
final CalculatorDisplayViewState viewState = display.getViewState();
public static void tryCreateFunction(@NotNull final Context context) {
final CalculatorDisplay display = Locator.getInstance().getDisplay();
final CalculatorDisplayViewState viewState = display.getViewState();
if (viewState.isValid() ) {
final String functionValue = viewState.getText();
if (!Strings.isEmpty(functionValue)) {
if (viewState.isValid()) {
final String functionValue = viewState.getText();
if (!Strings.isEmpty(functionValue)) {
FunctionEditDialogFragment.showDialog(FunctionEditDialogFragment.Input.newFromDisplay(viewState), context);
FunctionEditDialogFragment.showDialog(FunctionEditDialogFragment.Input.newFromDisplay(viewState), context);
} else {
getNotifier().showMessage(R.string.empty_function_error, MessageType.error);
}
} else {
getNotifier().showMessage(R.string.not_valid_result, MessageType.error);
}
}
} else {
getNotifier().showMessage(R.string.empty_function_error, MessageType.error);
}
} else {
getNotifier().showMessage(R.string.not_valid_result, MessageType.error);
}
}
@NotNull
private static CalculatorNotifier getNotifier() {
return Locator.getInstance().getNotifier();
}
@NotNull
private static CalculatorNotifier getNotifier() {
return Locator.getInstance().getNotifier();
}
public static void tryPlot() {
final CalculatorPlotter plotter = Locator.getInstance().getPlotter();
final CalculatorDisplay display = Locator.getInstance().getDisplay();
final CalculatorDisplayViewState viewState = display.getViewState();
public static void tryPlot() {
final CalculatorPlotter plotter = Locator.getInstance().getPlotter();
final CalculatorDisplay display = Locator.getInstance().getDisplay();
final CalculatorDisplayViewState viewState = display.getViewState();
if (viewState.isValid() ) {
final String functionValue = viewState.getText();
final Generic expression = viewState.getResult();
if (!Strings.isEmpty(functionValue) && expression != null) {
if ( plotter.isPlotPossibleFor(expression) ) {
plotter.plot(expression);
} else {
getNotifier().showMessage(R.string.cpp_plot_too_many_variables, MessageType.error);
}
} else {
getNotifier().showMessage(R.string.cpp_plot_empty_function_error, MessageType.error);
}
} else {
getNotifier().showMessage(R.string.not_valid_result, MessageType.error);
}
}
if (viewState.isValid()) {
final String functionValue = viewState.getText();
final Generic expression = viewState.getResult();
if (!Strings.isEmpty(functionValue) && expression != null) {
if (plotter.isPlotPossibleFor(expression)) {
plotter.plot(expression);
} else {
getNotifier().showMessage(R.string.cpp_plot_too_many_variables, MessageType.error);
}
} else {
getNotifier().showMessage(R.string.cpp_plot_empty_function_error, MessageType.error);
}
} else {
getNotifier().showMessage(R.string.not_valid_result, MessageType.error);
}
}
public static void openApp(@NotNull Context context) {
final Intent intent = new Intent(context, CalculatorActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(intent);
}
public static void openApp(@NotNull Context context) {
final Intent intent = new Intent(context, CalculatorActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(intent);
}
public static void likeButtonPressed(@NotNull final Context context) {
final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(CalculatorApplication.FACEBOOK_APP_URL));
Android.addIntentFlags(intent, false, context);
context.startActivity(intent);
}
public static void likeButtonPressed(@NotNull final Context context) {
final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(CalculatorApplication.FACEBOOK_APP_URL));
Android.addIntentFlags(intent, false, context);
context.startActivity(intent);
}
public static void showCalculationMessagesDialog(@NotNull Context context, @NotNull List<Message> messages) {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
public static void showCalculationMessagesDialog(@NotNull Context context, @NotNull List<Message> messages) {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
if ( CalculatorPreferences.Calculations.showCalculationMessagesDialog.getPreference(prefs) ) {
FixableMessagesDialog.showDialogForMessages(messages, context, true);
}
}
if (CalculatorPreferences.Calculations.showCalculationMessagesDialog.getPreference(prefs)) {
FixableMessagesDialog.showDialogForMessages(messages, context, true);
}
}
@Override
public void onCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
final Context context;
@Override
public void onCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
final Context context;
final Object source = calculatorEventData.getSource();
if ( source instanceof Context ) {
context = ((Context) source);
} else {
context = App.getApplication();
}
final Object source = calculatorEventData.getSource();
if (source instanceof Context) {
context = ((Context) source);
} else {
context = App.getApplication();
}
switch (calculatorEventType){
case show_create_matrix_dialog:
App.getUiThreadExecutor().execute(new Runnable() {
@Override
public void run() {
final Intent intent = new Intent(context, CalculatorMatrixActivity.class);
Android.addIntentFlags(intent, false, context);
context.startActivity(intent);
}
});
break;
case show_create_var_dialog:
App.getUiThreadExecutor().execute(new Runnable() {
@Override
public void run() {
CalculatorActivityLauncher.tryCreateVar(context);
}
});
break;
case show_create_function_dialog:
App.getUiThreadExecutor().execute(new Runnable() {
@Override
public void run() {
CalculatorActivityLauncher.tryCreateFunction(context);
}
});
break;
case show_evaluation_error:
final String errorMessage = (String) data;
if (errorMessage != null) {
App.getUiThreadExecutor().execute(new Runnable() {
@Override
public void run() {
showEvaluationError(context, errorMessage);
}
});
}
break;
case show_message_dialog:
final DialogData dialogData = (DialogData) data;
if (dialogData != null) {
App.getUiThreadExecutor().execute(new Runnable() {
@Override
public void run() {
CalculatorDialogActivity.showDialog(context, dialogData);
}
});
}
break;
switch (calculatorEventType) {
case show_create_matrix_dialog:
App.getUiThreadExecutor().execute(new Runnable() {
@Override
public void run() {
final Intent intent = new Intent(context, CalculatorMatrixActivity.class);
Android.addIntentFlags(intent, false, context);
context.startActivity(intent);
}
});
break;
case show_create_var_dialog:
App.getUiThreadExecutor().execute(new Runnable() {
@Override
public void run() {
CalculatorActivityLauncher.tryCreateVar(context);
}
});
break;
case show_create_function_dialog:
App.getUiThreadExecutor().execute(new Runnable() {
@Override
public void run() {
CalculatorActivityLauncher.tryCreateFunction(context);
}
});
break;
case show_evaluation_error:
final String errorMessage = (String) data;
if (errorMessage != null) {
App.getUiThreadExecutor().execute(new Runnable() {
@Override
public void run() {
showEvaluationError(context, errorMessage);
}
});
}
break;
case show_message_dialog:
final DialogData dialogData = (DialogData) data;
if (dialogData != null) {
App.getUiThreadExecutor().execute(new Runnable() {
@Override
public void run() {
CalculatorDialogActivity.showDialog(context, dialogData);
}
});
}
break;
}
}
}
}
public static void showEvaluationError(@NotNull Context context, @NotNull final String errorMessage) {
final LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
public static void showEvaluationError(@NotNull Context context, @NotNull final String errorMessage) {
final LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
final View errorMessageView = layoutInflater.inflate(R.layout.display_error_message, null);
((TextView) errorMessageView.findViewById(R.id.error_message_text_view)).setText(errorMessage);
final View errorMessageView = layoutInflater.inflate(R.layout.display_error_message, null);
((TextView) errorMessageView.findViewById(R.id.error_message_text_view)).setText(errorMessage);
final AlertDialog.Builder builder = new AlertDialog.Builder(context)
.setPositiveButton(R.string.c_cancel, null)
.setView(errorMessageView);
final AlertDialog.Builder builder = new AlertDialog.Builder(context)
.setPositiveButton(R.string.c_cancel, null)
.setView(errorMessageView);
builder.create().show();
}
builder.create().show();
}
}

View File

@@ -12,15 +12,15 @@ import org.jetbrains.annotations.Nullable;
*/
public class CalculatorActivityMobile extends CalculatorActivity {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
CalculatorPreferences.Gui.layout.putPreference(prefs, CalculatorPreferences.Gui.Layout.main_calculator_mobile);
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
CalculatorPreferences.Gui.layout.putPreference(prefs, CalculatorPreferences.Gui.Layout.main_calculator_mobile);
super.onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
if ( !CalculatorApplication.isMonkeyRunner(this) ) {
this.finish();
}
}
if (!CalculatorApplication.isMonkeyRunner(this)) {
this.finish();
}
}
}

View File

@@ -34,196 +34,197 @@ import java.util.List;
* Time: 1:21 PM
*/
/*@ReportsCrashes(formKey = "dEhDaW1nZU1qcFdsVUpiSnhON0c0ZHc6MQ",
mode = ReportingInteractionMode.TOAST)*/
mode = ReportingInteractionMode.TOAST)*/
@ReportsCrashes(formKey = "",
mailTo = "se.solovyev+programming+calculatorpp+crashes+1.5@gmail.com",
mode = ReportingInteractionMode.DIALOG,
resToastText = R.string.crashed,
resDialogTitle = R.string.crash_dialog_title,
resDialogText = R.string.crash_dialog_text)
mailTo = "se.solovyev+programming+calculatorpp+crashes+1.5@gmail.com",
mode = ReportingInteractionMode.DIALOG,
resToastText = R.string.crashed,
resDialogTitle = R.string.crash_dialog_title,
resDialogText = R.string.crash_dialog_text)
public class CalculatorApplication extends android.app.Application implements SharedPreferences.OnSharedPreferenceChangeListener, ServiceLocator {
/*
**********************************************************************
*
* CONSTANTS
*
**********************************************************************
*/
/*
**********************************************************************
*
* CONSTANTS
*
**********************************************************************
*/
private static final String TAG = "Calculator++ Application";
public static final String FACEBOOK_APP_URL = "http://www.facebook.com/calculatorpp";
private static final String TAG = "Calculator++ Application";
public static final String FACEBOOK_APP_URL = "http://www.facebook.com/calculatorpp";
public static final String AD_FREE_PRODUCT_ID = "ad_free";
public static final String AD_FREE_P_KEY = "org.solovyev.android.calculator_ad_free";
public static final String AD_FREE_PRODUCT_ID = "ad_free";
public static final String AD_FREE_P_KEY = "org.solovyev.android.calculator_ad_free";
public static final String ADMOB_USER_ID = "a14f02cf9c80cbc";
public static final String ADMOB_USER_ID = "a14f02cf9c80cbc";
@NotNull
private static CalculatorApplication instance;
@NotNull
private static CalculatorApplication instance;
/*
**********************************************************************
*
* FIELDS
*
**********************************************************************
*/
/*
**********************************************************************
*
* FIELDS
*
**********************************************************************
*/
@NotNull
private final List<CalculatorEventListener> listeners = new ArrayList<CalculatorEventListener>();
@NotNull
private final List<CalculatorEventListener> listeners = new ArrayList<CalculatorEventListener>();
@NotNull
protected final Handler uiHandler = new Handler();
@NotNull
protected final Handler uiHandler = new Handler();
/*
**********************************************************************
*
* CONSTRUCTORS
*
**********************************************************************
*/
/*
**********************************************************************
*
* CONSTRUCTORS
*
**********************************************************************
*/
public CalculatorApplication() {
instance = this;
}
public CalculatorApplication() {
instance = this;
}
/*
**********************************************************************
*
* METHODS
*
**********************************************************************
*/
/*
**********************************************************************
*
* METHODS
*
**********************************************************************
*/
@Override
public void onCreate() {
ACRA.init(this);
@Override
public void onCreate() {
ACRA.init(this);
App.init(this);
App.init(this);
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
CalculatorPreferences.setDefaultValues(preferences);
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
CalculatorPreferences.setDefaultValues(preferences);
preferences.registerOnSharedPreferenceChangeListener(this);
preferences.registerOnSharedPreferenceChangeListener(this);
setTheme(preferences);
setTheme(preferences);
super.onCreate();
super.onCreate();
final AndroidCalculator calculator = new AndroidCalculator(this);
final AndroidCalculator calculator = new AndroidCalculator(this);
Locator.getInstance().init(calculator,
new AndroidCalculatorEngine(this),
new AndroidCalculatorClipboard(this),
new AndroidCalculatorNotifier(this),
new AndroidCalculatorHistory(this, calculator),
new AndroidCalculatorLogger(),
new AndroidCalculatorPreferenceService(this),
new AndroidCalculatorKeyboard(this, new CalculatorKeyboardImpl(calculator)),
Locator.getInstance().init(calculator,
new AndroidCalculatorEngine(this),
new AndroidCalculatorClipboard(this),
new AndroidCalculatorNotifier(this),
new AndroidCalculatorHistory(this, calculator),
new AndroidCalculatorLogger(),
new AndroidCalculatorPreferenceService(this),
new AndroidCalculatorKeyboard(this, new CalculatorKeyboardImpl(calculator)),
new AndroidExternalListenersContainer(calculator),
new AndroidCalculatorPlotter(this, new CalculatorPlotterImpl(calculator)));
new AndroidCalculatorPlotter(this, new CalculatorPlotterImpl(calculator)));
listeners.add(new CalculatorActivityLauncher());
for (CalculatorEventListener listener : listeners) {
calculator.addCalculatorEventListener(listener);
}
listeners.add(new CalculatorActivityLauncher());
for (CalculatorEventListener listener : listeners) {
calculator.addCalculatorEventListener(listener);
}
Locator.getInstance().getCalculator().init();
Locator.getInstance().getCalculator().init();
BillingDB.init(CalculatorApplication.this);
BillingDB.init(CalculatorApplication.this);
AdsController.getInstance().init(ADMOB_USER_ID, AD_FREE_PRODUCT_ID, new BillingController.IConfiguration() {
AdsController.getInstance().init(ADMOB_USER_ID, AD_FREE_PRODUCT_ID, new BillingController.IConfiguration() {
@Override
public byte[] getObfuscationSalt() {
return new byte[]{81, -114, 32, -127, -32, -104, -40, -15, -47, 57, -13, -41, -33, 67, -114, 7, -11, 53, 126, 82};
}
@Override
public byte[] getObfuscationSalt() {
return new byte[]{81, -114, 32, -127, -32, -104, -40, -15, -47, 57, -13, -41, -33, 67, -114, 7, -11, 53, 126, 82};
}
@Override
public String getPublicKey() {
return CalculatorSecurity.getPK();
}
});
@Override
public String getPublicKey() {
return CalculatorSecurity.getPK();
}
});
BillingController.registerObserver(new DefaultBillingObserver(this, null));
BillingController.registerObserver(new DefaultBillingObserver(this, null));
// init billing controller
new Thread(new Runnable() {
@Override
public void run() {
BillingController.checkBillingSupported(CalculatorApplication.this);
AdsController.getInstance().isAdFree(CalculatorApplication.this);
// init billing controller
new Thread(new Runnable() {
@Override
public void run() {
BillingController.checkBillingSupported(CalculatorApplication.this);
AdsController.getInstance().isAdFree(CalculatorApplication.this);
try {
// prepare engine
Locator.getInstance().getEngine().getMathEngine0().evaluate("1+1");
Locator.getInstance().getEngine().getMathEngine0().evaluate("1*1");
} catch (Throwable e) {
Log.e(TAG, e.getMessage(), e);
}
try {
// prepare engine
Locator.getInstance().getEngine().getMathEngine0().evaluate("1+1");
Locator.getInstance().getEngine().getMathEngine0().evaluate("1*1");
} catch (Throwable e) {
Log.e(TAG, e.getMessage(), e);
}
}
}).start();
}
}).start();
Locator.getInstance().getLogger().debug(TAG, "Application started!");
Locator.getInstance().getNotifier().showDebugMessage(TAG, "Application started!");
}
Locator.getInstance().getLogger().debug(TAG, "Application started!");
Locator.getInstance().getNotifier().showDebugMessage(TAG, "Application started!");
}
private void setTheme(@NotNull SharedPreferences preferences) {
final CalculatorPreferences.Gui.Theme theme = CalculatorPreferences.Gui.getTheme(preferences);
setTheme(theme.getThemeId());
}
private void setTheme(@NotNull SharedPreferences preferences) {
final CalculatorPreferences.Gui.Theme theme = CalculatorPreferences.Gui.getTheme(preferences);
setTheme(theme.getThemeId());
}
@NotNull
public CalculatorActivityHelper createActivityHelper(int layoutResId, @NotNull String logTag) {
return new CalculatorActivityHelperImpl(layoutResId, logTag);
}
@NotNull
public CalculatorActivityHelper createActivityHelper(int layoutResId, @NotNull String logTag) {
return new CalculatorActivityHelperImpl(layoutResId, logTag);
}
@NotNull
public CalculatorFragmentHelper createFragmentHelper(int layoutId) {
return new CalculatorFragmentHelperImpl(layoutId);
}
@NotNull
public CalculatorFragmentHelper createFragmentHelper(int layoutId) {
return new CalculatorFragmentHelperImpl(layoutId);
}
@NotNull
public CalculatorFragmentHelper createFragmentHelper(int layoutId, int titleResId) {
return new CalculatorFragmentHelperImpl(layoutId, titleResId);
}
@NotNull
public CalculatorFragmentHelper createFragmentHelper(int layoutId, int titleResId, boolean listenersOnCreate) {
return new CalculatorFragmentHelperImpl(layoutId, titleResId, listenersOnCreate);
}
@NotNull
public CalculatorFragmentHelper createFragmentHelper(int layoutId, int titleResId) {
return new CalculatorFragmentHelperImpl(layoutId, titleResId);
}
@NotNull
public Handler getUiHandler() {
return uiHandler;
}
@NotNull
public CalculatorFragmentHelper createFragmentHelper(int layoutId, int titleResId, boolean listenersOnCreate) {
return new CalculatorFragmentHelperImpl(layoutId, titleResId, listenersOnCreate);
}
/*
**********************************************************************
*
* STATIC
*
**********************************************************************
*/
@NotNull
public Handler getUiHandler() {
return uiHandler;
}
@NotNull
public static CalculatorApplication getInstance() {
return instance;
}
/*
**********************************************************************
*
* STATIC
*
**********************************************************************
*/
public static boolean isMonkeyRunner(@NotNull Context context) {
// NOTE: this code is only for monkeyrunner
return context.checkCallingOrSelfPermission(android.Manifest.permission.DISABLE_KEYGUARD) == PackageManager.PERMISSION_GRANTED;
}
@NotNull
public static CalculatorApplication getInstance() {
return instance;
}
@Override
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (CalculatorPreferences.OnscreenCalculator.showAppIcon.getKey().equals(key)) {
boolean showAppIcon = CalculatorPreferences.OnscreenCalculator.showAppIcon.getPreference(prefs);
Android.toggleComponent(this, CalculatorOnscreenStartActivity.class, showAppIcon);
public static boolean isMonkeyRunner(@NotNull Context context) {
// NOTE: this code is only for monkeyrunner
return context.checkCallingOrSelfPermission(android.Manifest.permission.DISABLE_KEYGUARD) == PackageManager.PERMISSION_GRANTED;
}
@Override
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
if (CalculatorPreferences.OnscreenCalculator.showAppIcon.getKey().equals(key)) {
boolean showAppIcon = CalculatorPreferences.OnscreenCalculator.showAppIcon.getPreference(prefs);
Android.toggleComponent(this, CalculatorOnscreenStartActivity.class, showAppIcon);
Locator.getInstance().getNotifier().showMessage(R.string.cpp_this_change_may_require_reboot, MessageType.info);
}
}
}
}
}

View File

@@ -23,106 +23,106 @@ import org.solovyev.common.text.Strings;
*/
public class CalculatorDialogActivity extends SherlockFragmentActivity {
@NotNull
private static final String TAG = CalculatorDialogActivity.class.getSimpleName();
@NotNull
private static final String TAG = CalculatorDialogActivity.class.getSimpleName();
@NotNull
private static final String DIALOG_DATA_EXTRA = "dialog_data";
@NotNull
private static final String DIALOG_DATA_EXTRA = "dialog_data";
public static void showDialog(@NotNull Context context, @NotNull DialogData dialogData) {
final Intent intent = new Intent();
intent.setClass(context, CalculatorDialogActivity.class);
intent.putExtra(DIALOG_DATA_EXTRA, ParcelableDialogData.wrap(dialogData));
Android.addIntentFlags(intent, false, context);
context.startActivity(intent);
}
public static void showDialog(@NotNull Context context, @NotNull DialogData dialogData) {
final Intent intent = new Intent();
intent.setClass(context, CalculatorDialogActivity.class);
intent.putExtra(DIALOG_DATA_EXTRA, ParcelableDialogData.wrap(dialogData));
Android.addIntentFlags(intent, false, context);
context.startActivity(intent);
}
@Override
protected void onCreate(@Nullable Bundle in) {
super.onCreate(in);
@Override
protected void onCreate(@Nullable Bundle in) {
super.onCreate(in);
final DialogData dialogData = readDialogData(getIntent());
if ( dialogData == null ) {
Locator.getInstance().getLogger().error(TAG, "Dialog data is null!");
this.finish();
} else {
setContentView(R.layout.cpp_dialog);
final DialogData dialogData = readDialogData(getIntent());
if (dialogData == null) {
Locator.getInstance().getLogger().error(TAG, "Dialog data is null!");
this.finish();
} else {
setContentView(R.layout.cpp_dialog);
final String title = dialogData.getTitle();
if (!Strings.isEmpty(title)) {
setTitle(title);
}
final String title = dialogData.getTitle();
if (!Strings.isEmpty(title)) {
setTitle(title);
}
final Bundle args = new Bundle();
args.putParcelable(DIALOG_DATA_EXTRA, ParcelableDialogData.wrap(dialogData));
FragmentUtils.createFragment(this, CalculatorDialogFragment.class, R.id.dialog_layout, "dialog", args);
}
}
final Bundle args = new Bundle();
args.putParcelable(DIALOG_DATA_EXTRA, ParcelableDialogData.wrap(dialogData));
FragmentUtils.createFragment(this, CalculatorDialogFragment.class, R.id.dialog_layout, "dialog", args);
}
}
@Nullable
private static DialogData readDialogData(@Nullable Intent in) {
if ( in != null ) {
final Parcelable parcelable = in.getParcelableExtra(DIALOG_DATA_EXTRA);
if ( parcelable instanceof DialogData ) {
return (DialogData) parcelable;
}
}
@Nullable
private static DialogData readDialogData(@Nullable Intent in) {
if (in != null) {
final Parcelable parcelable = in.getParcelableExtra(DIALOG_DATA_EXTRA);
if (parcelable instanceof DialogData) {
return (DialogData) parcelable;
}
}
return null;
}
return null;
}
@Nullable
private static DialogData readDialogData(@Nullable Bundle in) {
if ( in != null ) {
final Parcelable parcelable = in.getParcelable(DIALOG_DATA_EXTRA);
if ( parcelable instanceof DialogData ) {
return (DialogData) parcelable;
}
}
@Nullable
private static DialogData readDialogData(@Nullable Bundle in) {
if (in != null) {
final Parcelable parcelable = in.getParcelable(DIALOG_DATA_EXTRA);
if (parcelable instanceof DialogData) {
return (DialogData) parcelable;
}
}
return null;
}
return null;
}
public static class CalculatorDialogFragment extends CalculatorFragment {
public static class CalculatorDialogFragment extends CalculatorFragment {
public CalculatorDialogFragment() {
super(CalculatorFragmentType.dialog);
}
public CalculatorDialogFragment() {
super(CalculatorFragmentType.dialog);
}
@Override
public void onViewCreated(@NotNull View root, Bundle savedInstanceState) {
super.onViewCreated(root, savedInstanceState);
@Override
public void onViewCreated(@NotNull View root, Bundle savedInstanceState) {
super.onViewCreated(root, savedInstanceState);
final DialogData dialogData = readDialogData(getArguments());
final DialogData dialogData = readDialogData(getArguments());
if (dialogData != null) {
final TextView messageTextView = (TextView) root.findViewById(R.id.cpp_dialog_message_textview);
messageTextView.setMovementMethod(ScrollingMovementMethod.getInstance());
messageTextView.setText(dialogData.getMessage());
if (dialogData != null) {
final TextView messageTextView = (TextView) root.findViewById(R.id.cpp_dialog_message_textview);
messageTextView.setMovementMethod(ScrollingMovementMethod.getInstance());
messageTextView.setText(dialogData.getMessage());
if ( dialogData.getMessageLevel() == MessageType.error || dialogData.getMessageLevel() == MessageType.warning ) {
final Button copyButton = (Button) root.findViewById(R.id.cpp_copy_button);
copyButton.setVisibility(View.VISIBLE);
copyButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Locator.getInstance().getClipboard().setText(dialogData.getMessage());
Locator.getInstance().getNotifier().showMessage(CalculatorMessage.newInfoMessage(CalculatorMessages.text_copied));
}
});
if (dialogData.getMessageLevel() == MessageType.error || dialogData.getMessageLevel() == MessageType.warning) {
final Button copyButton = (Button) root.findViewById(R.id.cpp_copy_button);
copyButton.setVisibility(View.VISIBLE);
copyButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Locator.getInstance().getClipboard().setText(dialogData.getMessage());
Locator.getInstance().getNotifier().showMessage(CalculatorMessage.newInfoMessage(CalculatorMessages.text_copied));
}
});
}
}
}
}
root.findViewById(R.id.cpp_ok_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getActivity().finish();
}
});
}
}
root.findViewById(R.id.cpp_ok_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getActivity().finish();
}
});
}
}
}

View File

@@ -16,61 +16,61 @@ import org.jetbrains.annotations.NotNull;
*/
public class CalculatorDisplayFragment extends SherlockFragment {
@NotNull
private CalculatorFragmentHelper fragmentHelper;
@NotNull
private CalculatorFragmentHelper fragmentHelper;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.getActivity());
final CalculatorPreferences.Gui.Layout layout = CalculatorPreferences.Gui.getLayout(prefs);
if (layout == CalculatorPreferences.Gui.Layout.main_calculator_mobile) {
fragmentHelper = CalculatorApplication.getInstance().createFragmentHelper(R.layout.cpp_app_display_mobile, R.string.result);
} else {
fragmentHelper = CalculatorApplication.getInstance().createFragmentHelper(R.layout.cpp_app_display, R.string.result);
}
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.getActivity());
final CalculatorPreferences.Gui.Layout layout = CalculatorPreferences.Gui.getLayout(prefs);
if (layout == CalculatorPreferences.Gui.Layout.main_calculator_mobile) {
fragmentHelper = CalculatorApplication.getInstance().createFragmentHelper(R.layout.cpp_app_display_mobile, R.string.result);
} else {
fragmentHelper = CalculatorApplication.getInstance().createFragmentHelper(R.layout.cpp_app_display, R.string.result);
}
fragmentHelper.onCreate(this);
}
fragmentHelper.onCreate(this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return fragmentHelper.onCreateView(this, inflater, container);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return fragmentHelper.onCreateView(this, inflater, container);
}
@Override
public void onViewCreated(View root, Bundle savedInstanceState) {
super.onViewCreated(root, savedInstanceState);
@Override
public void onViewCreated(View root, Bundle savedInstanceState) {
super.onViewCreated(root, savedInstanceState);
((AndroidCalculator) Locator.getInstance().getCalculator()).setDisplay(getActivity());
((AndroidCalculator) Locator.getInstance().getCalculator()).setDisplay(getActivity());
fragmentHelper.onViewCreated(this, root);
}
fragmentHelper.onViewCreated(this, root);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
@Override
public void onResume() {
super.onResume();
@Override
public void onResume() {
super.onResume();
fragmentHelper.onResume(this);
}
fragmentHelper.onResume(this);
}
@Override
public void onPause() {
fragmentHelper.onPause(this);
@Override
public void onPause() {
fragmentHelper.onPause(this);
super.onPause();
}
super.onPause();
}
@Override
public void onDestroy() {
fragmentHelper.onDestroy(this);
@Override
public void onDestroy() {
fragmentHelper.onDestroy(this);
super.onDestroy();
}
super.onDestroy();
}
}

View File

@@ -23,100 +23,100 @@ import org.solovyev.android.sherlock.menu.SherlockMenuHelper;
*/
public class CalculatorEditorFragment extends SherlockFragment {
@NotNull
private CalculatorFragmentHelper fragmentHelper;
@NotNull
private CalculatorFragmentHelper fragmentHelper;
@NotNull
private ActivityMenu<Menu, MenuItem> menu = ListActivityMenu.fromEnum(CalculatorMenu.class, SherlockMenuHelper.getInstance());
@NotNull
private ActivityMenu<Menu, MenuItem> menu = ListActivityMenu.fromEnum(CalculatorMenu.class, SherlockMenuHelper.getInstance());
public CalculatorEditorFragment() {
}
public CalculatorEditorFragment() {
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
fragmentHelper.onViewCreated(this, view);
fragmentHelper.onViewCreated(this, view);
((AndroidCalculator) Locator.getInstance().getCalculator()).setEditor(getActivity());
}
((AndroidCalculator) Locator.getInstance().getCalculator()).setEditor(getActivity());
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.getActivity());
final CalculatorPreferences.Gui.Layout layout = CalculatorPreferences.Gui.getLayout(prefs);
if (layout == CalculatorPreferences.Gui.Layout.main_calculator_mobile) {
fragmentHelper = CalculatorApplication.getInstance().createFragmentHelper(R.layout.cpp_app_editor_mobile, R.string.editor);
} else {
fragmentHelper = CalculatorApplication.getInstance().createFragmentHelper(R.layout.cpp_app_editor, R.string.editor);
}
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.getActivity());
final CalculatorPreferences.Gui.Layout layout = CalculatorPreferences.Gui.getLayout(prefs);
if (layout == CalculatorPreferences.Gui.Layout.main_calculator_mobile) {
fragmentHelper = CalculatorApplication.getInstance().createFragmentHelper(R.layout.cpp_app_editor_mobile, R.string.editor);
} else {
fragmentHelper = CalculatorApplication.getInstance().createFragmentHelper(R.layout.cpp_app_editor, R.string.editor);
}
fragmentHelper.onCreate(this);
setHasOptionsMenu(true);
}
fragmentHelper.onCreate(this);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return fragmentHelper.onCreateView(this, inflater, container);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return fragmentHelper.onCreateView(this, inflater, container);
}
@Override
public void onResume() {
super.onResume();
@Override
public void onResume() {
super.onResume();
this.fragmentHelper.onResume(this);
}
this.fragmentHelper.onResume(this);
}
@Override
public void onPause() {
this.fragmentHelper.onPause(this);
@Override
public void onPause() {
this.fragmentHelper.onPause(this);
super.onPause();
}
super.onPause();
}
@Override
public void onDestroyView() {
super.onDestroyView();
}
@Override
public void onDestroyView() {
super.onDestroyView();
}
@Override
public void onDestroy() {
fragmentHelper.onDestroy(this);
super.onDestroy();
}
@Override
public void onDestroy() {
fragmentHelper.onDestroy(this);
super.onDestroy();
}
@Override
public void onDetach() {
super.onDetach();
}
@Override
public void onDetach() {
super.onDetach();
}
/*
**********************************************************************
*
* MENU
*
**********************************************************************
*/
/*
**********************************************************************
*
* MENU
*
**********************************************************************
*/
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
this.menu.onCreateOptionsMenu(this.getActivity(), menu);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
this.menu.onCreateOptionsMenu(this.getActivity(), menu);
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
this.menu.onPrepareOptionsMenu(this.getActivity(), menu);
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
this.menu.onPrepareOptionsMenu(this.getActivity(), menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return this.menu.onOptionsItemSelected(this.getActivity(), item);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return this.menu.onOptionsItemSelected(this.getActivity(), item);
}
}

View File

@@ -15,76 +15,76 @@ import org.jetbrains.annotations.NotNull;
*/
public abstract class CalculatorFragment extends SherlockFragment {
@NotNull
private final CalculatorFragmentHelper fragmentHelper;
@NotNull
private final CalculatorFragmentHelper fragmentHelper;
protected CalculatorFragment(int layoutResId, int titleResId) {
fragmentHelper = CalculatorApplication.getInstance().createFragmentHelper(layoutResId, titleResId);
}
protected CalculatorFragment(int layoutResId, int titleResId) {
fragmentHelper = CalculatorApplication.getInstance().createFragmentHelper(layoutResId, titleResId);
}
protected CalculatorFragment(@NotNull CalculatorFragmentType fragmentType) {
fragmentHelper = CalculatorApplication.getInstance().createFragmentHelper(fragmentType.getDefaultLayoutId(), fragmentType.getDefaultTitleResId());
}
protected CalculatorFragment(@NotNull CalculatorFragmentType fragmentType) {
fragmentHelper = CalculatorApplication.getInstance().createFragmentHelper(fragmentType.getDefaultLayoutId(), fragmentType.getDefaultTitleResId());
}
protected CalculatorFragment(@NotNull CalculatorFragmentHelper fragmentHelper) {
this.fragmentHelper = fragmentHelper;
}
protected CalculatorFragment(@NotNull CalculatorFragmentHelper fragmentHelper) {
this.fragmentHelper = fragmentHelper;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fragmentHelper.onCreate(this);
}
fragmentHelper.onCreate(this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return fragmentHelper.onCreateView(this, inflater, container);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return fragmentHelper.onCreateView(this, inflater, container);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
fragmentHelper.onViewCreated(this, view);
}
fragmentHelper.onViewCreated(this, view);
}
@Override
public void onResume() {
super.onResume();
@Override
public void onResume() {
super.onResume();
this.fragmentHelper.onResume(this);
}
this.fragmentHelper.onResume(this);
}
@Override
public void onPause() {
this.fragmentHelper.onPause(this);
@Override
public void onPause() {
this.fragmentHelper.onPause(this);
super.onPause();
}
super.onPause();
}
@Override
public void onDestroyView() {
super.onDestroyView();
}
@Override
public void onDestroyView() {
super.onDestroyView();
}
@Override
public void onDestroy() {
fragmentHelper.onDestroy(this);
super.onDestroy();
}
@Override
public void onDestroy() {
fragmentHelper.onDestroy(this);
super.onDestroy();
}
@Override
public void onDetach() {
super.onDetach();
}
@Override
public void onDetach() {
super.onDetach();
}
public boolean isPaneFragment() {
return fragmentHelper.isPane(this);
}
public boolean isPaneFragment() {
return fragmentHelper.isPane(this);
}
}

View File

@@ -11,55 +11,55 @@ import org.jetbrains.annotations.NotNull;
*/
public abstract class CalculatorFragmentActivity extends SherlockFragmentActivity {
@NotNull
private final CalculatorActivityHelper activityHelper;
@NotNull
private final CalculatorActivityHelper activityHelper;
protected CalculatorFragmentActivity() {
this(R.layout.main_empty);
}
protected CalculatorFragmentActivity() {
this(R.layout.main_empty);
}
protected CalculatorFragmentActivity(int layoutResId) {
this.activityHelper = CalculatorApplication.getInstance().createActivityHelper(layoutResId, getClass().getSimpleName());
}
protected CalculatorFragmentActivity(int layoutResId) {
this.activityHelper = CalculatorApplication.getInstance().createActivityHelper(layoutResId, getClass().getSimpleName());
}
@NotNull
protected CalculatorActivityHelper getActivityHelper() {
return activityHelper;
}
@NotNull
protected CalculatorActivityHelper getActivityHelper() {
return activityHelper;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activityHelper.onCreate(this, savedInstanceState);
}
activityHelper.onCreate(this, savedInstanceState);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
activityHelper.onSaveInstanceState(this, outState);
}
activityHelper.onSaveInstanceState(this, outState);
}
@Override
protected void onResume() {
super.onResume();
@Override
protected void onResume() {
super.onResume();
activityHelper.onResume(this);
}
activityHelper.onResume(this);
}
@Override
protected void onPause() {
this.activityHelper.onPause(this);
@Override
protected void onPause() {
this.activityHelper.onPause(this);
super.onPause();
}
super.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
@Override
protected void onDestroy() {
super.onDestroy();
activityHelper.onDestroy(this);
}
activityHelper.onDestroy(this);
}
}

View File

@@ -14,20 +14,20 @@ import org.jetbrains.annotations.Nullable;
*/
public interface CalculatorFragmentHelper {
boolean isPane(@NotNull Fragment fragment);
boolean isPane(@NotNull Fragment fragment);
void setPaneTitle(@NotNull Fragment fragment, int titleResId);
void setPaneTitle(@NotNull Fragment fragment, int titleResId);
void onCreate(@NotNull Fragment fragment);
void onCreate(@NotNull Fragment fragment);
@NotNull
View onCreateView(@NotNull Fragment fragment, @NotNull LayoutInflater inflater, @Nullable ViewGroup container);
@NotNull
View onCreateView(@NotNull Fragment fragment, @NotNull LayoutInflater inflater, @Nullable ViewGroup container);
void onViewCreated(@NotNull Fragment fragment, @NotNull View root);
void onViewCreated(@NotNull Fragment fragment, @NotNull View root);
void onResume(@NotNull Fragment fragment);
void onResume(@NotNull Fragment fragment);
void onPause(@NotNull Fragment fragment);
void onPause(@NotNull Fragment fragment);
void onDestroy(@NotNull Fragment fragment);
void onDestroy(@NotNull Fragment fragment);
}

View File

@@ -17,115 +17,115 @@ import org.solovyev.android.ads.AdsController;
*/
public class CalculatorFragmentHelperImpl extends AbstractCalculatorHelper implements CalculatorFragmentHelper {
@Nullable
private AdView adView;
@Nullable
private AdView adView;
private int layoutId;
private int layoutId;
private int titleResId = -1;
private int titleResId = -1;
private boolean listenersOnCreate = true;
private boolean listenersOnCreate = true;
public CalculatorFragmentHelperImpl(int layoutId) {
this.layoutId = layoutId;
}
public CalculatorFragmentHelperImpl(int layoutId) {
this.layoutId = layoutId;
}
public CalculatorFragmentHelperImpl(int layoutId, int titleResId) {
this.layoutId = layoutId;
this.titleResId = titleResId;
}
public CalculatorFragmentHelperImpl(int layoutId, int titleResId) {
this.layoutId = layoutId;
this.titleResId = titleResId;
}
public CalculatorFragmentHelperImpl(int layoutId, int titleResId, boolean listenersOnCreate) {
this.layoutId = layoutId;
this.titleResId = titleResId;
this.listenersOnCreate = listenersOnCreate;
}
public CalculatorFragmentHelperImpl(int layoutId, int titleResId, boolean listenersOnCreate) {
this.layoutId = layoutId;
this.titleResId = titleResId;
this.listenersOnCreate = listenersOnCreate;
}
@Override
public boolean isPane(@NotNull Fragment fragment) {
return fragment.getActivity() instanceof CalculatorActivity;
}
@Override
public boolean isPane(@NotNull Fragment fragment) {
return fragment.getActivity() instanceof CalculatorActivity;
}
public void setPaneTitle(@NotNull Fragment fragment, int titleResId) {
final TextView fragmentTitle = (TextView) fragment.getView().findViewById(R.id.fragment_title);
if (fragmentTitle != null) {
if (!isPane(fragment)) {
fragmentTitle.setVisibility(View.GONE);
} else {
fragmentTitle.setText(fragment.getString(titleResId).toUpperCase());
}
}
}
public void setPaneTitle(@NotNull Fragment fragment, int titleResId) {
final TextView fragmentTitle = (TextView) fragment.getView().findViewById(R.id.fragment_title);
if (fragmentTitle != null) {
if (!isPane(fragment)) {
fragmentTitle.setVisibility(View.GONE);
} else {
fragmentTitle.setText(fragment.getString(titleResId).toUpperCase());
}
}
}
@Override
public void onCreate(@NotNull Fragment fragment) {
super.onCreate(fragment.getActivity());
@Override
public void onCreate(@NotNull Fragment fragment) {
super.onCreate(fragment.getActivity());
if (listenersOnCreate) {
if ( fragment instanceof CalculatorEventListener ) {
Locator.getInstance().getCalculator().addCalculatorEventListener((CalculatorEventListener) fragment);
}
}
}
if (listenersOnCreate) {
if (fragment instanceof CalculatorEventListener) {
Locator.getInstance().getCalculator().addCalculatorEventListener((CalculatorEventListener) fragment);
}
}
}
@Override
public void onResume(@NotNull Fragment fragment) {
if (!listenersOnCreate) {
if ( fragment instanceof CalculatorEventListener ) {
Locator.getInstance().getCalculator().addCalculatorEventListener((CalculatorEventListener) fragment);
}
}
}
@Override
public void onResume(@NotNull Fragment fragment) {
if (!listenersOnCreate) {
if (fragment instanceof CalculatorEventListener) {
Locator.getInstance().getCalculator().addCalculatorEventListener((CalculatorEventListener) fragment);
}
}
}
@Override
public void onPause(@NotNull Fragment fragment) {
if (!listenersOnCreate) {
if ( fragment instanceof CalculatorEventListener ) {
Locator.getInstance().getCalculator().removeCalculatorEventListener((CalculatorEventListener) fragment);
}
}
}
@Override
public void onPause(@NotNull Fragment fragment) {
if (!listenersOnCreate) {
if (fragment instanceof CalculatorEventListener) {
Locator.getInstance().getCalculator().removeCalculatorEventListener((CalculatorEventListener) fragment);
}
}
}
@Override
public void onViewCreated(@NotNull Fragment fragment, @NotNull View root) {
final ViewGroup adParentView = (ViewGroup) root.findViewById(R.id.ad_parent_view);
final ViewGroup mainFragmentLayout = (ViewGroup) root.findViewById(R.id.main_fragment_layout);
@Override
public void onViewCreated(@NotNull Fragment fragment, @NotNull View root) {
final ViewGroup adParentView = (ViewGroup) root.findViewById(R.id.ad_parent_view);
final ViewGroup mainFragmentLayout = (ViewGroup) root.findViewById(R.id.main_fragment_layout);
if (fragment instanceof CalculatorDisplayFragment || fragment instanceof CalculatorEditorFragment || fragment instanceof CalculatorKeyboardFragment) {
// no ads in those fragments
} else {
if (adParentView != null) {
adView = AdsController.getInstance().inflateAd(fragment.getActivity(), adParentView, R.id.ad_parent_view);
} else if ( mainFragmentLayout != null ) {
adView = AdsController.getInstance().inflateAd(fragment.getActivity(), mainFragmentLayout, R.id.main_fragment_layout);
}
}
if (fragment instanceof CalculatorDisplayFragment || fragment instanceof CalculatorEditorFragment || fragment instanceof CalculatorKeyboardFragment) {
// no ads in those fragments
} else {
if (adParentView != null) {
adView = AdsController.getInstance().inflateAd(fragment.getActivity(), adParentView, R.id.ad_parent_view);
} else if (mainFragmentLayout != null) {
adView = AdsController.getInstance().inflateAd(fragment.getActivity(), mainFragmentLayout, R.id.main_fragment_layout);
}
}
processButtons(fragment.getActivity(), root);
processButtons(fragment.getActivity(), root);
if (titleResId >= 0) {
this.setPaneTitle(fragment, titleResId);
}
}
if (titleResId >= 0) {
this.setPaneTitle(fragment, titleResId);
}
}
@Override
public void onDestroy(@NotNull Fragment fragment) {
super.onDestroy(fragment.getActivity());
@Override
public void onDestroy(@NotNull Fragment fragment) {
super.onDestroy(fragment.getActivity());
if (listenersOnCreate) {
if ( fragment instanceof CalculatorEventListener ) {
Locator.getInstance().getCalculator().removeCalculatorEventListener((CalculatorEventListener) fragment);
}
}
if (listenersOnCreate) {
if (fragment instanceof CalculatorEventListener) {
Locator.getInstance().getCalculator().removeCalculatorEventListener((CalculatorEventListener) fragment);
}
}
if (this.adView != null) {
this.adView.destroy();
}
}
if (this.adView != null) {
this.adView.destroy();
}
}
@NotNull
@Override
public View onCreateView(@NotNull Fragment fragment, @NotNull LayoutInflater inflater, @Nullable ViewGroup container) {
return inflater.inflate(layoutId, container, false);
}
@NotNull
@Override
public View onCreateView(@NotNull Fragment fragment, @NotNull LayoutInflater inflater, @Nullable ViewGroup container) {
return inflater.inflate(layoutId, container, false);
}
}

View File

@@ -13,7 +13,10 @@ import org.solovyev.android.calculator.math.edit.CalculatorFunctionsFragment;
import org.solovyev.android.calculator.math.edit.CalculatorOperatorsFragment;
import org.solovyev.android.calculator.math.edit.CalculatorVarsFragment;
import org.solovyev.android.calculator.matrix.CalculatorMatrixEditFragment;
import org.solovyev.android.calculator.plot.*;
import org.solovyev.android.calculator.plot.CalculatorPlotFragment;
import org.solovyev.android.calculator.plot.CalculatorPlotFunctionSettingsActivity;
import org.solovyev.android.calculator.plot.CalculatorPlotFunctionsActivity;
import org.solovyev.android.calculator.plot.CalculatorPlotRangeActivity;
/**
* User: Solovyev_S
@@ -22,67 +25,67 @@ import org.solovyev.android.calculator.plot.*;
*/
public enum CalculatorFragmentType {
editor(CalculatorEditorFragment.class, R.layout.cpp_app_editor, R.string.editor),
//display(CalculatorHistoryFragment.class, "history", R.layout.history_fragment, R.string.c_history),
//keyboard(CalculatorHistoryFragment.class, "history", R.layout.history_fragment, R.string.c_history),
history(CalculatorHistoryFragment.class, R.layout.history_fragment, R.string.c_history),
saved_history(CalculatorSavedHistoryFragment.class, R.layout.history_fragment, R.string.c_saved_history),
variables(CalculatorVarsFragment.class, R.layout.vars_fragment, R.string.c_vars),
functions(CalculatorFunctionsFragment.class, R.layout.math_entities_fragment, R.string.c_functions),
operators(CalculatorOperatorsFragment.class, R.layout.math_entities_fragment, R.string.c_operators),
plotter(CalculatorPlotFragment.class, R.layout.cpp_plot_fragment, R.string.c_graph),
editor(CalculatorEditorFragment.class, R.layout.cpp_app_editor, R.string.editor),
//display(CalculatorHistoryFragment.class, "history", R.layout.history_fragment, R.string.c_history),
//keyboard(CalculatorHistoryFragment.class, "history", R.layout.history_fragment, R.string.c_history),
history(CalculatorHistoryFragment.class, R.layout.history_fragment, R.string.c_history),
saved_history(CalculatorSavedHistoryFragment.class, R.layout.history_fragment, R.string.c_saved_history),
variables(CalculatorVarsFragment.class, R.layout.vars_fragment, R.string.c_vars),
functions(CalculatorFunctionsFragment.class, R.layout.math_entities_fragment, R.string.c_functions),
operators(CalculatorOperatorsFragment.class, R.layout.math_entities_fragment, R.string.c_operators),
plotter(CalculatorPlotFragment.class, R.layout.cpp_plot_fragment, R.string.c_graph),
plotter_functions(CalculatorPlotFunctionsActivity.CalculatorPlotFunctionsFragment.class, R.layout.cpp_plot_functions_fragment, R.string.cpp_plot_functions),
plotter_function_settings(CalculatorPlotFunctionSettingsActivity.CalculatorPlotFunctionSettingsFragment.class, R.layout.cpp_plot_function_settings_fragment, R.string.cpp_plot_function_settings),
plotter_range(CalculatorPlotRangeActivity.CalculatorPlotRangeFragment.class, R.layout.cpp_plot_range_fragment, R.string.cpp_plot_range),
purchase_dialog(CalculatorPlotRangeActivity.CalculatorPlotRangeFragment.class, R.layout.cpp_purchase_dialog_fragment, R.string.cpp_purchase_title),
purchase_dialog(CalculatorPlotRangeActivity.CalculatorPlotRangeFragment.class, R.layout.cpp_purchase_dialog_fragment, R.string.cpp_purchase_title),
dialog(CalculatorDialogActivity.CalculatorDialogFragment.class, R.layout.cpp_dialog_fragment, R.string.cpp_message),
dialog(CalculatorDialogActivity.CalculatorDialogFragment.class, R.layout.cpp_dialog_fragment, R.string.cpp_message),
about(CalculatorAboutFragment.class, R.layout.about_fragment, R.string.c_about),
faq(CalculatorHelpFaqFragment.class, R.layout.help_faq_fragment, R.string.c_faq),
hints(CalculatorHelpHintsFragment.class, R.layout.help_hints_fragment, R.string.c_hints),
screens(CalculatorHelpScreensFragment.class, R.layout.help_screens_fragment, R.string.c_screens),
about(CalculatorAboutFragment.class, R.layout.about_fragment, R.string.c_about),
faq(CalculatorHelpFaqFragment.class, R.layout.help_faq_fragment, R.string.c_faq),
hints(CalculatorHelpHintsFragment.class, R.layout.help_hints_fragment, R.string.c_hints),
screens(CalculatorHelpScreensFragment.class, R.layout.help_screens_fragment, R.string.c_screens),
// todo serso: strings
matrix_edit(CalculatorMatrixEditFragment.class, R.layout.matrix_edit_fragment, R.string.c_screens),
release_notes(CalculatorReleaseNotesFragment.class, R.layout.release_notes_fragment, R.string.c_release_notes);
// todo serso: strings
matrix_edit(CalculatorMatrixEditFragment.class, R.layout.matrix_edit_fragment, R.string.c_screens),
release_notes(CalculatorReleaseNotesFragment.class, R.layout.release_notes_fragment, R.string.c_release_notes);
@NotNull
private Class<? extends Fragment> fragmentClass;
@NotNull
private Class<? extends Fragment> fragmentClass;
private final int defaultLayoutId;
private final int defaultLayoutId;
private int defaultTitleResId;
private int defaultTitleResId;
private CalculatorFragmentType(@NotNull Class<? extends Fragment> fragmentClass,
int defaultLayoutId,
int defaultTitleResId) {
this.fragmentClass = fragmentClass;
this.defaultLayoutId = defaultLayoutId;
this.defaultTitleResId = defaultTitleResId;
}
private CalculatorFragmentType(@NotNull Class<? extends Fragment> fragmentClass,
int defaultLayoutId,
int defaultTitleResId) {
this.fragmentClass = fragmentClass;
this.defaultLayoutId = defaultLayoutId;
this.defaultTitleResId = defaultTitleResId;
}
@NotNull
public String getFragmentTag() {
return this.name();
}
@NotNull
public String getFragmentTag() {
return this.name();
}
public int getDefaultTitleResId() {
return defaultTitleResId;
}
public int getDefaultTitleResId() {
return defaultTitleResId;
}
@NotNull
public Class<? extends Fragment> getFragmentClass() {
return fragmentClass;
}
@NotNull
public Class<? extends Fragment> getFragmentClass() {
return fragmentClass;
}
public int getDefaultLayoutId() {
return defaultLayoutId;
}
public int getDefaultLayoutId() {
return defaultLayoutId;
}
@NotNull
public String createSubFragmentTag(@NotNull String subFragmentTag) {
return this.getFragmentTag() + "_" + subFragmentTag;
}
@NotNull
public String createSubFragmentTag(@NotNull String subFragmentTag) {
return this.getFragmentTag() + "_" + subFragmentTag;
}
}

View File

@@ -18,74 +18,74 @@ import org.solovyev.android.calculator.model.AndroidCalculatorEngine;
*/
public class CalculatorKeyboardFragment extends SherlockFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
@NotNull
private CalculatorPreferences.Gui.Theme theme;
@NotNull
private CalculatorPreferences.Gui.Theme theme;
@NotNull
private CalculatorFragmentHelper fragmentHelper;
@NotNull
private CalculatorFragmentHelper fragmentHelper;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this.getActivity());
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this.getActivity());
final CalculatorPreferences.Gui.Layout layout = CalculatorPreferences.Gui.getLayout(preferences);
if (layout == CalculatorPreferences.Gui.Layout.main_calculator_mobile) {
fragmentHelper = CalculatorApplication.getInstance().createFragmentHelper(R.layout.cpp_app_keyboard_mobile);
} else {
fragmentHelper = CalculatorApplication.getInstance().createFragmentHelper(R.layout.cpp_app_keyboard);
}
final CalculatorPreferences.Gui.Layout layout = CalculatorPreferences.Gui.getLayout(preferences);
if (layout == CalculatorPreferences.Gui.Layout.main_calculator_mobile) {
fragmentHelper = CalculatorApplication.getInstance().createFragmentHelper(R.layout.cpp_app_keyboard_mobile);
} else {
fragmentHelper = CalculatorApplication.getInstance().createFragmentHelper(R.layout.cpp_app_keyboard);
}
fragmentHelper.onCreate(this);
fragmentHelper.onCreate(this);
preferences.registerOnSharedPreferenceChangeListener(this);
preferences.registerOnSharedPreferenceChangeListener(this);
theme = CalculatorPreferences.Gui.theme.getPreferenceNoError(preferences);
theme = CalculatorPreferences.Gui.theme.getPreferenceNoError(preferences);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return fragmentHelper.onCreateView(this, inflater, container);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return fragmentHelper.onCreateView(this, inflater, container);
}
@Override
public void onViewCreated(View root, Bundle savedInstanceState) {
super.onViewCreated(root, savedInstanceState);
@Override
public void onViewCreated(View root, Bundle savedInstanceState) {
super.onViewCreated(root, savedInstanceState);
fragmentHelper.onViewCreated(this, root);
}
fragmentHelper.onViewCreated(this, root);
}
@Override
public void onResume() {
super.onResume();
@Override
public void onResume() {
super.onResume();
this.fragmentHelper.onResume(this);
}
this.fragmentHelper.onResume(this);
}
@Override
public void onPause() {
this.fragmentHelper.onPause(this);
@Override
public void onPause() {
this.fragmentHelper.onPause(this);
super.onPause();
}
super.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
@Override
public void onDestroy() {
super.onDestroy();
fragmentHelper.onDestroy(this);
fragmentHelper.onDestroy(this);
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this.getActivity());
preferences.unregisterOnSharedPreferenceChangeListener(this);
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this.getActivity());
preferences.unregisterOnSharedPreferenceChangeListener(this);
}
}
/* private static void setMarginsForView(@Nullable View view, int marginLeft, int marginBottom, @NotNull Context context) {
// IMPORTANT: this is workaround for probably android bug
// currently margin values set in styles are not applied for some reasons to the views (using include tag) => set them manually
/* private static void setMarginsForView(@Nullable View view, int marginLeft, int marginBottom, @NotNull Context context) {
// IMPORTANT: this is workaround for probably android bug
// currently margin values set in styles are not applied for some reasons to the views (using include tag) => set them manually
if (view != null) {
final DisplayMetrics dm = context.getResources().getDisplayMetrics();
@@ -98,50 +98,50 @@ public class CalculatorKeyboardFragment extends SherlockFragment implements Shar
}
}*/
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
@Override
public void onSharedPreferenceChanged(SharedPreferences preferences, String key) {
if (AndroidCalculatorEngine.Preferences.numeralBase.getKey().equals(key) ||
CalculatorPreferences.Gui.hideNumeralBaseDigits.getKey().equals(key) ) {
NumeralBaseButtons.toggleNumericDigits(this.getActivity(), preferences);
}
@Override
public void onSharedPreferenceChanged(SharedPreferences preferences, String key) {
if (AndroidCalculatorEngine.Preferences.numeralBase.getKey().equals(key) ||
CalculatorPreferences.Gui.hideNumeralBaseDigits.getKey().equals(key)) {
NumeralBaseButtons.toggleNumericDigits(this.getActivity(), preferences);
}
if ( AndroidCalculatorEngine.Preferences.angleUnit.getKey().equals(key) ||
AndroidCalculatorEngine.Preferences.numeralBase.getKey().equals(key) ) {
View view = getView();
if ( view != null) {
// we should update state of angle units/numeral base button => we can achieve it by invalidating the whole view
view.invalidate();
}
}
if (AndroidCalculatorEngine.Preferences.angleUnit.getKey().equals(key) ||
AndroidCalculatorEngine.Preferences.numeralBase.getKey().equals(key)) {
View view = getView();
if (view != null) {
// we should update state of angle units/numeral base button => we can achieve it by invalidating the whole view
view.invalidate();
}
}
if ( CalculatorPreferences.Gui.showEqualsButton.getKey().equals(key) ) {
CalculatorButtons.toggleEqualsButton(preferences, this.getActivity());
}
if (CalculatorPreferences.Gui.showEqualsButton.getKey().equals(key)) {
CalculatorButtons.toggleEqualsButton(preferences, this.getActivity());
}
if ( AndroidCalculatorEngine.Preferences.multiplicationSign.getKey().equals(key) ) {
CalculatorButtons.initMultiplicationButton(getView());
}
}
if (AndroidCalculatorEngine.Preferences.multiplicationSign.getKey().equals(key)) {
CalculatorButtons.initMultiplicationButton(getView());
}
}
@Nullable
private static AndroidCalculatorDisplayView getCalculatorDisplayView() {
return (AndroidCalculatorDisplayView) Locator.getInstance().getDisplay().getView();
}
@Nullable
private static AndroidCalculatorDisplayView getCalculatorDisplayView() {
return (AndroidCalculatorDisplayView) Locator.getInstance().getDisplay().getView();
}
@NotNull
private Calculator getCalculator() {
return Locator.getInstance().getCalculator();
}
@NotNull
private Calculator getCalculator() {
return Locator.getInstance().getCalculator();
}
@NotNull
private static CalculatorKeyboard getKeyboard() {
return Locator.getInstance().getKeyboard();
}
@NotNull
private static CalculatorKeyboard getKeyboard() {
return Locator.getInstance().getKeyboard();
}
}

View File

@@ -15,68 +15,68 @@ import org.solovyev.android.menu.LabeledMenuItem;
*/
enum CalculatorMenu implements LabeledMenuItem<MenuItem> {
settings(R.string.c_settings) {
@Override
public void onClick(@NotNull MenuItem data, @NotNull Context context) {
CalculatorActivityLauncher.showSettings(context);
}
},
settings(R.string.c_settings) {
@Override
public void onClick(@NotNull MenuItem data, @NotNull Context context) {
CalculatorActivityLauncher.showSettings(context);
}
},
history(R.string.c_history) {
@Override
public void onClick(@NotNull MenuItem data, @NotNull Context context) {
CalculatorActivityLauncher.showHistory(context);
}
},
history(R.string.c_history) {
@Override
public void onClick(@NotNull MenuItem data, @NotNull Context context) {
CalculatorActivityLauncher.showHistory(context);
}
},
plotter(R.string.cpp_plotter) {
@Override
public void onClick(@NotNull MenuItem data, @NotNull Context context) {
Locator.getInstance().getPlotter().plot();
}
},
plotter(R.string.cpp_plotter) {
@Override
public void onClick(@NotNull MenuItem data, @NotNull Context context) {
Locator.getInstance().getPlotter().plot();
}
},
conversion_tool(R.string.c_conversion_tool) {
@Override
public void onClick(@NotNull MenuItem data, @NotNull Context context) {
new NumeralBaseConverterDialog(null).show(context);
}
},
conversion_tool(R.string.c_conversion_tool) {
@Override
public void onClick(@NotNull MenuItem data, @NotNull Context context) {
new NumeralBaseConverterDialog(null).show(context);
}
},
exit(R.string.c_exit) {
@Override
public void onClick(@NotNull MenuItem data, @NotNull Context context) {
if (context instanceof Activity) {
((Activity) context).finish();
} else {
Log.e(CalculatorActivity.TAG, "Activity menu used with context");
}
}
},
exit(R.string.c_exit) {
@Override
public void onClick(@NotNull MenuItem data, @NotNull Context context) {
if (context instanceof Activity) {
((Activity) context).finish();
} else {
Log.e(CalculatorActivity.TAG, "Activity menu used with context");
}
}
},
help(R.string.c_help) {
@Override
public void onClick(@NotNull MenuItem data, @NotNull Context context) {
CalculatorActivityLauncher.showHelp(context);
}
},
help(R.string.c_help) {
@Override
public void onClick(@NotNull MenuItem data, @NotNull Context context) {
CalculatorActivityLauncher.showHelp(context);
}
},
about(R.string.c_about) {
@Override
public void onClick(@NotNull MenuItem data, @NotNull Context context) {
CalculatorActivityLauncher.showAbout(context);
}
};
about(R.string.c_about) {
@Override
public void onClick(@NotNull MenuItem data, @NotNull Context context) {
CalculatorActivityLauncher.showAbout(context);
}
};
private final int captionResId;
private final int captionResId;
private CalculatorMenu(int captionResId) {
this.captionResId = captionResId;
}
private CalculatorMenu(int captionResId) {
this.captionResId = captionResId;
}
@NotNull
@Override
public String getCaption(@NotNull Context context) {
return context.getString(captionResId);
}
@NotNull
@Override
public String getCaption(@NotNull Context context) {
return context.getString(captionResId);
}
}

View File

@@ -18,7 +18,7 @@ import org.solovyev.common.math.Point2d;
* Date: 9/16/11
* Time: 11:45 PM
*/
public class CursorDragProcessor implements SimpleOnDragListener.DragProcessor{
public class CursorDragProcessor implements SimpleOnDragListener.DragProcessor {
public CursorDragProcessor() {
}
@@ -33,7 +33,7 @@ public class CursorDragProcessor implements SimpleOnDragListener.DragProcessor{
Locator.getInstance().getEditor().setCursorOnStart();
result = true;
} else if ("▶▶".equals(text)) {
Locator.getInstance().getEditor().setCursorOnEnd();
Locator.getInstance().getEditor().setCursorOnEnd();
result = true;
}
}

View File

@@ -29,17 +29,17 @@ public class EqualsDragProcessor implements SimpleOnDragListener.DragProcessor {
boolean result = false;
if (dragButton instanceof DirectionDragButton) {
if (dragDirection == DragDirection.down) {
CalculatorActivityLauncher.tryPlot();
result = true;
} else {
final String text = ((DirectionDragButton) dragButton).getText(dragDirection);
if ("".equals(text)) {
Locator.getInstance().getCalculator().simplify();
result = true;
}
}
}
if (dragDirection == DragDirection.down) {
CalculatorActivityLauncher.tryPlot();
result = true;
} else {
final String text = ((DirectionDragButton) dragButton).getText(dragDirection);
if ("".equals(text)) {
Locator.getInstance().getCalculator().simplify();
result = true;
}
}
}
return result;
}

View File

@@ -13,23 +13,23 @@ import org.solovyev.android.calculator.model.AndroidCalculatorEngine;
*/
public class NumeralBaseButtons {
public static void toggleNumericDigits(@NotNull Activity activity, @NotNull NumeralBase currentNumeralBase) {
for (NumeralBase numeralBase : NumeralBase.values()) {
if ( currentNumeralBase != numeralBase ) {
AndroidNumeralBase.valueOf(numeralBase).toggleButtons(false, activity);
}
}
public static void toggleNumericDigits(@NotNull Activity activity, @NotNull NumeralBase currentNumeralBase) {
for (NumeralBase numeralBase : NumeralBase.values()) {
if (currentNumeralBase != numeralBase) {
AndroidNumeralBase.valueOf(numeralBase).toggleButtons(false, activity);
}
}
AndroidNumeralBase.valueOf(currentNumeralBase).toggleButtons(true, activity);
}
AndroidNumeralBase.valueOf(currentNumeralBase).toggleButtons(true, activity);
}
public static void toggleNumericDigits(@NotNull Activity activity, @NotNull SharedPreferences preferences) {
if (CalculatorPreferences.Gui.hideNumeralBaseDigits.getPreference(preferences)) {
final NumeralBase nb = AndroidCalculatorEngine.Preferences.numeralBase.getPreference(preferences);
toggleNumericDigits(activity, nb);
} else {
// set HEX to show all digits
AndroidNumeralBase.valueOf(NumeralBase.hex).toggleButtons(true, activity);
}
}
public static void toggleNumericDigits(@NotNull Activity activity, @NotNull SharedPreferences preferences) {
if (CalculatorPreferences.Gui.hideNumeralBaseDigits.getPreference(preferences)) {
final NumeralBase nb = AndroidCalculatorEngine.Preferences.numeralBase.getPreference(preferences);
toggleNumericDigits(activity, nb);
} else {
// set HEX to show all digits
AndroidNumeralBase.valueOf(NumeralBase.hex).toggleButtons(true, activity);
}
}
}

View File

@@ -18,11 +18,11 @@ import org.solovyev.android.calculator.R;
*/
public class CalculatorAboutActivity extends CalculatorFragmentActivity {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActivityHelper().addTab(this, CalculatorFragmentType.about, null, R.id.main_layout);
getActivityHelper().addTab(this, CalculatorFragmentType.release_notes, null, R.id.main_layout);
}
getActivityHelper().addTab(this, CalculatorFragmentType.about, null, R.id.main_layout);
getActivityHelper().addTab(this, CalculatorFragmentType.release_notes, null, R.id.main_layout);
}
}

View File

@@ -21,15 +21,15 @@ import org.solovyev.android.calculator.R;
*/
public class CalculatorAboutFragment extends CalculatorFragment {
public CalculatorAboutFragment() {
super(CalculatorFragmentType.about);
}
public CalculatorAboutFragment() {
super(CalculatorFragmentType.about);
}
@Override
public void onViewCreated(View root, Bundle savedInstanceState) {
super.onViewCreated(root, savedInstanceState);
@Override
public void onViewCreated(View root, Bundle savedInstanceState) {
super.onViewCreated(root, savedInstanceState);
final TextView about = (TextView) root.findViewById(R.id.aboutTextView);
about.setMovementMethod(LinkMovementMethod.getInstance());
}
final TextView about = (TextView) root.findViewById(R.id.aboutTextView);
about.setMovementMethod(LinkMovementMethod.getInstance());
}
}

View File

@@ -27,21 +27,21 @@ import org.solovyev.common.text.Strings;
*/
public class CalculatorReleaseNotesFragment extends CalculatorFragment {
public CalculatorReleaseNotesFragment() {
super(CalculatorFragmentType.release_notes);
}
public CalculatorReleaseNotesFragment() {
super(CalculatorFragmentType.release_notes);
}
@Override
public void onViewCreated(View root, Bundle savedInstanceState) {
super.onViewCreated(root, savedInstanceState);
@Override
public void onViewCreated(View root, Bundle savedInstanceState) {
super.onViewCreated(root, savedInstanceState);
final TextView releaseNotes = (TextView) root.findViewById(R.id.releaseNotesTextView);
releaseNotes.setMovementMethod(LinkMovementMethod.getInstance());
final TextView releaseNotes = (TextView) root.findViewById(R.id.releaseNotesTextView);
releaseNotes.setMovementMethod(LinkMovementMethod.getInstance());
releaseNotes.setText(Html.fromHtml(getReleaseNotes(this.getActivity())));
}
releaseNotes.setText(Html.fromHtml(getReleaseNotes(this.getActivity())));
}
@NotNull
@NotNull
public static String getReleaseNotes(@NotNull Context context) {
return getReleaseNotes(context, 0);
}
@@ -53,14 +53,14 @@ public class CalculatorReleaseNotesFragment extends CalculatorFragment {
final String releaseNotesForTitle = context.getString(R.string.c_release_notes_for_title);
final int version = Android.getAppVersionCode(context);
final TextHelper textHelper = new TextHelper(context.getResources(), CalculatorApplication.class.getPackage().getName());
final TextHelper textHelper = new TextHelper(context.getResources(), CalculatorApplication.class.getPackage().getName());
boolean first = true;
for ( int i = version; i >= minVersion; i-- ) {
for (int i = version; i >= minVersion; i--) {
String releaseNotesForVersion = textHelper.getText("c_release_notes_for_" + i);
if (!Strings.isEmpty(releaseNotesForVersion)){
if (!Strings.isEmpty(releaseNotesForVersion)) {
assert releaseNotesForVersion != null;
if ( !first ) {
if (!first) {
result.append("<br/><br/>");
} else {
first = false;

View File

@@ -1,8 +1,6 @@
package org.solovyev.android.calculator.about;
import android.content.Context;
import android.content.res.Resources;
import android.util.Log;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -13,25 +11,25 @@ import org.jetbrains.annotations.Nullable;
*/
public class TextHelper {
@NotNull
public String packageName;
@NotNull
public String packageName;
@NotNull
public Resources resources;
@NotNull
public Resources resources;
public TextHelper(@NotNull Resources resources, @NotNull String packageName) {
this.packageName = packageName;
this.resources = resources;
}
public TextHelper(@NotNull Resources resources, @NotNull String packageName) {
this.packageName = packageName;
this.resources = resources;
}
@Nullable
public String getText(@NotNull String stringName) {
final int stringId = this.resources.getIdentifier(stringName, "string", this.packageName);
try {
return resources.getString(stringId);
} catch (Resources.NotFoundException e) {
return null;
}
}
@Nullable
public String getText(@NotNull String stringName) {
final int stringId = this.resources.getIdentifier(stringName, "string", this.packageName);
try {
return resources.getString(stringId);
} catch (Resources.NotFoundException e) {
return null;
}
}
}

View File

@@ -40,35 +40,35 @@ public class FunctionEditDialogFragment extends DialogFragment implements Calcul
private static final String INPUT = "input";
@NotNull
private Input input;
private Input input;
public FunctionEditDialogFragment() {
this(Input.newInstance());
}
public FunctionEditDialogFragment() {
this(Input.newInstance());
}
public FunctionEditDialogFragment(@NotNull Input input) {
this.input = input;
}
public FunctionEditDialogFragment(@NotNull Input input) {
this.input = input;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View result = inflater.inflate(R.layout.function_edit, container, false);
if (savedInstanceState != null) {
final Parcelable input = savedInstanceState.getParcelable(INPUT);
if ( input instanceof Input ) {
this.input = (Input)input;
final Parcelable input = savedInstanceState.getParcelable(INPUT);
if (input instanceof Input) {
this.input = (Input) input;
}
}
return result;
}
}
@Override
public void onViewCreated(@NotNull View root, Bundle savedInstanceState) {
super.onViewCreated(root, savedInstanceState);
@Override
public void onViewCreated(@NotNull View root, Bundle savedInstanceState) {
super.onViewCreated(root, savedInstanceState);
final FunctionParamsView paramsView = (FunctionParamsView) root.findViewById(R.id.function_params_layout);
final FunctionParamsView paramsView = (FunctionParamsView) root.findViewById(R.id.function_params_layout);
final AFunction.Builder builder;
final AFunction function = input.getFunction();
@@ -76,25 +76,25 @@ public class FunctionEditDialogFragment extends DialogFragment implements Calcul
builder = new AFunction.Builder(function);
} else {
builder = new AFunction.Builder();
}
}
final List<String> parameterNames = input.getParameterNames();
if (parameterNames != null) {
paramsView.init(parameterNames);
} else {
paramsView.init();
}
final List<String> parameterNames = input.getParameterNames();
if (parameterNames != null) {
paramsView.init(parameterNames);
} else {
paramsView.init();
}
final EditText editName = (EditText) root.findViewById(R.id.function_edit_name);
// show soft keyboard automatically
editName.requestFocus();
editName.setText(input.getName());
final EditText editName = (EditText) root.findViewById(R.id.function_edit_name);
// show soft keyboard automatically
editName.requestFocus();
editName.setText(input.getName());
final EditText editDescription = (EditText) root.findViewById(R.id.function_edit_description);
editDescription.setText(input.getDescription());
final EditText editDescription = (EditText) root.findViewById(R.id.function_edit_description);
editDescription.setText(input.getDescription());
final EditText editContent = (EditText) root.findViewById(R.id.function_edit_value);
editContent.setText(input.getContent());
final EditText editContent = (EditText) root.findViewById(R.id.function_edit_value);
editContent.setText(input.getContent());
root.findViewById(R.id.cancel_button).setOnClickListener(new View.OnClickListener() {
@Override
@@ -105,7 +105,7 @@ public class FunctionEditDialogFragment extends DialogFragment implements Calcul
root.findViewById(R.id.save_button).setOnClickListener(new FunctionEditorSaver(builder, function, root, Locator.getInstance().getEngine().getFunctionsRegistry(), this));
if ( function == null ) {
if (function == null) {
// CREATE MODE
getDialog().setTitle(R.string.function_create_function);
@@ -127,57 +127,57 @@ public class FunctionEditDialogFragment extends DialogFragment implements Calcul
}
@Override
public void onResume() {
super.onResume();
public void onResume() {
super.onResume();
Locator.getInstance().getCalculator().addCalculatorEventListener(this);
}
Locator.getInstance().getCalculator().addCalculatorEventListener(this);
}
@Override
public void onPause() {
Locator.getInstance().getCalculator().removeCalculatorEventListener(this);
@Override
public void onPause() {
Locator.getInstance().getCalculator().removeCalculatorEventListener(this);
super.onPause();
}
super.onPause();
}
@Override
public void onCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
@Override
public void onCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
switch (calculatorEventType) {
case function_removed:
case function_added:
case function_changed:
if ( calculatorEventData.getSource() == FunctionEditDialogFragment.this ) {
if (calculatorEventData.getSource() == FunctionEditDialogFragment.this) {
dismiss();
}
break;
}
}
}
/*
**********************************************************************
*
* STATIC
*
**********************************************************************
*/
/*
**********************************************************************
*
* STATIC
*
**********************************************************************
*/
public static void showDialog(@NotNull Input input, @NotNull Context context) {
if (context instanceof SherlockFragmentActivity) {
FunctionEditDialogFragment.showDialog(input, ((SherlockFragmentActivity) context).getSupportFragmentManager());
} else {
final Intent intent = new Intent(context, CalculatorFunctionsActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(CalculatorFunctionsFragment.CREATE_FUNCTION_EXTRA, input);
context.startActivity(intent);
}
}
public static void showDialog(@NotNull Input input, @NotNull Context context) {
if (context instanceof SherlockFragmentActivity) {
FunctionEditDialogFragment.showDialog(input, ((SherlockFragmentActivity) context).getSupportFragmentManager());
} else {
final Intent intent = new Intent(context, CalculatorFunctionsActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(CalculatorFunctionsFragment.CREATE_FUNCTION_EXTRA, input);
context.startActivity(intent);
}
}
public static void showDialog(@NotNull Input input, @NotNull FragmentManager fm) {
AndroidSherlockUtils.showDialog(new FunctionEditDialogFragment(input), "function-editor", fm);
}
public static void showDialog(@NotNull Input input, @NotNull FragmentManager fm) {
AndroidSherlockUtils.showDialog(new FunctionEditDialogFragment(input), "function-editor", fm);
}
public static class Input implements Parcelable {
public static class Input implements Parcelable {
public static final Parcelable.Creator<Input> CREATOR = new Creator<Input>() {
@Override
@@ -220,78 +220,78 @@ public class FunctionEditDialogFragment extends DialogFragment implements Calcul
}
@Nullable
private AFunction function;
private AFunction function;
@Nullable
private String name;
@Nullable
private String name;
@Nullable
private String content;
@Nullable
private String content;
@Nullable
private String description;
@Nullable
private String description;
@Nullable
private List<String> parameterNames;
@Nullable
private List<String> parameterNames;
private Input() {
}
private Input() {
}
@NotNull
public static Input newInstance() {
return new Input();
}
@NotNull
public static Input newInstance() {
return new Input();
}
@NotNull
public static Input newFromFunction(@NotNull IFunction function) {
final Input result = new Input();
result.function = AFunction.fromIFunction(function);
return result;
}
@NotNull
public static Input newFromFunction(@NotNull IFunction function) {
final Input result = new Input();
result.function = AFunction.fromIFunction(function);
return result;
}
@NotNull
public static Input newInstance(@Nullable IFunction function,
@Nullable String name,
@Nullable String value,
@Nullable String description,
@NotNull
public static Input newInstance(@Nullable IFunction function,
@Nullable String name,
@Nullable String value,
@Nullable String description,
@NotNull List<String> parameterNames) {
final Input result = new Input();
final Input result = new Input();
if (function != null) {
result.function = AFunction.fromIFunction(function);
}
result.name = name;
result.content = value;
result.description = description;
result.parameterNames = new ArrayList<String>(parameterNames);
result.content = value;
result.description = description;
result.parameterNames = new ArrayList<String>(parameterNames);
return result;
}
return result;
}
@Nullable
public AFunction getFunction() {
return function;
}
@Nullable
public AFunction getFunction() {
return function;
}
@Nullable
public String getName() {
return name == null ? (function == null ? null : function.getName()) : name;
}
@Nullable
public String getName() {
return name == null ? (function == null ? null : function.getName()) : name;
}
@Nullable
public String getContent() {
return content == null ? (function == null ? null : function.getContent()) : content;
}
@Nullable
public String getContent() {
return content == null ? (function == null ? null : function.getContent()) : content;
}
@Nullable
public String getDescription() {
return description == null ? (function == null ? null : function.getDescription()) : description;
}
@Nullable
public String getDescription() {
return description == null ? (function == null ? null : function.getDescription()) : description;
}
@Nullable
public List<String> getParameterNames() {
return parameterNames == null ? (function == null ? null : function.getParameterNames()) : parameterNames;
}
@Nullable
public List<String> getParameterNames() {
return parameterNames == null ? (function == null ? null : function.getParameterNames()) : parameterNames;
}
@Override
public int describeContents() {
@@ -307,22 +307,22 @@ public class FunctionEditDialogFragment extends DialogFragment implements Calcul
out.writeSerializable(function);
}
@NotNull
public static Input newFromDisplay(@NotNull CalculatorDisplayViewState viewState) {
final Input result = new Input();
@NotNull
public static Input newFromDisplay(@NotNull CalculatorDisplayViewState viewState) {
final Input result = new Input();
result.content = viewState.getText();
final Generic generic = viewState.getResult();
if ( generic != null ) {
final Set<Constant> constants = CalculatorUtils.getNotSystemConstants(generic);
final List<String> parameterNames = new ArrayList<String>(constants.size());
for (Constant constant : constants) {
parameterNames.add(constant.getName());
}
result.parameterNames = parameterNames;
}
result.content = viewState.getText();
final Generic generic = viewState.getResult();
if (generic != null) {
final Set<Constant> constants = CalculatorUtils.getNotSystemConstants(generic);
final List<String> parameterNames = new ArrayList<String>(constants.size());
for (Constant constant : constants) {
parameterNames.add(constant.getName());
}
result.parameterNames = parameterNames;
}
return result;
}
}
return result;
}
}
}

View File

@@ -7,9 +7,9 @@ import jscl.math.function.Function;
import jscl.math.function.IFunction;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.Locator;
import org.solovyev.android.calculator.CalculatorFunctionsMathRegistry;
import org.solovyev.android.calculator.CalculatorMathRegistry;
import org.solovyev.android.calculator.Locator;
import org.solovyev.android.calculator.R;
import org.solovyev.android.calculator.math.edit.VarEditorSaver;
import org.solovyev.android.calculator.model.AFunction;
@@ -61,7 +61,7 @@ public class FunctionEditorSaver implements View.OnClickListener {
final String description = input.getDescription();
List<String> parameterNames = input.getParameterNames();
if ( parameterNames == null ) {
if (parameterNames == null) {
parameterNames = Collections.emptyList();
}
@@ -79,16 +79,16 @@ public class FunctionEditorSaver implements View.OnClickListener {
if (canBeSaved) {
if (validateParameters(parameterNames)) {
if (!Strings.isEmpty(content)) {
builder.setParameterNames(parameterNames);
builder.setName(name);
builder.setDescription(description);
builder.setValue(content);
error = null;
} else {
error = R.string.function_is_empty;
}
} else {
if (!Strings.isEmpty(content)) {
builder.setParameterNames(parameterNames);
builder.setName(name);
builder.setDescription(description);
builder.setValue(content);
error = null;
} else {
error = R.string.function_is_empty;
}
} else {
error = R.string.function_param_not_empty;
}
} else {
@@ -101,14 +101,14 @@ public class FunctionEditorSaver implements View.OnClickListener {
if (error != null) {
Locator.getInstance().getNotifier().showMessage(error, MessageType.error);
} else {
try {
CalculatorFunctionsMathRegistry.saveFunction(mathRegistry, new FunctionBuilderAdapter(builder), editedInstance, source, true);
} catch (CustomFunctionCalculationException e) {
Locator.getInstance().getNotifier().showMessage(e);
} catch (AFunction.Builder.CreationException e) {
try {
CalculatorFunctionsMathRegistry.saveFunction(mathRegistry, new FunctionBuilderAdapter(builder), editedInstance, source, true);
} catch (CustomFunctionCalculationException e) {
Locator.getInstance().getNotifier().showMessage(e);
} catch (AFunction.Builder.CreationException e) {
Locator.getInstance().getNotifier().showMessage(e);
}
}
}
}
@NotNull
@@ -130,7 +130,7 @@ public class FunctionEditorSaver implements View.OnClickListener {
private boolean validateParameters(@NotNull List<String> parameterNames) {
for (String parameterName : parameterNames) {
if ( !VarEditorSaver.isValidName(parameterName) ) {
if (!VarEditorSaver.isValidName(parameterName)) {
return false;
}
}

View File

@@ -76,10 +76,10 @@ public class FunctionParamsView extends LinearLayout {
editParamView.setTag(getParamTag(id));
final EditText paramNameEditText = (EditText) editParamView.findViewById(R.id.function_param_edit_text);
paramNameEditText.setText(name);
final EditText paramNameEditText = (EditText) editParamView.findViewById(R.id.function_param_edit_text);
paramNameEditText.setText(name);
final View removeParamButton = editParamView.findViewById(R.id.function_remove_param_button);
final View removeParamButton = editParamView.findViewById(R.id.function_remove_param_button);
removeParamButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
@@ -153,7 +153,7 @@ public class FunctionParamsView extends LinearLayout {
}
@NotNull
private String getParamTag(@NotNull Integer index) {
private String getParamTag(@NotNull Integer index) {
return PARAM_TAG_PREFIX + index;
}
@@ -176,7 +176,7 @@ public class FunctionParamsView extends LinearLayout {
for (Integer id : paramIds) {
final View paramView = getParamView(id);
if ( paramView != null ) {
if (paramView != null) {
final EditText paramNameEditText = (EditText) paramView.findViewById(R.id.function_param_edit_text);
result.add(paramNameEditText.getText().toString());
}

View File

@@ -19,12 +19,12 @@ import org.solovyev.android.calculator.R;
*/
public class CalculatorHelpActivity extends CalculatorFragmentActivity {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActivityHelper().addTab(this, CalculatorFragmentType.faq, null, R.id.main_layout);
getActivityHelper().addTab(this, CalculatorFragmentType.hints, null, R.id.main_layout);
getActivityHelper().addTab(this, CalculatorFragmentType.screens, null, R.id.main_layout);
}
getActivityHelper().addTab(this, CalculatorFragmentType.faq, null, R.id.main_layout);
getActivityHelper().addTab(this, CalculatorFragmentType.hints, null, R.id.main_layout);
getActivityHelper().addTab(this, CalculatorFragmentType.screens, null, R.id.main_layout);
}
}

View File

@@ -44,16 +44,16 @@ import java.util.List;
*/
public abstract class AbstractCalculatorHistoryFragment extends SherlockListFragment implements CalculatorEventListener {
/*
**********************************************************************
*
* CONSTANTS
*
**********************************************************************
*/
/*
**********************************************************************
*
* CONSTANTS
*
**********************************************************************
*/
@NotNull
private static final String TAG = "CalculatorHistoryFragment";
@NotNull
private static final String TAG = "CalculatorHistoryFragment";
public static final Comparator<CalculatorHistoryState> COMPARATOR = new Comparator<CalculatorHistoryState>() {
@Override
@@ -70,163 +70,163 @@ public abstract class AbstractCalculatorHistoryFragment extends SherlockListFrag
}
};
/*
**********************************************************************
*
* FIELDS
*
**********************************************************************
*/
/*
**********************************************************************
*
* FIELDS
*
**********************************************************************
*/
@NotNull
private ArrayAdapter<CalculatorHistoryState> adapter;
@NotNull
private CalculatorFragmentHelper fragmentHelper;
@NotNull
private CalculatorFragmentHelper fragmentHelper;
private ActivityMenu<Menu, MenuItem> menu = ListActivityMenu.fromResource(org.solovyev.android.calculator.R.menu.history_menu, HistoryMenu.class, SherlockMenuHelper.getInstance());
private ActivityMenu<Menu, MenuItem> menu = ListActivityMenu.fromResource(org.solovyev.android.calculator.R.menu.history_menu, HistoryMenu.class, SherlockMenuHelper.getInstance());
protected AbstractCalculatorHistoryFragment(@NotNull CalculatorFragmentType fragmentType) {
fragmentHelper = CalculatorApplication.getInstance().createFragmentHelper(fragmentType.getDefaultLayoutId(), fragmentType.getDefaultTitleResId(), false);
}
protected AbstractCalculatorHistoryFragment(@NotNull CalculatorFragmentType fragmentType) {
fragmentHelper = CalculatorApplication.getInstance().createFragmentHelper(fragmentType.getDefaultLayoutId(), fragmentType.getDefaultTitleResId(), false);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fragmentHelper.onCreate(this);
fragmentHelper.onCreate(this);
setHasOptionsMenu(true);
setHasOptionsMenu(true);
logDebug("onCreate");
}
logDebug("onCreate");
}
private int logDebug(@NotNull String msg) {
return Log.d(TAG + ": " + getTag(), msg);
}
private int logDebug(@NotNull String msg) {
return Log.d(TAG + ": " + getTag(), msg);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return fragmentHelper.onCreateView(this, inflater, container);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return fragmentHelper.onCreateView(this, inflater, container);
}
@Override
public void onViewCreated(View root, Bundle savedInstanceState) {
super.onViewCreated(root, savedInstanceState);
@Override
public void onViewCreated(View root, Bundle savedInstanceState) {
super.onViewCreated(root, savedInstanceState);
logDebug("onViewCreated");
logDebug("onViewCreated");
fragmentHelper.onViewCreated(this, root);
fragmentHelper.onViewCreated(this, root);
adapter = new HistoryArrayAdapter(this.getActivity(), getItemLayoutId(), org.solovyev.android.calculator.R.id.history_item, new ArrayList<CalculatorHistoryState>());
setListAdapter(adapter);
adapter = new HistoryArrayAdapter(this.getActivity(), getItemLayoutId(), org.solovyev.android.calculator.R.id.history_item, new ArrayList<CalculatorHistoryState>());
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(final AdapterView<?> parent,
final View view,
final int position,
final long id) {
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(final AdapterView<?> parent,
final View view,
final int position,
final long id) {
useHistoryItem((CalculatorHistoryState) parent.getItemAtPosition(position));
}
});
useHistoryItem((CalculatorHistoryState) parent.getItemAtPosition(position));
}
});
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
final CalculatorHistoryState historyState = (CalculatorHistoryState) parent.getItemAtPosition(position);
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
final CalculatorHistoryState historyState = (CalculatorHistoryState) parent.getItemAtPosition(position);
final FragmentActivity activity = getActivity();
final FragmentActivity activity = getActivity();
final HistoryItemMenuData data = new HistoryItemMenuData(historyState, adapter);
final HistoryItemMenuData data = new HistoryItemMenuData(historyState, adapter);
final List<HistoryItemMenuItem> menuItems = Collections.asList(HistoryItemMenuItem.values());
final List<HistoryItemMenuItem> menuItems = Collections.asList(HistoryItemMenuItem.values());
if (historyState.isSaved()) {
menuItems.remove(HistoryItemMenuItem.save);
} else {
if (isAlreadySaved(historyState)) {
menuItems.remove(HistoryItemMenuItem.save);
}
menuItems.remove(HistoryItemMenuItem.remove);
menuItems.remove(HistoryItemMenuItem.edit);
}
if (historyState.isSaved()) {
menuItems.remove(HistoryItemMenuItem.save);
} else {
if (isAlreadySaved(historyState)) {
menuItems.remove(HistoryItemMenuItem.save);
}
menuItems.remove(HistoryItemMenuItem.remove);
menuItems.remove(HistoryItemMenuItem.edit);
}
if (historyState.getDisplayState().isValid() && Strings.isEmpty(historyState.getDisplayState().getEditorState().getText())) {
menuItems.remove(HistoryItemMenuItem.copy_result);
}
if (historyState.getDisplayState().isValid() && Strings.isEmpty(historyState.getDisplayState().getEditorState().getText())) {
menuItems.remove(HistoryItemMenuItem.copy_result);
}
final ContextMenuBuilder<HistoryItemMenuItem, HistoryItemMenuData> menuBuilder = ContextMenuBuilder.newInstance(activity, "history-menu", ListContextMenu.newInstance(menuItems));
menuBuilder.build(data).show();
final ContextMenuBuilder<HistoryItemMenuItem, HistoryItemMenuData> menuBuilder = ContextMenuBuilder.newInstance(activity, "history-menu", ListContextMenu.newInstance(menuItems));
menuBuilder.build(data).show();
return true;
}
});
}
return true;
}
});
}
@Override
public void onResume() {
super.onResume();
@Override
public void onResume() {
super.onResume();
this.fragmentHelper.onResume(this);
this.fragmentHelper.onResume(this);
updateAdapter();
}
updateAdapter();
}
@Override
public void onPause() {
this.fragmentHelper.onPause(this);
@Override
public void onPause() {
this.fragmentHelper.onPause(this);
super.onPause();
}
super.onPause();
}
@Override
@Override
public void onDestroy() {
logDebug("onDestroy");
logDebug("onDestroy");
fragmentHelper.onDestroy(this);
fragmentHelper.onDestroy(this);
super.onDestroy();
super.onDestroy();
}
protected abstract int getItemLayoutId();
private void updateAdapter() {
final List<CalculatorHistoryState> historyList = getHistoryList();
private void updateAdapter() {
final List<CalculatorHistoryState> historyList = getHistoryList();
final ArrayAdapter<CalculatorHistoryState> adapter = getAdapter();
try {
adapter.setNotifyOnChange(false);
adapter.clear();
for (CalculatorHistoryState historyState : historyList) {
adapter.add(historyState);
}
} finally {
adapter.setNotifyOnChange(true);
}
final ArrayAdapter<CalculatorHistoryState> adapter = getAdapter();
try {
adapter.setNotifyOnChange(false);
adapter.clear();
for (CalculatorHistoryState historyState : historyList) {
adapter.add(historyState);
}
} finally {
adapter.setNotifyOnChange(true);
}
adapter.notifyDataSetChanged();
}
adapter.notifyDataSetChanged();
}
public static boolean isAlreadySaved(@NotNull CalculatorHistoryState historyState) {
public static boolean isAlreadySaved(@NotNull CalculatorHistoryState historyState) {
assert !historyState.isSaved();
boolean result = false;
try {
historyState.setSaved(true);
if ( Collections.contains(historyState, Locator.getInstance().getHistory().getSavedHistory(), new Equalizer<CalculatorHistoryState>() {
if (Collections.contains(historyState, Locator.getInstance().getHistory().getSavedHistory(), new Equalizer<CalculatorHistoryState>() {
@Override
public boolean areEqual(@Nullable CalculatorHistoryState first, @Nullable CalculatorHistoryState second) {
return first != null && second != null &&
first.getTime() == second.getTime() &&
first.getDisplayState().equals(second.getDisplayState()) &&
first.getEditorState().equals(second.getEditorState());
first.getDisplayState().equals(second.getDisplayState()) &&
first.getEditorState().equals(second.getEditorState());
}
}) ) {
})) {
result = true;
}
} finally {
@@ -236,7 +236,7 @@ public abstract class AbstractCalculatorHistoryFragment extends SherlockListFrag
}
public static void useHistoryItem(@NotNull final CalculatorHistoryState historyState) {
Locator.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.use_history_state, historyState);
Locator.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.use_history_state, historyState);
}
@NotNull
@@ -285,73 +285,73 @@ public abstract class AbstractCalculatorHistoryFragment extends SherlockListFrag
return adapter;
}
@Override
public void onCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
switch (calculatorEventType) {
case history_state_added:
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
logDebug("onCalculatorEvent");
updateAdapter();
}
});
break;
@Override
public void onCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
switch (calculatorEventType) {
case history_state_added:
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
logDebug("onCalculatorEvent");
updateAdapter();
}
});
break;
case clear_history_requested:
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
clearHistory();
}
});
break;
}
case clear_history_requested:
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
clearHistory();
}
});
break;
}
}
}
/*
**********************************************************************
*
* MENU
*
**********************************************************************
*/
/*
**********************************************************************
*
* MENU
*
**********************************************************************
*/
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
this.menu.onCreateOptionsMenu(this.getActivity(), menu);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
this.menu.onCreateOptionsMenu(this.getActivity(), menu);
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
this.menu.onPrepareOptionsMenu(this.getActivity(), menu);
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
this.menu.onPrepareOptionsMenu(this.getActivity(), menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return this.menu.onOptionsItemSelected(this.getActivity(), item);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return this.menu.onOptionsItemSelected(this.getActivity(), item);
}
private static enum HistoryMenu implements IdentifiableMenuItem<MenuItem> {
private static enum HistoryMenu implements IdentifiableMenuItem<MenuItem> {
clear_history(org.solovyev.android.calculator.R.id.history_menu_clear_history) {
@Override
public void onClick(@NotNull MenuItem data, @NotNull Context context) {
Locator.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.clear_history_requested, null);
}
};
clear_history(org.solovyev.android.calculator.R.id.history_menu_clear_history) {
@Override
public void onClick(@NotNull MenuItem data, @NotNull Context context) {
Locator.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.clear_history_requested, null);
}
};
private final int itemId;
private final int itemId;
HistoryMenu(int itemId) {
this.itemId = itemId;
}
HistoryMenu(int itemId) {
this.itemId = itemId;
}
@NotNull
@Override
public Integer getItemId() {
return this.itemId;
}
}
@NotNull
@Override
public Integer getItemId() {
return this.itemId;
}
}
}

View File

@@ -27,26 +27,26 @@ import java.util.List;
*/
public class AndroidCalculatorHistory implements CalculatorHistory {
@NotNull
private final CalculatorHistoryImpl calculatorHistory;
@NotNull
private final CalculatorHistoryImpl calculatorHistory;
@NotNull
private final Context context;
@NotNull
private final Context context;
public AndroidCalculatorHistory(@NotNull Application application, @NotNull Calculator calculator) {
this.context = application;
calculatorHistory = new CalculatorHistoryImpl(calculator);
}
public AndroidCalculatorHistory(@NotNull Application application, @NotNull Calculator calculator) {
this.context = application;
calculatorHistory = new CalculatorHistoryImpl(calculator);
}
@Override
@Override
public void load() {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
if (preferences != null) {
final String value = preferences.getString(context.getString(R.string.p_calc_history), null);
if (value != null) {
calculatorHistory.fromXml(value);
}
}
if (value != null) {
calculatorHistory.fromXml(value);
}
}
}
public void save() {
@@ -58,101 +58,101 @@ public class AndroidCalculatorHistory implements CalculatorHistory {
editor.commit();
}
public void clearSavedHistory() {
calculatorHistory.clearSavedHistory();
save();
}
public void clearSavedHistory() {
calculatorHistory.clearSavedHistory();
save();
}
public void removeSavedHistory(@NotNull CalculatorHistoryState historyState) {
historyState.setSaved(false);
calculatorHistory.removeSavedHistory(historyState);
save();
}
public void removeSavedHistory(@NotNull CalculatorHistoryState historyState) {
historyState.setSaved(false);
calculatorHistory.removeSavedHistory(historyState);
save();
}
@Override
public boolean isEmpty() {
return calculatorHistory.isEmpty();
}
@Override
public boolean isEmpty() {
return calculatorHistory.isEmpty();
}
@Override
public CalculatorHistoryState getLastHistoryState() {
return calculatorHistory.getLastHistoryState();
}
@Override
public CalculatorHistoryState getLastHistoryState() {
return calculatorHistory.getLastHistoryState();
}
@Override
public boolean isUndoAvailable() {
return calculatorHistory.isUndoAvailable();
}
@Override
public boolean isUndoAvailable() {
return calculatorHistory.isUndoAvailable();
}
@Override
public CalculatorHistoryState undo(@Nullable CalculatorHistoryState currentState) {
return calculatorHistory.undo(currentState);
}
@Override
public CalculatorHistoryState undo(@Nullable CalculatorHistoryState currentState) {
return calculatorHistory.undo(currentState);
}
@Override
public boolean isRedoAvailable() {
return calculatorHistory.isRedoAvailable();
}
@Override
public boolean isRedoAvailable() {
return calculatorHistory.isRedoAvailable();
}
@Override
public CalculatorHistoryState redo(@Nullable CalculatorHistoryState currentState) {
return calculatorHistory.redo(currentState);
}
@Override
public CalculatorHistoryState redo(@Nullable CalculatorHistoryState currentState) {
return calculatorHistory.redo(currentState);
}
@Override
public boolean isActionAvailable(@NotNull HistoryAction historyAction) {
return calculatorHistory.isActionAvailable(historyAction);
}
@Override
public boolean isActionAvailable(@NotNull HistoryAction historyAction) {
return calculatorHistory.isActionAvailable(historyAction);
}
@Override
public CalculatorHistoryState doAction(@NotNull HistoryAction historyAction, @Nullable CalculatorHistoryState currentState) {
return calculatorHistory.doAction(historyAction, currentState);
}
@Override
public CalculatorHistoryState doAction(@NotNull HistoryAction historyAction, @Nullable CalculatorHistoryState currentState) {
return calculatorHistory.doAction(historyAction, currentState);
}
@Override
public void addState(@Nullable CalculatorHistoryState currentState) {
calculatorHistory.addState(currentState);
}
@Override
public void addState(@Nullable CalculatorHistoryState currentState) {
calculatorHistory.addState(currentState);
}
@NotNull
@Override
public List<CalculatorHistoryState> getStates() {
return calculatorHistory.getStates();
}
@NotNull
@Override
public List<CalculatorHistoryState> getStates() {
return calculatorHistory.getStates();
}
@NotNull
@Override
public List<CalculatorHistoryState> getStates(boolean includeIntermediateStates) {
return calculatorHistory.getStates(includeIntermediateStates);
}
@NotNull
@Override
public List<CalculatorHistoryState> getStates(boolean includeIntermediateStates) {
return calculatorHistory.getStates(includeIntermediateStates);
}
@Override
public void clear() {
calculatorHistory.clear();
}
@Override
public void clear() {
calculatorHistory.clear();
}
@NotNull
public List<CalculatorHistoryState> getSavedHistory() {
return calculatorHistory.getSavedHistory();
}
@NotNull
public List<CalculatorHistoryState> getSavedHistory() {
return calculatorHistory.getSavedHistory();
}
@NotNull
public CalculatorHistoryState addSavedState(@NotNull CalculatorHistoryState historyState) {
return calculatorHistory.addSavedState(historyState);
}
@NotNull
public CalculatorHistoryState addSavedState(@NotNull CalculatorHistoryState historyState) {
return calculatorHistory.addSavedState(historyState);
}
@Override
public void fromXml(@NotNull String xml) {
calculatorHistory.fromXml(xml);
}
@Override
public void fromXml(@NotNull String xml) {
calculatorHistory.fromXml(xml);
}
@Override
public String toXml() {
return calculatorHistory.toXml();
}
@Override
public String toXml() {
return calculatorHistory.toXml();
}
@Override
public void onCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
calculatorHistory.onCalculatorEvent(calculatorEventData, calculatorEventType, data);
}
@Override
public void onCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
calculatorHistory.onCalculatorEvent(calculatorEventData, calculatorEventType, data);
}
}

View File

@@ -11,7 +11,6 @@ import com.actionbarsherlock.app.SherlockFragmentActivity;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.*;
import org.solovyev.android.calculator.CalculatorFragmentType;
/**
* User: serso
@@ -20,52 +19,52 @@ import org.solovyev.android.calculator.CalculatorFragmentType;
*/
public class CalculatorHistoryActivity extends SherlockFragmentActivity implements CalculatorEventListener {
@NotNull
private final CalculatorActivityHelper activityHelper = CalculatorApplication.getInstance().createActivityHelper(R.layout.main_empty, CalculatorHistoryActivity.class.getSimpleName());
@NotNull
private final CalculatorActivityHelper activityHelper = CalculatorApplication.getInstance().createActivityHelper(R.layout.main_empty, CalculatorHistoryActivity.class.getSimpleName());
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activityHelper.onCreate(this, savedInstanceState);
activityHelper.onCreate(this, savedInstanceState);
activityHelper.addTab(this, CalculatorFragmentType.history, null, R.id.main_layout);
activityHelper.addTab(this, CalculatorFragmentType.saved_history, null, R.id.main_layout);
}
activityHelper.addTab(this, CalculatorFragmentType.history, null, R.id.main_layout);
activityHelper.addTab(this, CalculatorFragmentType.saved_history, null, R.id.main_layout);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
activityHelper.onSaveInstanceState(this, outState);
}
activityHelper.onSaveInstanceState(this, outState);
}
@Override
protected void onResume() {
super.onResume();
@Override
protected void onResume() {
super.onResume();
activityHelper.onResume(this);
}
activityHelper.onResume(this);
}
@Override
protected void onPause() {
this.activityHelper.onPause(this);
@Override
protected void onPause() {
this.activityHelper.onPause(this);
super.onPause();
}
super.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
@Override
protected void onDestroy() {
super.onDestroy();
activityHelper.onDestroy(this);
}
activityHelper.onDestroy(this);
}
@Override
public void onCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
if ( calculatorEventType == CalculatorEventType.use_history_state ) {
this.finish();
}
}
@Override
public void onCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
if (calculatorEventType == CalculatorEventType.use_history_state) {
this.finish();
}
}
}

View File

@@ -8,10 +8,10 @@ package org.solovyev.android.calculator.history;
import android.preference.PreferenceManager;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.Locator;
import org.solovyev.android.calculator.CalculatorPreferences;
import org.solovyev.android.calculator.R;
import org.solovyev.android.calculator.CalculatorFragmentType;
import org.solovyev.android.calculator.CalculatorPreferences;
import org.solovyev.android.calculator.Locator;
import org.solovyev.android.calculator.R;
import java.util.ArrayList;
import java.util.List;
@@ -23,11 +23,11 @@ import java.util.List;
*/
public class CalculatorHistoryFragment extends AbstractCalculatorHistoryFragment {
public CalculatorHistoryFragment() {
super(CalculatorFragmentType.history);
}
public CalculatorHistoryFragment() {
super(CalculatorFragmentType.history);
}
@Override
@Override
protected int getItemLayoutId() {
return R.layout.history_item;
}
@@ -35,13 +35,13 @@ public class CalculatorHistoryFragment extends AbstractCalculatorHistoryFragment
@NotNull
@Override
protected List<CalculatorHistoryState> getHistoryItems() {
final boolean showIntermediateCalculations = CalculatorPreferences.History.showIntermediateCalculations.getPreference(PreferenceManager.getDefaultSharedPreferences(getActivity()));
final boolean showIntermediateCalculations = CalculatorPreferences.History.showIntermediateCalculations.getPreference(PreferenceManager.getDefaultSharedPreferences(getActivity()));
return new ArrayList<CalculatorHistoryState>(Locator.getInstance().getHistory().getStates(showIntermediateCalculations));
}
@Override
protected void clearHistory() {
Locator.getInstance().getHistory().clear();
Locator.getInstance().getHistory().clear();
getAdapter().clear();
}
}

View File

@@ -21,11 +21,11 @@ import java.util.List;
*/
public class CalculatorSavedHistoryFragment extends AbstractCalculatorHistoryFragment {
public CalculatorSavedHistoryFragment() {
super(CalculatorFragmentType.saved_history);
}
public CalculatorSavedHistoryFragment() {
super(CalculatorFragmentType.saved_history);
}
@Override
@Override
protected int getItemLayoutId() {
return R.layout.saved_history_item;
}
@@ -38,7 +38,7 @@ public class CalculatorSavedHistoryFragment extends AbstractCalculatorHistoryFra
@Override
protected void clearHistory() {
Locator.getInstance().getHistory().clearSavedHistory();
Locator.getInstance().getHistory().clearSavedHistory();
getAdapter().clear();
}
}

View File

@@ -20,10 +20,10 @@ import java.util.Date;
import java.util.List;
/**
* User: serso
* Date: 12/18/11
* Time: 7:39 PM
*/
* User: serso
* Date: 12/18/11
* Time: 7:39 PM
*/
public class HistoryArrayAdapter extends ArrayAdapter<CalculatorHistoryState> {
HistoryArrayAdapter(Context context, int resource, int textViewResourceId, @NotNull List<CalculatorHistoryState> historyList) {
@@ -57,7 +57,7 @@ public class HistoryArrayAdapter extends ArrayAdapter<CalculatorHistoryState> {
if (state.isSaved()) {
status.setText(getContext().getString(R.string.c_history_item_saved));
} else {
if ( AbstractCalculatorHistoryFragment.isAlreadySaved(state) ) {
if (AbstractCalculatorHistoryFragment.isAlreadySaved(state)) {
status.setText(getContext().getString(R.string.c_history_item_already_saved));
} else {
status.setText(getContext().getString(R.string.c_history_item_not_saved));

View File

@@ -10,10 +10,10 @@ import android.widget.ArrayAdapter;
import org.jetbrains.annotations.NotNull;
/**
* User: serso
* Date: 12/18/11
* Time: 3:10 PM
*/
* User: serso
* Date: 12/18/11
* Time: 3:10 PM
*/
public class HistoryItemMenuData {
@NotNull

View File

@@ -23,10 +23,10 @@ import org.solovyev.android.menu.LabeledMenuItem;
import org.solovyev.common.text.Strings;
/**
* User: serso
* Date: 12/18/11
* Time: 3:09 PM
*/
* User: serso
* Date: 12/18/11
* Time: 3:09 PM
*/
public enum HistoryItemMenuItem implements LabeledMenuItem<HistoryItemMenuData> {
use(R.string.c_use) {
@@ -104,10 +104,10 @@ public enum HistoryItemMenuItem implements LabeledMenuItem<HistoryItemMenuData>
final LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View editView = layoutInflater.inflate(R.layout.history_edit, null);
final TextView historyExpression = (TextView)editView.findViewById(R.id.history_edit_expression);
final TextView historyExpression = (TextView) editView.findViewById(R.id.history_edit_expression);
historyExpression.setText(AbstractCalculatorHistoryFragment.getHistoryText(historyState));
final EditText comment = (EditText)editView.findViewById(R.id.history_edit_comment);
final EditText comment = (EditText) editView.findViewById(R.id.history_edit_comment);
comment.setText(historyState.getComment());
final AlertDialog.Builder builder = new AlertDialog.Builder(context)
@@ -120,12 +120,12 @@ public enum HistoryItemMenuItem implements LabeledMenuItem<HistoryItemMenuData>
if (save) {
final CalculatorHistoryState savedHistoryItem = Locator.getInstance().getHistory().addSavedState(historyState);
savedHistoryItem.setComment(comment.getText().toString());
Locator.getInstance().getHistory().save();
Locator.getInstance().getHistory().save();
// we don't need to add element to the adapter as adapter of another activity must be updated and not this
//data.getAdapter().add(savedHistoryItem);
} else {
historyState.setComment(comment.getText().toString());
Locator.getInstance().getHistory().save();
Locator.getInstance().getHistory().save();
}
data.getAdapter().notifyDataSetChanged();
Toast.makeText(context, context.getText(R.string.c_history_saved), Toast.LENGTH_LONG).show();

View File

@@ -43,7 +43,7 @@ public class TextViewEditorAdapter implements Editor {
@Override
public void setSelection(int selection) {
if ( textView instanceof EditText ) {
if (textView instanceof EditText) {
((EditText) textView).setSelection(selection);
}
}

View File

@@ -19,7 +19,6 @@ import com.actionbarsherlock.app.SherlockListFragment;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.*;
import org.solovyev.android.calculator.CalculatorFragmentType;
import org.solovyev.android.menu.AMenuItem;
import org.solovyev.android.menu.ContextMenuBuilder;
import org.solovyev.android.menu.LabeledMenuItem;
@@ -41,258 +40,258 @@ import java.util.List;
*/
public abstract class AbstractMathEntityListFragment<T extends MathEntity> extends SherlockListFragment implements CalculatorEventListener {
/*
**********************************************************************
*
* CONSTANTS
*
**********************************************************************
*/
/*
**********************************************************************
*
* CONSTANTS
*
**********************************************************************
*/
public static final String MATH_ENTITY_CATEGORY_EXTRA_STRING = "org.solovyev.android.calculator.CalculatorVarsActivity_math_entity_category";
public static final String MATH_ENTITY_CATEGORY_EXTRA_STRING = "org.solovyev.android.calculator.CalculatorVarsActivity_math_entity_category";
protected final static List<Character> acceptableChars = Arrays.asList(Strings.toObjects("1234567890abcdefghijklmnopqrstuvwxyzйцукенгшщзхъфывапролджэячсмитьбюё_".toCharArray()));
protected final static List<Character> acceptableChars = Arrays.asList(Strings.toObjects("1234567890abcdefghijklmnopqrstuvwxyzйцукенгшщзхъфывапролджэячсмитьбюё_".toCharArray()));
/*
**********************************************************************
*
* FIELDS
*
**********************************************************************
*/
/*
**********************************************************************
*
* FIELDS
*
**********************************************************************
*/
@Nullable
private MathEntityArrayAdapter<T> adapter;
@Nullable
private MathEntityArrayAdapter<T> adapter;
@Nullable
private String category;
@Nullable
private String category;
@NotNull
private final CalculatorFragmentHelper fragmentHelper;
@NotNull
private final CalculatorFragmentHelper fragmentHelper;
@NotNull
private final Handler uiHandler = new Handler();
@NotNull
private final Handler uiHandler = new Handler();
protected AbstractMathEntityListFragment(@NotNull CalculatorFragmentType fragmentType) {
fragmentHelper = CalculatorApplication.getInstance().createFragmentHelper(fragmentType.getDefaultLayoutId(),fragmentType.getDefaultTitleResId());
}
protected AbstractMathEntityListFragment(@NotNull CalculatorFragmentType fragmentType) {
fragmentHelper = CalculatorApplication.getInstance().createFragmentHelper(fragmentType.getDefaultLayoutId(), fragmentType.getDefaultTitleResId());
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Bundle bundle = getArguments();
if (bundle != null) {
category = bundle.getString(MATH_ENTITY_CATEGORY_EXTRA_STRING);
}
final Bundle bundle = getArguments();
if (bundle != null) {
category = bundle.getString(MATH_ENTITY_CATEGORY_EXTRA_STRING);
}
fragmentHelper.onCreate(this);
}
fragmentHelper.onCreate(this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return fragmentHelper.onCreateView(this, inflater, container);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return fragmentHelper.onCreateView(this, inflater, container);
}
@Override
public void onViewCreated(View root, Bundle savedInstanceState) {
super.onViewCreated(root, savedInstanceState);
@Override
public void onViewCreated(View root, Bundle savedInstanceState) {
super.onViewCreated(root, savedInstanceState);
fragmentHelper.onViewCreated(this, root);
fragmentHelper.onViewCreated(this, root);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(final AdapterView<?> parent,
final View view,
final int position,
final long id) {
final AMenuItem<T> onClick = getOnClickAction();
if (onClick != null) {
onClick.onClick(((T) parent.getItemAtPosition(position)), getActivity());
}
}
});
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(final AdapterView<?> parent,
final View view,
final int position,
final long id) {
final AMenuItem<T> onClick = getOnClickAction();
if (onClick != null) {
onClick.onClick(((T) parent.getItemAtPosition(position)), getActivity());
}
}
});
getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
final T item = (T) parent.getItemAtPosition(position);
getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
final T item = (T) parent.getItemAtPosition(position);
final List<LabeledMenuItem<T>> menuItems = getMenuItemsOnLongClick(item);
final List<LabeledMenuItem<T>> menuItems = getMenuItemsOnLongClick(item);
if (!menuItems.isEmpty()) {
final ContextMenuBuilder<LabeledMenuItem<T>, T> menuBuilder = ContextMenuBuilder.newInstance(AbstractMathEntityListFragment.this.getActivity(), "math-entity-menu", ListContextMenu.newInstance(menuItems));
menuBuilder.build(item).show();
}
if (!menuItems.isEmpty()) {
final ContextMenuBuilder<LabeledMenuItem<T>, T> menuBuilder = ContextMenuBuilder.newInstance(AbstractMathEntityListFragment.this.getActivity(), "math-entity-menu", ListContextMenu.newInstance(menuItems));
menuBuilder.build(item).show();
}
return true;
}
});
}
return true;
}
});
}
@Nullable
protected abstract AMenuItem<T> getOnClickAction();
@Nullable
protected abstract AMenuItem<T> getOnClickAction();
@Override
public void onDestroy() {
fragmentHelper.onDestroy(this);
@Override
public void onDestroy() {
fragmentHelper.onDestroy(this);
super.onDestroy();
}
super.onDestroy();
}
@NotNull
protected abstract List<LabeledMenuItem<T>> getMenuItemsOnLongClick(@NotNull T item);
@NotNull
protected abstract List<LabeledMenuItem<T>> getMenuItemsOnLongClick(@NotNull T item);
@Override
public void onPause() {
this.fragmentHelper.onPause(this);
@Override
public void onPause() {
this.fragmentHelper.onPause(this);
super.onPause();
}
super.onPause();
}
@Override
public void onResume() {
super.onResume();
@Override
public void onResume() {
super.onResume();
this.fragmentHelper.onResume(this);
this.fragmentHelper.onResume(this);
adapter = new MathEntityArrayAdapter<T>(getDescriptionGetter(), this.getActivity(), R.layout.math_entity, R.id.math_entity_text, getMathEntitiesByCategory());
setListAdapter(adapter);
adapter = new MathEntityArrayAdapter<T>(getDescriptionGetter(), this.getActivity(), R.layout.math_entity, R.id.math_entity_text, getMathEntitiesByCategory());
setListAdapter(adapter);
sort();
}
sort();
}
@NotNull
private List<T> getMathEntitiesByCategory() {
final List<T> result = getMathEntities();
@NotNull
private List<T> getMathEntitiesByCategory() {
final List<T> result = getMathEntities();
new Filter<T>(new JPredicate<T>() {
@Override
public boolean apply(T t) {
return !isInCategory(t);
}
}).filter(result.iterator());
new Filter<T>(new JPredicate<T>() {
@Override
public boolean apply(T t) {
return !isInCategory(t);
}
}).filter(result.iterator());
return result;
}
return result;
}
protected boolean isInCategory(@Nullable T t) {
return t != null && (category == null || Objects.areEqual(getMathEntityCategory(t), category));
}
protected boolean isInCategory(@Nullable T t) {
return t != null && (category == null || Objects.areEqual(getMathEntityCategory(t), category));
}
@NotNull
protected abstract MathEntityDescriptionGetter getDescriptionGetter();
@NotNull
protected abstract MathEntityDescriptionGetter getDescriptionGetter();
@NotNull
protected abstract List<T> getMathEntities();
@NotNull
protected abstract List<T> getMathEntities();
@Nullable
abstract String getMathEntityCategory(@NotNull T t);
@Nullable
abstract String getMathEntityCategory(@NotNull T t);
protected void sort() {
final MathEntityArrayAdapter<T> localAdapter = adapter;
if (localAdapter != null) {
localAdapter.sort(new Comparator<T>() {
@Override
public int compare(T function1, T function2) {
return function1.getName().compareTo(function2.getName());
}
});
protected void sort() {
final MathEntityArrayAdapter<T> localAdapter = adapter;
if (localAdapter != null) {
localAdapter.sort(new Comparator<T>() {
@Override
public int compare(T function1, T function2) {
return function1.getName().compareTo(function2.getName());
}
});
localAdapter.notifyDataSetChanged();
}
}
localAdapter.notifyDataSetChanged();
}
}
protected static class MathEntityArrayAdapter<T extends MathEntity> extends ArrayAdapter<T> {
protected static class MathEntityArrayAdapter<T extends MathEntity> extends ArrayAdapter<T> {
@NotNull
private final MathEntityDescriptionGetter descriptionGetter;
@NotNull
private final MathEntityDescriptionGetter descriptionGetter;
private MathEntityArrayAdapter(@NotNull MathEntityDescriptionGetter descriptionGetter,
@NotNull Context context,
int resource,
int textViewResourceId,
@NotNull List<T> objects) {
private MathEntityArrayAdapter(@NotNull MathEntityDescriptionGetter descriptionGetter,
@NotNull Context context,
int resource,
int textViewResourceId,
@NotNull List<T> objects) {
super(context, resource, textViewResourceId, objects);
this.descriptionGetter = descriptionGetter;
}
super(context, resource, textViewResourceId, objects);
this.descriptionGetter = descriptionGetter;
}
@Override
public View getView(int position, @Nullable View convertView, ViewGroup parent) {
final ViewGroup result;
@Override
public View getView(int position, @Nullable View convertView, ViewGroup parent) {
final ViewGroup result;
if (convertView == null) {
result = (ViewGroup) super.getView(position, convertView, parent);
fillView(position, result);
} else {
result = (ViewGroup) convertView;
fillView(position, result);
}
if (convertView == null) {
result = (ViewGroup) super.getView(position, convertView, parent);
fillView(position, result);
} else {
result = (ViewGroup) convertView;
fillView(position, result);
}
return result;
}
return result;
}
private void fillView(int position, @NotNull ViewGroup result) {
final T mathEntity = getItem(position);
private void fillView(int position, @NotNull ViewGroup result) {
final T mathEntity = getItem(position);
final TextView text = (TextView) result.findViewById(R.id.math_entity_text);
text.setText(String.valueOf(mathEntity));
final TextView text = (TextView) result.findViewById(R.id.math_entity_text);
text.setText(String.valueOf(mathEntity));
final String mathEntityDescription = descriptionGetter.getDescription(getContext(), mathEntity.getName());
final String mathEntityDescription = descriptionGetter.getDescription(getContext(), mathEntity.getName());
final TextView description = (TextView) result.findViewById(R.id.math_entity_description);
if (!Strings.isEmpty(mathEntityDescription)) {
description.setVisibility(View.VISIBLE);
description.setText(mathEntityDescription);
} else {
description.setVisibility(View.GONE);
}
}
}
final TextView description = (TextView) result.findViewById(R.id.math_entity_description);
if (!Strings.isEmpty(mathEntityDescription)) {
description.setVisibility(View.VISIBLE);
description.setText(mathEntityDescription);
} else {
description.setVisibility(View.GONE);
}
}
}
protected static class MathEntityDescriptionGetterImpl implements MathEntityDescriptionGetter {
protected static class MathEntityDescriptionGetterImpl implements MathEntityDescriptionGetter {
@NotNull
private final CalculatorMathRegistry<?> mathRegistry;
@NotNull
private final CalculatorMathRegistry<?> mathRegistry;
public MathEntityDescriptionGetterImpl(@NotNull CalculatorMathRegistry<?> mathRegistry) {
this.mathRegistry = mathRegistry;
}
public MathEntityDescriptionGetterImpl(@NotNull CalculatorMathRegistry<?> mathRegistry) {
this.mathRegistry = mathRegistry;
}
@Override
public String getDescription(@NotNull Context context, @NotNull String mathEntityName) {
return this.mathRegistry.getDescription(mathEntityName);
}
}
@Override
public String getDescription(@NotNull Context context, @NotNull String mathEntityName) {
return this.mathRegistry.getDescription(mathEntityName);
}
}
protected static interface MathEntityDescriptionGetter {
protected static interface MathEntityDescriptionGetter {
@Nullable
String getDescription(@NotNull Context context, @NotNull String mathEntityName);
}
@Nullable
String getDescription(@NotNull Context context, @NotNull String mathEntityName);
}
public void addToAdapter(@NotNull T mathEntity) {
if (this.adapter != null) {
this.adapter.add(mathEntity);
}
}
public void addToAdapter(@NotNull T mathEntity) {
if (this.adapter != null) {
this.adapter.add(mathEntity);
}
}
public void removeFromAdapter(@NotNull T mathEntity) {
if (this.adapter != null) {
this.adapter.remove(mathEntity);
}
}
public void removeFromAdapter(@NotNull T mathEntity) {
if (this.adapter != null) {
this.adapter.remove(mathEntity);
}
}
public void notifyAdapter() {
if (this.adapter != null) {
this.adapter.notifyDataSetChanged();
}
}
public void notifyAdapter() {
if (this.adapter != null) {
this.adapter.notifyDataSetChanged();
}
}
@Nullable
protected MathEntityArrayAdapter<T> getAdapter() {
@@ -300,55 +299,55 @@ public abstract class AbstractMathEntityListFragment<T extends MathEntity> exten
}
@NotNull
protected Handler getUiHandler() {
return uiHandler;
}
protected Handler getUiHandler() {
return uiHandler;
}
/*
**********************************************************************
*
* STATIC
*
**********************************************************************
*/
/*
**********************************************************************
*
* STATIC
*
**********************************************************************
*/
static void createTab(@NotNull Context context,
@NotNull TabHost tabHost,
@NotNull String tabId,
@NotNull String categoryId,
int tabCaptionId,
@NotNull Class<? extends Activity> activityClass,
@Nullable Intent parentIntent) {
static void createTab(@NotNull Context context,
@NotNull TabHost tabHost,
@NotNull String tabId,
@NotNull String categoryId,
int tabCaptionId,
@NotNull Class<? extends Activity> activityClass,
@Nullable Intent parentIntent) {
TabHost.TabSpec spec;
TabHost.TabSpec spec;
final Intent intent;
if (parentIntent != null) {
intent = new Intent(parentIntent);
} else {
intent = new Intent();
}
intent.setClass(context, activityClass);
intent.putExtra(MATH_ENTITY_CATEGORY_EXTRA_STRING, categoryId);
final Intent intent;
if (parentIntent != null) {
intent = new Intent(parentIntent);
} else {
intent = new Intent();
}
intent.setClass(context, activityClass);
intent.putExtra(MATH_ENTITY_CATEGORY_EXTRA_STRING, categoryId);
// Initialize a TabSpec for each tab and add it to the TabHost
spec = tabHost.newTabSpec(tabId).setIndicator(context.getString(tabCaptionId)).setContent(intent);
// Initialize a TabSpec for each tab and add it to the TabHost
spec = tabHost.newTabSpec(tabId).setIndicator(context.getString(tabCaptionId)).setContent(intent);
tabHost.addTab(spec);
}
tabHost.addTab(spec);
}
@NotNull
public static Bundle createBundleFor(@NotNull String categoryId) {
final Bundle result = new Bundle(1);
putCategory(result, categoryId);
return result;
}
@NotNull
public static Bundle createBundleFor(@NotNull String categoryId) {
final Bundle result = new Bundle(1);
putCategory(result, categoryId);
return result;
}
static void putCategory(@NotNull Bundle bundle, @NotNull String categoryId) {
bundle.putString(MATH_ENTITY_CATEGORY_EXTRA_STRING, categoryId);
}
static void putCategory(@NotNull Bundle bundle, @NotNull String categoryId) {
bundle.putString(MATH_ENTITY_CATEGORY_EXTRA_STRING, categoryId);
}
@Override
public void onCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
}
@Override
public void onCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
}
}

View File

@@ -13,7 +13,6 @@ import com.actionbarsherlock.app.SherlockFragmentActivity;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.*;
import org.solovyev.android.calculator.CalculatorFragmentType;
import org.solovyev.android.calculator.history.CalculatorHistoryActivity;
/**
@@ -23,82 +22,82 @@ import org.solovyev.android.calculator.history.CalculatorHistoryActivity;
*/
public class CalculatorFunctionsActivity extends SherlockFragmentActivity implements CalculatorEventListener {
@NotNull
private final CalculatorActivityHelper activityHelper = CalculatorApplication.getInstance().createActivityHelper(R.layout.main_empty, CalculatorHistoryActivity.class.getSimpleName());
@NotNull
private final CalculatorActivityHelper activityHelper = CalculatorApplication.getInstance().createActivityHelper(R.layout.main_empty, CalculatorHistoryActivity.class.getSimpleName());
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activityHelper.onCreate(this, savedInstanceState);
activityHelper.onCreate(this, savedInstanceState);
final Bundle bundle;
final Bundle bundle;
final Intent intent = getIntent();
if (intent != null) {
bundle = intent.getExtras();
} else {
bundle = null;
}
final Intent intent = getIntent();
if (intent != null) {
bundle = intent.getExtras();
} else {
bundle = null;
}
final CalculatorFragmentType fragmentType = CalculatorFragmentType.functions;
final CalculatorFragmentType fragmentType = CalculatorFragmentType.functions;
for (FunctionCategory category : FunctionCategory.getCategoriesByTabOrder()) {
final AndroidFunctionCategory androidCategory = AndroidFunctionCategory.valueOf(category);
if (androidCategory != null) {
for (FunctionCategory category : FunctionCategory.getCategoriesByTabOrder()) {
final AndroidFunctionCategory androidCategory = AndroidFunctionCategory.valueOf(category);
if (androidCategory != null) {
final Bundle fragmentParameters;
final Bundle fragmentParameters;
if (category == FunctionCategory.my && bundle != null) {
AbstractMathEntityListFragment.putCategory(bundle, category.name());
fragmentParameters = bundle;
} else {
fragmentParameters = AbstractMathEntityListFragment.createBundleFor(category.name());
}
if (category == FunctionCategory.my && bundle != null) {
AbstractMathEntityListFragment.putCategory(bundle, category.name());
fragmentParameters = bundle;
} else {
fragmentParameters = AbstractMathEntityListFragment.createBundleFor(category.name());
}
activityHelper.addTab(this, fragmentType.createSubFragmentTag(category.name()), fragmentType.getFragmentClass(), fragmentParameters, androidCategory.getCaptionId(), R.id.main_layout);
} else {
Log.e(CalculatorFunctionsActivity.class.getSimpleName(), "Unable to find android function category for " + category);
}
}
activityHelper.addTab(this, fragmentType.createSubFragmentTag(category.name()), fragmentType.getFragmentClass(), fragmentParameters, androidCategory.getCaptionId(), R.id.main_layout);
} else {
Log.e(CalculatorFunctionsActivity.class.getSimpleName(), "Unable to find android function category for " + category);
}
}
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
activityHelper.onSaveInstanceState(this, outState);
}
activityHelper.onSaveInstanceState(this, outState);
}
@Override
protected void onResume() {
super.onResume();
@Override
protected void onResume() {
super.onResume();
activityHelper.onResume(this);
}
activityHelper.onResume(this);
}
@Override
protected void onPause() {
this.activityHelper.onPause(this);
@Override
protected void onPause() {
this.activityHelper.onPause(this);
super.onPause();
}
super.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
@Override
protected void onDestroy() {
super.onDestroy();
this.activityHelper.onDestroy(this);
}
this.activityHelper.onDestroy(this);
}
@Override
public void onCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
switch (calculatorEventType) {
case use_function:
this.finish();
break;
}
}
@Override
public void onCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
switch (calculatorEventType) {
case use_function:
this.finish();
break;
}
}
}

View File

@@ -20,7 +20,6 @@ import jscl.math.function.IFunction;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.*;
import org.solovyev.android.calculator.CalculatorFragmentType;
import org.solovyev.android.calculator.function.FunctionEditDialogFragment;
import org.solovyev.android.menu.AMenuItem;
import org.solovyev.android.menu.LabeledMenuItem;
@@ -39,52 +38,53 @@ public class CalculatorFunctionsFragment extends AbstractMathEntityListFragment<
public static final String CREATE_FUNCTION_EXTRA = "create_function";
public CalculatorFunctionsFragment() {
super(CalculatorFragmentType.functions);
}
public CalculatorFunctionsFragment() {
super(CalculatorFragmentType.functions);
}
@Override
public void onCreate(Bundle savedInstanceState) {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Bundle bundle = getArguments();
if (bundle != null) {
final Parcelable parcelable = bundle.getParcelable(CREATE_FUNCTION_EXTRA);
if (parcelable instanceof FunctionEditDialogFragment.Input) {
FunctionEditDialogFragment.showDialog((FunctionEditDialogFragment.Input) parcelable, this.getActivity().getSupportFragmentManager());
final Bundle bundle = getArguments();
if (bundle != null) {
final Parcelable parcelable = bundle.getParcelable(CREATE_FUNCTION_EXTRA);
if (parcelable instanceof FunctionEditDialogFragment.Input) {
FunctionEditDialogFragment.showDialog((FunctionEditDialogFragment.Input) parcelable, this.getActivity().getSupportFragmentManager());
// in order to stop intent for other tabs
bundle.remove(CREATE_FUNCTION_EXTRA);
}
}
// in order to stop intent for other tabs
bundle.remove(CREATE_FUNCTION_EXTRA);
}
}
setHasOptionsMenu(true);
setHasOptionsMenu(true);
}
@Override
protected AMenuItem<Function> getOnClickAction() {
return LongClickMenuItem.use;
}
@Override
protected AMenuItem<Function> getOnClickAction() {
return LongClickMenuItem.use;
}
@NotNull
@NotNull
@Override
protected List<LabeledMenuItem<Function>> getMenuItemsOnLongClick(@NotNull Function item) {
List<LabeledMenuItem<Function>> result = new ArrayList<LabeledMenuItem<Function>>(Arrays.asList(LongClickMenuItem.values()));
final CalculatorMathRegistry<Function> functionsRegistry = Locator.getInstance().getEngine().getFunctionsRegistry();
if ( Strings.isEmpty(functionsRegistry.getDescription(item.getName())) ) {
final CalculatorMathRegistry<Function> functionsRegistry = Locator.getInstance().getEngine().getFunctionsRegistry();
if (Strings.isEmpty(functionsRegistry.getDescription(item.getName()))) {
result.remove(LongClickMenuItem.copy_description);
}
final Function function = functionsRegistry.get(item.getName());
if (function == null || function.isSystem()) {
result.remove(LongClickMenuItem.edit);
result.remove(LongClickMenuItem.remove);
}
final Function function = functionsRegistry.get(item.getName());
if (function == null || function.isSystem()) {
result.remove(LongClickMenuItem.edit);
result.remove(LongClickMenuItem.remove);
}
return result;
}
@NotNull
@Override
protected MathEntityDescriptionGetter getDescriptionGetter() {
@@ -102,44 +102,44 @@ public class CalculatorFunctionsFragment extends AbstractMathEntityListFragment<
return Locator.getInstance().getEngine().getFunctionsRegistry().getCategory(function);
}
@Override
public void onCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
super.onCalculatorEvent(calculatorEventData, calculatorEventType, data);
@Override
public void onCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
super.onCalculatorEvent(calculatorEventData, calculatorEventType, data);
switch (calculatorEventType) {
case function_added:
processFunctionAdded((Function) data);
break;
switch (calculatorEventType) {
case function_added:
processFunctionAdded((Function) data);
break;
case function_changed:
processFunctionChanged((Change<IFunction>) data);
break;
case function_changed:
processFunctionChanged((Change<IFunction>) data);
break;
case function_removed:
processFunctionRemoved((Function) data);
break;
}
}
case function_removed:
processFunctionRemoved((Function) data);
break;
}
}
private void processFunctionRemoved(@NotNull final Function function) {
if (this.isInCategory(function)) {
getUiHandler().post(new Runnable() {
@Override
public void run() {
removeFromAdapter(function);
notifyAdapter();
}
});
}
}
private void processFunctionRemoved(@NotNull final Function function) {
if (this.isInCategory(function)) {
getUiHandler().post(new Runnable() {
@Override
public void run() {
removeFromAdapter(function);
notifyAdapter();
}
});
}
}
private void processFunctionChanged(@NotNull final Change<IFunction> change) {
final IFunction newFunction = change.getNewValue();
private void processFunctionChanged(@NotNull final Change<IFunction> change) {
final IFunction newFunction = change.getNewValue();
if (newFunction instanceof Function) {
if (this.isInCategory((Function)newFunction)) {
if (this.isInCategory((Function) newFunction)) {
getUiHandler().post(new Runnable() {
@Override
@@ -148,10 +148,10 @@ public class CalculatorFunctionsFragment extends AbstractMathEntityListFragment<
if (oldValue.isIdDefined()) {
final MathEntityArrayAdapter<Function> adapter = getAdapter();
if ( adapter != null ) {
if (adapter != null) {
for (int i = 0; i < adapter.getCount(); i++) {
final Function functionFromAdapter = adapter.getItem(i);
if ( functionFromAdapter.isIdDefined() && oldValue.getId().equals(functionFromAdapter.getId()) ) {
if (functionFromAdapter.isIdDefined() && oldValue.getId().equals(functionFromAdapter.getId())) {
adapter.remove(functionFromAdapter);
break;
}
@@ -159,7 +159,7 @@ public class CalculatorFunctionsFragment extends AbstractMathEntityListFragment<
}
}
addToAdapter((Function)newFunction);
addToAdapter((Function) newFunction);
sort();
}
});
@@ -169,100 +169,100 @@ public class CalculatorFunctionsFragment extends AbstractMathEntityListFragment<
}
}
private void processFunctionAdded(@NotNull final Function function) {
if (this.isInCategory(function)) {
getUiHandler().post(new Runnable() {
@Override
public void run() {
addToAdapter(function);
sort();
}
});
}
}
private void processFunctionAdded(@NotNull final Function function) {
if (this.isInCategory(function)) {
getUiHandler().post(new Runnable() {
@Override
public void run() {
addToAdapter(function);
sort();
}
});
}
}
/*
**********************************************************************
*
* MENU
*
**********************************************************************
*/
/*
**********************************************************************
*
* MENU
*
**********************************************************************
*/
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.functions_menu, menu);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.functions_menu, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
boolean result;
@Override
public boolean onOptionsItemSelected(MenuItem item) {
boolean result;
switch (item.getItemId()) {
case R.id.functions_menu_add_function:
FunctionEditDialogFragment.showDialog(FunctionEditDialogFragment.Input.newInstance(), this.getActivity().getSupportFragmentManager());
result = true;
break;
default:
result = super.onOptionsItemSelected(item);
}
switch (item.getItemId()) {
case R.id.functions_menu_add_function:
FunctionEditDialogFragment.showDialog(FunctionEditDialogFragment.Input.newInstance(), this.getActivity().getSupportFragmentManager());
result = true;
break;
default:
result = super.onOptionsItemSelected(item);
}
return result;
}
return result;
}
/*
**********************************************************************
*
* STATIC
*
**********************************************************************
*/
/*
**********************************************************************
*
* STATIC
*
**********************************************************************
*/
private static enum LongClickMenuItem implements LabeledMenuItem<Function> {
use(R.string.c_use) {
@Override
public void onClick(@NotNull Function function, @NotNull Context context) {
Locator.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.use_function, function);
}
},
private static enum LongClickMenuItem implements LabeledMenuItem<Function> {
use(R.string.c_use) {
@Override
public void onClick(@NotNull Function function, @NotNull Context context) {
Locator.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.use_function, function);
}
},
edit(R.string.c_edit) {
@Override
public void onClick(@NotNull Function function, @NotNull Context context) {
edit(R.string.c_edit) {
@Override
public void onClick(@NotNull Function function, @NotNull Context context) {
if (function instanceof IFunction) {
FunctionEditDialogFragment.showDialog(FunctionEditDialogFragment.Input.newFromFunction((IFunction) function), ((SherlockFragmentActivity) context).getSupportFragmentManager());
}
}
},
},
remove(R.string.c_remove) {
@Override
public void onClick(@NotNull Function function, @NotNull Context context) {
MathEntityRemover.newFunctionRemover(function, null, context, context).showConfirmationDialog();
}
},
remove(R.string.c_remove) {
@Override
public void onClick(@NotNull Function function, @NotNull Context context) {
MathEntityRemover.newFunctionRemover(function, null, context, context).showConfirmationDialog();
}
},
copy_description(R.string.c_copy_description) {
@Override
public void onClick(@NotNull Function function, @NotNull Context context) {
final String text = Locator.getInstance().getEngine().getFunctionsRegistry().getDescription(function.getName());
if (!Strings.isEmpty(text)) {
final ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Activity.CLIPBOARD_SERVICE);
clipboard.setText(text);
}
}
};
private final int captionId;
copy_description(R.string.c_copy_description) {
@Override
public void onClick(@NotNull Function function, @NotNull Context context) {
final String text = Locator.getInstance().getEngine().getFunctionsRegistry().getDescription(function.getName());
if (!Strings.isEmpty(text)) {
final ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Activity.CLIPBOARD_SERVICE);
clipboard.setText(text);
}
}
};
private final int captionId;
LongClickMenuItem(int captionId) {
this.captionId = captionId;
}
LongClickMenuItem(int captionId) {
this.captionId = captionId;
}
@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

@@ -11,7 +11,6 @@ import com.actionbarsherlock.app.SherlockFragmentActivity;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.*;
import org.solovyev.android.calculator.CalculatorFragmentType;
import org.solovyev.android.calculator.history.CalculatorHistoryActivity;
/**
@@ -21,62 +20,62 @@ import org.solovyev.android.calculator.history.CalculatorHistoryActivity;
*/
public class CalculatorOperatorsActivity extends SherlockFragmentActivity implements CalculatorEventListener {
@NotNull
private final CalculatorActivityHelper activityHelper = CalculatorApplication.getInstance().createActivityHelper(R.layout.main_empty, CalculatorHistoryActivity.class.getSimpleName());
@NotNull
private final CalculatorActivityHelper activityHelper = CalculatorApplication.getInstance().createActivityHelper(R.layout.main_empty, CalculatorHistoryActivity.class.getSimpleName());
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activityHelper.onCreate(this, savedInstanceState);
activityHelper.onCreate(this, savedInstanceState);
final CalculatorFragmentType fragmentType = CalculatorFragmentType.operators;
final CalculatorFragmentType fragmentType = CalculatorFragmentType.operators;
for (OperatorCategory category : OperatorCategory.getCategoriesByTabOrder()) {
final AndroidOperatorCategory androidCategory = AndroidOperatorCategory.valueOf(category);
if (androidCategory != null) {
activityHelper.addTab(this, fragmentType.createSubFragmentTag(category.name()), fragmentType.getFragmentClass(), AbstractMathEntityListFragment.createBundleFor(category.name()), androidCategory.getCaptionId(), R.id.main_layout);
} else {
activityHelper.logError("Unable to find android operator category for " + category);
}
}
}
for (OperatorCategory category : OperatorCategory.getCategoriesByTabOrder()) {
final AndroidOperatorCategory androidCategory = AndroidOperatorCategory.valueOf(category);
if (androidCategory != null) {
activityHelper.addTab(this, fragmentType.createSubFragmentTag(category.name()), fragmentType.getFragmentClass(), AbstractMathEntityListFragment.createBundleFor(category.name()), androidCategory.getCaptionId(), R.id.main_layout);
} else {
activityHelper.logError("Unable to find android operator category for " + category);
}
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
activityHelper.onSaveInstanceState(this, outState);
}
activityHelper.onSaveInstanceState(this, outState);
}
@Override
protected void onResume() {
super.onResume();
@Override
protected void onResume() {
super.onResume();
activityHelper.onResume(this);
}
activityHelper.onResume(this);
}
@Override
protected void onPause() {
this.activityHelper.onPause(this);
@Override
protected void onPause() {
this.activityHelper.onPause(this);
super.onPause();
}
super.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
@Override
protected void onDestroy() {
super.onDestroy();
this.activityHelper.onDestroy(this);
}
this.activityHelper.onDestroy(this);
}
@Override
public void onCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
switch (calculatorEventType) {
case use_operator:
this.finish();
break;
}
}
@Override
public void onCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
switch (calculatorEventType) {
case use_operator:
this.finish();
break;
}
}
}

View File

@@ -5,10 +5,10 @@ import android.content.Context;
import android.text.ClipboardManager;
import jscl.math.operator.Operator;
import org.jetbrains.annotations.NotNull;
import org.solovyev.android.calculator.Locator;
import org.solovyev.android.calculator.CalculatorEventType;
import org.solovyev.android.calculator.R;
import org.solovyev.android.calculator.CalculatorFragmentType;
import org.solovyev.android.calculator.Locator;
import org.solovyev.android.calculator.R;
import org.solovyev.android.menu.AMenuItem;
import org.solovyev.android.menu.LabeledMenuItem;
import org.solovyev.common.text.Strings;
@@ -25,21 +25,21 @@ import java.util.List;
public class CalculatorOperatorsFragment extends AbstractMathEntityListFragment<Operator> {
public CalculatorOperatorsFragment() {
super(CalculatorFragmentType.operators);
}
public CalculatorOperatorsFragment() {
super(CalculatorFragmentType.operators);
}
@Override
protected AMenuItem<Operator> getOnClickAction() {
return LongClickMenuItem.use;
}
@Override
protected AMenuItem<Operator> getOnClickAction() {
return LongClickMenuItem.use;
}
@NotNull
@NotNull
@Override
protected List<LabeledMenuItem<Operator>> getMenuItemsOnLongClick(@NotNull Operator item) {
final List<LabeledMenuItem<Operator>> result = new ArrayList<LabeledMenuItem<Operator>>(Arrays.asList(LongClickMenuItem.values()));
if ( Strings.isEmpty(OperatorDescriptionGetter.instance.getDescription(this.getActivity(), item.getName())) ) {
if (Strings.isEmpty(OperatorDescriptionGetter.instance.getDescription(this.getActivity(), item.getName()))) {
result.remove(LongClickMenuItem.copy_description);
}
@@ -47,87 +47,87 @@ public class CalculatorOperatorsFragment extends AbstractMathEntityListFragment<
}
@NotNull
@Override
protected MathEntityDescriptionGetter getDescriptionGetter() {
return OperatorDescriptionGetter.instance;
}
@Override
protected MathEntityDescriptionGetter getDescriptionGetter() {
return OperatorDescriptionGetter.instance;
}
@NotNull
@Override
protected List<Operator> getMathEntities() {
final List<Operator> result = new ArrayList<Operator>();
@NotNull
@Override
protected List<Operator> getMathEntities() {
final List<Operator> result = new ArrayList<Operator>();
result.addAll(Locator.getInstance().getEngine().getOperatorsRegistry().getEntities());
result.addAll(Locator.getInstance().getEngine().getPostfixFunctionsRegistry().getEntities());
result.addAll(Locator.getInstance().getEngine().getOperatorsRegistry().getEntities());
result.addAll(Locator.getInstance().getEngine().getPostfixFunctionsRegistry().getEntities());
return result;
}
return result;
}
@Override
protected String getMathEntityCategory(@NotNull Operator operator) {
String result = Locator.getInstance().getEngine().getOperatorsRegistry().getCategory(operator);
if (result == null) {
result = Locator.getInstance().getEngine().getPostfixFunctionsRegistry().getCategory(operator);
}
@Override
protected String getMathEntityCategory(@NotNull Operator operator) {
String result = Locator.getInstance().getEngine().getOperatorsRegistry().getCategory(operator);
if (result == null) {
result = Locator.getInstance().getEngine().getPostfixFunctionsRegistry().getCategory(operator);
}
return result;
}
return result;
}
private static enum OperatorDescriptionGetter implements MathEntityDescriptionGetter {
private static enum OperatorDescriptionGetter implements MathEntityDescriptionGetter {
instance;
@Override
public String getDescription(@NotNull Context context, @NotNull String mathEntityName) {
String result = Locator.getInstance().getEngine().getOperatorsRegistry().getDescription(mathEntityName);
if (Strings.isEmpty(result)) {
result = Locator.getInstance().getEngine().getPostfixFunctionsRegistry().getDescription(mathEntityName);
}
@Override
public String getDescription(@NotNull Context context, @NotNull String mathEntityName) {
String result = Locator.getInstance().getEngine().getOperatorsRegistry().getDescription(mathEntityName);
if (Strings.isEmpty(result)) {
result = Locator.getInstance().getEngine().getPostfixFunctionsRegistry().getDescription(mathEntityName);
}
return result;
}
}
return result;
}
}
/*
**********************************************************************
*
* STATIC
*
**********************************************************************
*/
/*
**********************************************************************
*
* STATIC
*
**********************************************************************
*/
private static enum LongClickMenuItem implements LabeledMenuItem<Operator> {
private static enum LongClickMenuItem implements LabeledMenuItem<Operator> {
use(R.string.c_use) {
@Override
public void onClick(@NotNull Operator data, @NotNull Context context) {
Locator.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.use_operator, data);
}
},
use(R.string.c_use) {
@Override
public void onClick(@NotNull Operator data, @NotNull Context context) {
Locator.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.use_operator, data);
}
},
copy_description(R.string.c_copy_description) {
@Override
public void onClick(@NotNull Operator data, @NotNull Context context) {
final String text = OperatorDescriptionGetter.instance.getDescription(context, data.getName());
if (!Strings.isEmpty(text)) {
final ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Activity.CLIPBOARD_SERVICE);
clipboard.setText(text);
}
}
};
private final int captionId;
copy_description(R.string.c_copy_description) {
@Override
public void onClick(@NotNull Operator data, @NotNull Context context) {
final String text = OperatorDescriptionGetter.instance.getDescription(context, data.getName());
if (!Strings.isEmpty(text)) {
final ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Activity.CLIPBOARD_SERVICE);
clipboard.setText(text);
}
}
};
private final int captionId;
LongClickMenuItem(int captionId) {
this.captionId = captionId;
}
LongClickMenuItem(int captionId) {
this.captionId = captionId;
}
@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

@@ -12,10 +12,7 @@ import com.actionbarsherlock.app.SherlockFragmentActivity;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.*;
import org.solovyev.android.calculator.CalculatorFragmentType;
import org.solovyev.android.calculator.history.CalculatorHistoryActivity;
import org.solovyev.android.calculator.AndroidVarCategory;
import org.solovyev.android.calculator.VarCategory;
/**
* User: serso
@@ -24,84 +21,84 @@ import org.solovyev.android.calculator.VarCategory;
*/
public class CalculatorVarsActivity extends SherlockFragmentActivity implements CalculatorEventListener {
@NotNull
private final CalculatorActivityHelper activityHelper = CalculatorApplication.getInstance().createActivityHelper(R.layout.main_empty, CalculatorHistoryActivity.class.getSimpleName());
@NotNull
private final CalculatorActivityHelper activityHelper = CalculatorApplication.getInstance().createActivityHelper(R.layout.main_empty, CalculatorHistoryActivity.class.getSimpleName());
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activityHelper.onCreate(this, savedInstanceState);
activityHelper.onCreate(this, savedInstanceState);
final Bundle bundle;
final Bundle bundle;
final Intent intent = getIntent();
if (intent != null) {
bundle = intent.getExtras();
} else {
bundle = null;
}
final Intent intent = getIntent();
if (intent != null) {
bundle = intent.getExtras();
} else {
bundle = null;
}
final CalculatorFragmentType fragmentType = CalculatorFragmentType.variables;
final CalculatorFragmentType fragmentType = CalculatorFragmentType.variables;
for (VarCategory category : VarCategory.getCategoriesByTabOrder()) {
for (VarCategory category : VarCategory.getCategoriesByTabOrder()) {
final Bundle fragmentParameters;
final Bundle fragmentParameters;
if (category == VarCategory.my && bundle != null) {
AbstractMathEntityListFragment.putCategory(bundle, category.name());
fragmentParameters = bundle;
} else {
fragmentParameters = AbstractMathEntityListFragment.createBundleFor(category.name());
}
if (category == VarCategory.my && bundle != null) {
AbstractMathEntityListFragment.putCategory(bundle, category.name());
fragmentParameters = bundle;
} else {
fragmentParameters = AbstractMathEntityListFragment.createBundleFor(category.name());
}
final AndroidVarCategory androidVarCategory = AndroidVarCategory.valueOf(category);
final AndroidVarCategory androidVarCategory = AndroidVarCategory.valueOf(category);
if (androidVarCategory != null) {
activityHelper.addTab(this, fragmentType.createSubFragmentTag(category.name()), fragmentType.getFragmentClass(), fragmentParameters, androidVarCategory.getCaptionId(), R.id.main_layout);
} else {
activityHelper.logError("Unable to find android var category for " + category);
}
if (androidVarCategory != null) {
activityHelper.addTab(this, fragmentType.createSubFragmentTag(category.name()), fragmentType.getFragmentClass(), fragmentParameters, androidVarCategory.getCaptionId(), R.id.main_layout);
} else {
activityHelper.logError("Unable to find android var category for " + category);
}
}
}
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
activityHelper.onSaveInstanceState(this, outState);
}
activityHelper.onSaveInstanceState(this, outState);
}
@Override
protected void onResume() {
super.onResume();
@Override
protected void onResume() {
super.onResume();
activityHelper.onResume(this);
}
activityHelper.onResume(this);
}
@Override
protected void onPause() {
this.activityHelper.onPause(this);
@Override
protected void onPause() {
this.activityHelper.onPause(this);
super.onPause();
}
super.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
@Override
protected void onDestroy() {
super.onDestroy();
this.activityHelper.onDestroy(this);
}
this.activityHelper.onDestroy(this);
}
@Override
public void onCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
switch (calculatorEventType) {
case use_constant:
this.finish();
break;
}
}
@Override
public void onCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
switch (calculatorEventType) {
case use_constant:
this.finish();
break;
}
}
}

View File

@@ -17,7 +17,6 @@ import jscl.math.function.IConstant;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.*;
import org.solovyev.android.calculator.CalculatorFragmentType;
import org.solovyev.android.calculator.math.MathType;
import org.solovyev.android.menu.AMenuItem;
import org.solovyev.android.menu.LabeledMenuItem;
@@ -36,246 +35,246 @@ import java.util.List;
*/
public class CalculatorVarsFragment extends AbstractMathEntityListFragment<IConstant> {
public static final String CREATE_VAR_EXTRA_STRING = "create_var";
public static final String CREATE_VAR_EXTRA_STRING = "create_var";
public CalculatorVarsFragment() {
super(CalculatorFragmentType.variables);
}
public CalculatorVarsFragment() {
super(CalculatorFragmentType.variables);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Bundle bundle = getArguments();
if (bundle != null) {
final String varValue = bundle.getString(CREATE_VAR_EXTRA_STRING);
if (!Strings.isEmpty(varValue)) {
VarEditDialogFragment.showDialog(VarEditDialogFragment.Input.newFromValue(varValue), this.getActivity().getSupportFragmentManager());
final Bundle bundle = getArguments();
if (bundle != null) {
final String varValue = bundle.getString(CREATE_VAR_EXTRA_STRING);
if (!Strings.isEmpty(varValue)) {
VarEditDialogFragment.showDialog(VarEditDialogFragment.Input.newFromValue(varValue), this.getActivity().getSupportFragmentManager());
// in order to stop intent for other tabs
bundle.remove(CREATE_VAR_EXTRA_STRING);
}
}
// in order to stop intent for other tabs
bundle.remove(CREATE_VAR_EXTRA_STRING);
}
}
setHasOptionsMenu(true);
}
setHasOptionsMenu(true);
}
@Override
protected AMenuItem<IConstant> getOnClickAction() {
return LongClickMenuItem.use;
}
@Override
protected AMenuItem<IConstant> getOnClickAction() {
return LongClickMenuItem.use;
}
@NotNull
@Override
protected List<LabeledMenuItem<IConstant>> getMenuItemsOnLongClick(@NotNull IConstant item) {
final List<LabeledMenuItem<IConstant>> result = new ArrayList<LabeledMenuItem<IConstant>>(Arrays.asList(LongClickMenuItem.values()));
@NotNull
@Override
protected List<LabeledMenuItem<IConstant>> getMenuItemsOnLongClick(@NotNull IConstant item) {
final List<LabeledMenuItem<IConstant>> result = new ArrayList<LabeledMenuItem<IConstant>>(Arrays.asList(LongClickMenuItem.values()));
if (item.isSystem()) {
result.remove(LongClickMenuItem.edit);
result.remove(LongClickMenuItem.remove);
}
if (item.isSystem()) {
result.remove(LongClickMenuItem.edit);
result.remove(LongClickMenuItem.remove);
}
if (Strings.isEmpty(Locator.getInstance().getEngine().getVarsRegistry().getDescription(item.getName()))) {
result.remove(LongClickMenuItem.copy_description);
}
if (Strings.isEmpty(Locator.getInstance().getEngine().getVarsRegistry().getDescription(item.getName()))) {
result.remove(LongClickMenuItem.copy_description);
}
if (Strings.isEmpty(item.getValue())) {
result.remove(LongClickMenuItem.copy_value);
}
if (Strings.isEmpty(item.getValue())) {
result.remove(LongClickMenuItem.copy_value);
}
return result;
}
return result;
}
@NotNull
@Override
protected MathEntityDescriptionGetter getDescriptionGetter() {
return new MathEntityDescriptionGetterImpl(Locator.getInstance().getEngine().getVarsRegistry());
}
@NotNull
@Override
protected MathEntityDescriptionGetter getDescriptionGetter() {
return new MathEntityDescriptionGetterImpl(Locator.getInstance().getEngine().getVarsRegistry());
}
@SuppressWarnings({"UnusedDeclaration"})
public void addVarButtonClickHandler(@NotNull View v) {
VarEditDialogFragment.showDialog(VarEditDialogFragment.Input.newInstance(), this.getActivity().getSupportFragmentManager());
}
@SuppressWarnings({"UnusedDeclaration"})
public void addVarButtonClickHandler(@NotNull View v) {
VarEditDialogFragment.showDialog(VarEditDialogFragment.Input.newInstance(), this.getActivity().getSupportFragmentManager());
}
@NotNull
@Override
protected List<IConstant> getMathEntities() {
final List<IConstant> result = new ArrayList<IConstant>(Locator.getInstance().getEngine().getVarsRegistry().getEntities());
@NotNull
@Override
protected List<IConstant> getMathEntities() {
final List<IConstant> result = new ArrayList<IConstant>(Locator.getInstance().getEngine().getVarsRegistry().getEntities());
Collections.removeAll(result, new JPredicate<IConstant>() {
@Override
public boolean apply(@Nullable IConstant var) {
return var != null && Collections.contains(var.getName(), MathType.INFINITY_JSCL, MathType.NAN);
}
});
Collections.removeAll(result, new JPredicate<IConstant>() {
@Override
public boolean apply(@Nullable IConstant var) {
return var != null && Collections.contains(var.getName(), MathType.INFINITY_JSCL, MathType.NAN);
}
});
return result;
}
return result;
}
@Override
protected String getMathEntityCategory(@NotNull IConstant var) {
return Locator.getInstance().getEngine().getVarsRegistry().getCategory(var);
}
@Override
protected String getMathEntityCategory(@NotNull IConstant var) {
return Locator.getInstance().getEngine().getVarsRegistry().getCategory(var);
}
public static boolean isValidValue(@NotNull String value) {
try {
final PreparedExpression expression = ToJsclTextProcessor.getInstance().process(value);
final List<IConstant> constants = expression.getUndefinedVars();
return constants.isEmpty();
} catch (RuntimeException e) {
return true;
} catch (CalculatorParseException e) {
return true;
}
}
public static boolean isValidValue(@NotNull String value) {
try {
final PreparedExpression expression = ToJsclTextProcessor.getInstance().process(value);
final List<IConstant> constants = expression.getUndefinedVars();
return constants.isEmpty();
} catch (RuntimeException e) {
return true;
} catch (CalculatorParseException e) {
return true;
}
}
/*
**********************************************************************
*
* MENU
*
**********************************************************************
*/
/*
**********************************************************************
*
* MENU
*
**********************************************************************
*/
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.vars_menu, menu);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.vars_menu, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
boolean result;
@Override
public boolean onOptionsItemSelected(MenuItem item) {
boolean result;
switch (item.getItemId()) {
case R.id.var_menu_add_var:
VarEditDialogFragment.showDialog(VarEditDialogFragment.Input.newInstance(), this.getActivity().getSupportFragmentManager());
result = true;
break;
default:
result = super.onOptionsItemSelected(item);
}
switch (item.getItemId()) {
case R.id.var_menu_add_var:
VarEditDialogFragment.showDialog(VarEditDialogFragment.Input.newInstance(), this.getActivity().getSupportFragmentManager());
result = true;
break;
default:
result = super.onOptionsItemSelected(item);
}
return result;
}
return result;
}
@Override
public void onCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
super.onCalculatorEvent(calculatorEventData, calculatorEventType, data);
@Override
public void onCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
super.onCalculatorEvent(calculatorEventData, calculatorEventType, data);
switch (calculatorEventType) {
case constant_added:
processConstantAdded((IConstant) data);
break;
switch (calculatorEventType) {
case constant_added:
processConstantAdded((IConstant) data);
break;
case constant_changed:
processConstantChanged((Change<IConstant>) data);
break;
case constant_changed:
processConstantChanged((Change<IConstant>) data);
break;
case constant_removed:
processConstantRemoved((IConstant) data);
break;
}
}
case constant_removed:
processConstantRemoved((IConstant) data);
break;
}
}
private void processConstantRemoved(@NotNull final IConstant constant) {
if (this.isInCategory(constant)) {
getUiHandler().post(new Runnable() {
@Override
public void run() {
removeFromAdapter(constant);
notifyAdapter();
}
});
}
}
private void processConstantRemoved(@NotNull final IConstant constant) {
if (this.isInCategory(constant)) {
getUiHandler().post(new Runnable() {
@Override
public void run() {
removeFromAdapter(constant);
notifyAdapter();
}
});
}
}
private void processConstantChanged(@NotNull final Change<IConstant> change) {
final IConstant newConstant = change.getNewValue();
if (this.isInCategory(newConstant)) {
getUiHandler().post(new Runnable() {
@Override
public void run() {
removeFromAdapter(change.getOldValue());
addToAdapter(newConstant);
sort();
}
});
}
}
private void processConstantChanged(@NotNull final Change<IConstant> change) {
final IConstant newConstant = change.getNewValue();
if (this.isInCategory(newConstant)) {
getUiHandler().post(new Runnable() {
@Override
public void run() {
removeFromAdapter(change.getOldValue());
addToAdapter(newConstant);
sort();
}
});
}
}
private void processConstantAdded(@NotNull final IConstant constant) {
if (this.isInCategory(constant)) {
getUiHandler().post(new Runnable() {
@Override
public void run() {
addToAdapter(constant);
sort();
}
});
}
}
private void processConstantAdded(@NotNull final IConstant constant) {
if (this.isInCategory(constant)) {
getUiHandler().post(new Runnable() {
@Override
public void run() {
addToAdapter(constant);
sort();
}
});
}
}
/*
**********************************************************************
*
* STATIC
*
**********************************************************************
*/
/*
**********************************************************************
*
* STATIC
*
**********************************************************************
*/
private static enum LongClickMenuItem implements LabeledMenuItem<IConstant> {
use(R.string.c_use) {
@Override
public void onClick(@NotNull IConstant data, @NotNull Context context) {
Locator.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.use_constant, data);
}
},
private static enum LongClickMenuItem implements LabeledMenuItem<IConstant> {
use(R.string.c_use) {
@Override
public void onClick(@NotNull IConstant data, @NotNull Context context) {
Locator.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.use_constant, data);
}
},
edit(R.string.c_edit) {
@Override
public void onClick(@NotNull IConstant constant, @NotNull Context context) {
VarEditDialogFragment.showDialog(VarEditDialogFragment.Input.newFromConstant(constant), ((SherlockFragmentActivity) context).getSupportFragmentManager());
}
},
edit(R.string.c_edit) {
@Override
public void onClick(@NotNull IConstant constant, @NotNull Context context) {
VarEditDialogFragment.showDialog(VarEditDialogFragment.Input.newFromConstant(constant), ((SherlockFragmentActivity) context).getSupportFragmentManager());
}
},
remove(R.string.c_remove) {
@Override
public void onClick(@NotNull IConstant constant, @NotNull Context context) {
MathEntityRemover.newConstantRemover(constant, null, context, context).showConfirmationDialog();
}
},
remove(R.string.c_remove) {
@Override
public void onClick(@NotNull IConstant constant, @NotNull Context context) {
MathEntityRemover.newConstantRemover(constant, null, context, context).showConfirmationDialog();
}
},
copy_value(R.string.c_copy_value) {
@Override
public void onClick(@NotNull IConstant data, @NotNull Context context) {
final String text = data.getValue();
if (!Strings.isEmpty(text)) {
assert text != null;
Locator.getInstance().getClipboard().setText(text);
}
}
},
copy_value(R.string.c_copy_value) {
@Override
public void onClick(@NotNull IConstant data, @NotNull Context context) {
final String text = data.getValue();
if (!Strings.isEmpty(text)) {
assert text != null;
Locator.getInstance().getClipboard().setText(text);
}
}
},
copy_description(R.string.c_copy_description) {
@Override
public void onClick(@NotNull IConstant data, @NotNull Context context) {
final String text = Locator.getInstance().getEngine().getVarsRegistry().getDescription(data.getName());
if (!Strings.isEmpty(text)) {
assert text != null;
Locator.getInstance().getClipboard().setText(text);
}
}
};
private final int captionId;
copy_description(R.string.c_copy_description) {
@Override
public void onClick(@NotNull IConstant data, @NotNull Context context) {
final String text = Locator.getInstance().getEngine().getVarsRegistry().getDescription(data.getName());
if (!Strings.isEmpty(text)) {
assert text != null;
Locator.getInstance().getClipboard().setText(text);
}
}
};
private final int captionId;
LongClickMenuItem(int captionId) {
this.captionId = captionId;
}
LongClickMenuItem(int captionId) {
this.captionId = captionId;
}
@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,8 +16,8 @@ import jscl.math.function.IConstant;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.CalculatorEventType;
import org.solovyev.android.calculator.Locator;
import org.solovyev.android.calculator.CalculatorMathRegistry;
import org.solovyev.android.calculator.Locator;
import org.solovyev.android.calculator.R;
import org.solovyev.common.math.MathEntity;
@@ -39,138 +39,138 @@ public class MathEntityRemover<T extends MathEntity> implements View.OnClickList
@NotNull
private final CalculatorMathRegistry<? super T> varsRegistry;
@NotNull
private Context context;
@NotNull
private Context context;
@NotNull
private final Object source;
@NotNull
private final Object source;
@NotNull
private final Params params;
@NotNull
private final Params params;
/*
**********************************************************************
*
* CONSTRUCTORS
*
**********************************************************************
*/
/*
**********************************************************************
*
* CONSTRUCTORS
*
**********************************************************************
*/
private MathEntityRemover(@NotNull T mathEntity,
@Nullable DialogInterface.OnClickListener callbackOnCancel,
boolean confirmed,
@NotNull CalculatorMathRegistry<? super T> varsRegistry,
@NotNull Context context,
@NotNull Object source,
@NotNull Params params) {
@Nullable DialogInterface.OnClickListener callbackOnCancel,
boolean confirmed,
@NotNull CalculatorMathRegistry<? super T> varsRegistry,
@NotNull Context context,
@NotNull Object source,
@NotNull Params params) {
this.mathEntity = mathEntity;
this.callbackOnCancel = callbackOnCancel;
this.confirmed = confirmed;
this.varsRegistry = varsRegistry;
this.context = context;
this.source = source;
this.params = params;
}
this.context = context;
this.source = source;
this.params = params;
}
public static MathEntityRemover<IConstant> newConstantRemover(@NotNull IConstant constant,
@Nullable DialogInterface.OnClickListener callbackOnCancel,
@NotNull Context context,
@NotNull Object source) {
return new MathEntityRemover<IConstant>(constant, callbackOnCancel, false, Locator.getInstance().getEngine().getVarsRegistry(), context, source, Params.newConstantInstance());
}
public static MathEntityRemover<IConstant> newConstantRemover(@NotNull IConstant constant,
@Nullable DialogInterface.OnClickListener callbackOnCancel,
@NotNull Context context,
@NotNull Object source) {
return new MathEntityRemover<IConstant>(constant, callbackOnCancel, false, Locator.getInstance().getEngine().getVarsRegistry(), context, source, Params.newConstantInstance());
}
public static MathEntityRemover<Function> newFunctionRemover(@NotNull Function function,
@Nullable DialogInterface.OnClickListener callbackOnCancel,
@NotNull Context context,
@NotNull Object source) {
return new MathEntityRemover<Function>(function, callbackOnCancel, false, Locator.getInstance().getEngine().getFunctionsRegistry(), context, source, Params.newFunctionInstance());
}
public static MathEntityRemover<Function> newFunctionRemover(@NotNull Function function,
@Nullable DialogInterface.OnClickListener callbackOnCancel,
@NotNull Context context,
@NotNull Object source) {
return new MathEntityRemover<Function>(function, callbackOnCancel, false, Locator.getInstance().getEngine().getFunctionsRegistry(), context, source, Params.newFunctionInstance());
}
/*
**********************************************************************
*
* METHODS
*
**********************************************************************
*/
/*
**********************************************************************
*
* METHODS
*
**********************************************************************
*/
public void showConfirmationDialog() {
final TextView question = new TextView(context);
question.setText(String.format(context.getString(params.getRemovalConfirmationQuestionResId()), mathEntity.getName()));
question.setPadding(6, 6, 6, 6);
final AlertDialog.Builder builder = new AlertDialog.Builder(context)
.setCancelable(true)
.setView(question)
.setTitle(params.getRemovalConfirmationTitleResId())
.setNegativeButton(R.string.c_no, callbackOnCancel)
.setPositiveButton(R.string.c_yes, new MathEntityRemover<T>(mathEntity, callbackOnCancel, true, varsRegistry, context, source, params));
public void showConfirmationDialog() {
final TextView question = new TextView(context);
question.setText(String.format(context.getString(params.getRemovalConfirmationQuestionResId()), mathEntity.getName()));
question.setPadding(6, 6, 6, 6);
final AlertDialog.Builder builder = new AlertDialog.Builder(context)
.setCancelable(true)
.setView(question)
.setTitle(params.getRemovalConfirmationTitleResId())
.setNegativeButton(R.string.c_no, callbackOnCancel)
.setPositiveButton(R.string.c_yes, new MathEntityRemover<T>(mathEntity, callbackOnCancel, true, varsRegistry, context, source, params));
builder.create().show();
}
builder.create().show();
}
@Override
public void onClick(@Nullable View v) {
if (!confirmed) {
showConfirmationDialog();
} else {
varsRegistry.remove(mathEntity);
varsRegistry.save();
@Override
public void onClick(@Nullable View v) {
if (!confirmed) {
showConfirmationDialog();
} else {
varsRegistry.remove(mathEntity);
varsRegistry.save();
Locator.getInstance().getCalculator().fireCalculatorEvent(params.getCalculatorEventType(), mathEntity, source);
}
}
Locator.getInstance().getCalculator().fireCalculatorEvent(params.getCalculatorEventType(), mathEntity, source);
}
}
@Override
public void onClick(DialogInterface dialog, int which) {
onClick(null);
}
@Override
public void onClick(DialogInterface dialog, int which) {
onClick(null);
}
/*
**********************************************************************
*
* STATIC
*
**********************************************************************
*/
/*
**********************************************************************
*
* STATIC
*
**********************************************************************
*/
private static final class Params {
private static final class Params {
private int removalConfirmationTitleResId;
private int removalConfirmationTitleResId;
private int removalConfirmationQuestionResId;
private int removalConfirmationQuestionResId;
private CalculatorEventType calculatorEventType;
private CalculatorEventType calculatorEventType;
private Params() {
}
private Params() {
}
public int getRemovalConfirmationTitleResId() {
return removalConfirmationTitleResId;
}
public int getRemovalConfirmationTitleResId() {
return removalConfirmationTitleResId;
}
public int getRemovalConfirmationQuestionResId() {
return removalConfirmationQuestionResId;
}
public int getRemovalConfirmationQuestionResId() {
return removalConfirmationQuestionResId;
}
public CalculatorEventType getCalculatorEventType() {
return calculatorEventType;
}
public CalculatorEventType getCalculatorEventType() {
return calculatorEventType;
}
private static <T extends MathEntity> Params newConstantInstance() {
final Params result = new Params();
result.removalConfirmationTitleResId = R.string.removal_confirmation;
result.removalConfirmationQuestionResId = R.string.c_var_removal_confirmation_question;
result.calculatorEventType = CalculatorEventType.constant_removed;
return result;
}
private static <T extends MathEntity> Params newConstantInstance() {
final Params result = new Params();
result.removalConfirmationTitleResId = R.string.removal_confirmation;
result.removalConfirmationQuestionResId = R.string.c_var_removal_confirmation_question;
result.calculatorEventType = CalculatorEventType.constant_removed;
return result;
}
private static <T extends MathEntity> Params newFunctionInstance() {
final Params result = new Params();
result.removalConfirmationTitleResId = R.string.removal_confirmation;
result.removalConfirmationQuestionResId = R.string.function_removal_confirmation_question;
result.calculatorEventType = CalculatorEventType.function_removed;
return result;
}
}
private static <T extends MathEntity> Params newFunctionInstance() {
final Params result = new Params();
result.removalConfirmationTitleResId = R.string.removal_confirmation;
result.removalConfirmationQuestionResId = R.string.function_removal_confirmation_question;
result.calculatorEventType = CalculatorEventType.function_removed;
return result;
}
}
}

View File

@@ -25,196 +25,196 @@ import org.solovyev.android.sherlock.AndroidSherlockUtils;
*/
public class VarEditDialogFragment extends DialogFragment implements CalculatorEventListener {
@NotNull
private final Input input;
@NotNull
private final Input input;
public VarEditDialogFragment() {
this(Input.newInstance());
}
public VarEditDialogFragment() {
this(Input.newInstance());
}
public VarEditDialogFragment(@NotNull Input input) {
this.input = input;
}
public VarEditDialogFragment(@NotNull Input input) {
this.input = input;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.var_edit, container, false);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.var_edit, container, false);
}
@Override
public void onResume() {
super.onResume();
@Override
public void onResume() {
super.onResume();
Locator.getInstance().getCalculator().addCalculatorEventListener(this);
}
Locator.getInstance().getCalculator().addCalculatorEventListener(this);
}
@Override
public void onPause() {
Locator.getInstance().getCalculator().removeCalculatorEventListener(this);
@Override
public void onPause() {
Locator.getInstance().getCalculator().removeCalculatorEventListener(this);
super.onPause();
}
super.onPause();
}
@Override
public void onViewCreated(@NotNull View root, Bundle savedInstanceState) {
super.onViewCreated(root, savedInstanceState);
@Override
public void onViewCreated(@NotNull View root, Bundle savedInstanceState) {
super.onViewCreated(root, savedInstanceState);
final String errorMsg = this.getString(R.string.c_char_is_not_accepted);
final String errorMsg = this.getString(R.string.c_char_is_not_accepted);
final EditText editName = (EditText) root.findViewById(R.id.var_edit_name);
editName.setText(input.getName());
editName.addTextChangedListener(new TextWatcher() {
final EditText editName = (EditText) root.findViewById(R.id.var_edit_name);
editName.setText(input.getName());
editName.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@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) {
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (!AbstractMathEntityListFragment.acceptableChars.contains(c)) {
s.delete(i, i + 1);
Toast.makeText(getActivity(), String.format(errorMsg, c), Toast.LENGTH_SHORT).show();
}
}
}
});
@Override
public void afterTextChanged(Editable s) {
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (!AbstractMathEntityListFragment.acceptableChars.contains(c)) {
s.delete(i, i + 1);
Toast.makeText(getActivity(), String.format(errorMsg, c), Toast.LENGTH_SHORT).show();
}
}
}
});
// show soft keyboard automatically
editName.requestFocus();
getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
// show soft keyboard automatically
editName.requestFocus();
getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
final EditText editValue = (EditText) root.findViewById(R.id.var_edit_value);
editValue.setText(input.getValue());
final EditText editValue = (EditText) root.findViewById(R.id.var_edit_value);
editValue.setText(input.getValue());
final EditText editDescription = (EditText) root.findViewById(R.id.var_edit_description);
editDescription.setText(input.getDescription());
final EditText editDescription = (EditText) root.findViewById(R.id.var_edit_description);
editDescription.setText(input.getDescription());
final Var.Builder varBuilder;
final IConstant constant = input.getConstant();
if (constant != null) {
varBuilder = new Var.Builder(constant);
} else {
varBuilder = new Var.Builder();
}
final Var.Builder varBuilder;
final IConstant constant = input.getConstant();
if (constant != null) {
varBuilder = new Var.Builder(constant);
} else {
varBuilder = new Var.Builder();
}
root.findViewById(R.id.cancel_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
}
});
root.findViewById(R.id.cancel_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
}
});
root.findViewById(R.id.save_button).setOnClickListener(new VarEditorSaver<IConstant>(varBuilder, constant, root, Locator.getInstance().getEngine().getVarsRegistry(), this));
root.findViewById(R.id.save_button).setOnClickListener(new VarEditorSaver<IConstant>(varBuilder, constant, root, Locator.getInstance().getEngine().getVarsRegistry(), this));
if ( constant == null ) {
// CREATE MODE
getDialog().setTitle(R.string.c_var_create_var);
if (constant == null) {
// CREATE MODE
getDialog().setTitle(R.string.c_var_create_var);
root.findViewById(R.id.remove_button).setVisibility(View.GONE);
} else {
// EDIT MODE
getDialog().setTitle(R.string.c_var_edit_var);
root.findViewById(R.id.remove_button).setVisibility(View.GONE);
} else {
// EDIT MODE
getDialog().setTitle(R.string.c_var_edit_var);
root.findViewById(R.id.remove_button).setOnClickListener(MathEntityRemover.newConstantRemover(constant, null, getActivity(), VarEditDialogFragment.this));
}
}
root.findViewById(R.id.remove_button).setOnClickListener(MathEntityRemover.newConstantRemover(constant, null, getActivity(), VarEditDialogFragment.this));
}
}
@Override
public void onCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
switch (calculatorEventType) {
case constant_removed:
case constant_added:
case constant_changed:
if ( calculatorEventData.getSource() == this ) {
dismiss();
}
break;
@Override
public void onCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable Object data) {
switch (calculatorEventType) {
case constant_removed:
case constant_added:
case constant_changed:
if (calculatorEventData.getSource() == this) {
dismiss();
}
break;
}
}
}
}
/*
**********************************************************************
*
* STATIC
*
**********************************************************************
*/
/*
**********************************************************************
*
* STATIC
*
**********************************************************************
*/
public static void showDialog(@NotNull Input input, @NotNull FragmentManager fm) {
AndroidSherlockUtils.showDialog(new VarEditDialogFragment(input), "constant-editor", fm);
}
public static void showDialog(@NotNull Input input, @NotNull FragmentManager fm) {
AndroidSherlockUtils.showDialog(new VarEditDialogFragment(input), "constant-editor", fm);
}
public static class Input {
public static class Input {
@Nullable
private IConstant constant;
@Nullable
private IConstant constant;
@Nullable
private String name;
@Nullable
private String name;
@Nullable
private String value;
@Nullable
private String value;
@Nullable
private String description;
@Nullable
private String description;
private Input() {
}
private Input() {
}
@NotNull
public static Input newInstance() {
return new Input();
}
@NotNull
public static Input newInstance() {
return new Input();
}
@NotNull
public static Input newFromConstant(@NotNull IConstant constant) {
final Input result = new Input();
result.constant = constant;
return result;
}
@NotNull
public static Input newFromConstant(@NotNull IConstant constant) {
final Input result = new Input();
result.constant = constant;
return result;
}
@NotNull
public static Input newFromValue(@Nullable String value) {
final Input result = new Input();
result.value = value;
return result;
}
@NotNull
public static Input newFromValue(@Nullable String value) {
final Input result = new Input();
result.value = value;
return result;
}
@NotNull
public static Input newInstance(@Nullable IConstant constant, @Nullable String name, @Nullable String value, @Nullable String description) {
final Input result = new Input();
result.constant = constant;
result.name = name;
result.value = value;
result.description = description;
return result;
}
@NotNull
public static Input newInstance(@Nullable IConstant constant, @Nullable String name, @Nullable String value, @Nullable String description) {
final Input result = new Input();
result.constant = constant;
result.name = name;
result.value = value;
result.description = description;
return result;
}
@Nullable
public IConstant getConstant() {
return constant;
}
@Nullable
public IConstant getConstant() {
return constant;
}
@Nullable
public String getName() {
return name == null ? (constant == null ? null : constant.getName()) : name;
}
@Nullable
public String getName() {
return name == null ? (constant == null ? null : constant.getName()) : name;
}
@Nullable
public String getValue() {
return value == null ? (constant == null ? null : constant.getValue()) : value;
}
@Nullable
public String getValue() {
return value == null ? (constant == null ? null : constant.getValue()) : value;
}
@Nullable
public String getDescription() {
return description == null ? (constant == null ? null : constant.getDescription()) : description;
}
}
@Nullable
public String getDescription() {
return description == null ? (constant == null ? null : constant.getDescription()) : description;
}
}
}

View File

@@ -14,9 +14,9 @@ import jscl.text.ParseException;
import jscl.text.Parser;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.android.calculator.Locator;
import org.solovyev.android.calculator.CalculatorMathRegistry;
import org.solovyev.android.calculator.CalculatorVarsRegistry;
import org.solovyev.android.calculator.Locator;
import org.solovyev.android.calculator.R;
import org.solovyev.android.calculator.math.MathType;
import org.solovyev.android.calculator.model.MathEntityBuilder;
@@ -40,90 +40,90 @@ public class VarEditorSaver<T extends MathEntity> implements View.OnClickListene
@NotNull
private final CalculatorMathRegistry<T> mathRegistry;
@NotNull
private final Object source;
@NotNull
private final Object source;
@NotNull
@NotNull
private View editView;
public VarEditorSaver(@NotNull MathEntityBuilder<? extends T> varBuilder,
@Nullable T editedInstance,
@NotNull View editView,
@NotNull CalculatorMathRegistry<T> mathRegistry,
@NotNull Object source) {
@Nullable T editedInstance,
@NotNull View editView,
@NotNull CalculatorMathRegistry<T> mathRegistry,
@NotNull Object source) {
this.varBuilder = varBuilder;
this.editedInstance = editedInstance;
this.editView = editView;
this.mathRegistry = mathRegistry;
this.source = source;
}
this.source = source;
}
@Override
public void onClick(View v) {
final Integer error;
@Override
public void onClick(View v) {
final Integer error;
final EditText editName = (EditText) editView.findViewById(R.id.var_edit_name);
String name = editName.getText().toString();
final EditText editName = (EditText) editView.findViewById(R.id.var_edit_name);
String name = editName.getText().toString();
final EditText editValue = (EditText) editView.findViewById(R.id.var_edit_value);
String value = editValue.getText().toString();
final EditText editValue = (EditText) editView.findViewById(R.id.var_edit_value);
String value = editValue.getText().toString();
final EditText editDescription = (EditText) editView.findViewById(R.id.var_edit_description);
String description = editDescription.getText().toString();
final EditText editDescription = (EditText) editView.findViewById(R.id.var_edit_description);
String description = editDescription.getText().toString();
if (isValidName(name)) {
if (isValidName(name)) {
boolean canBeSaved = false;
boolean canBeSaved = false;
final T entityFromRegistry = mathRegistry.get(name);
if (entityFromRegistry == null) {
canBeSaved = true;
} else if (editedInstance != null && entityFromRegistry.getId().equals(editedInstance.getId())) {
canBeSaved = true;
}
final T entityFromRegistry = mathRegistry.get(name);
if (entityFromRegistry == null) {
canBeSaved = true;
} else if (editedInstance != null && entityFromRegistry.getId().equals(editedInstance.getId())) {
canBeSaved = true;
}
if (canBeSaved) {
final MathType.Result mathType = MathType.getType(name, 0, false);
if (canBeSaved) {
final MathType.Result mathType = MathType.getType(name, 0, false);
if (mathType.getMathType() == MathType.text || mathType.getMathType() == MathType.constant) {
if (mathType.getMathType() == MathType.text || mathType.getMathType() == MathType.constant) {
if (Strings.isEmpty(value)) {
// value is empty => undefined variable
varBuilder.setName(name);
varBuilder.setDescription(description);
varBuilder.setValue(null);
error = null;
} else {
// value is not empty => must be a number
boolean valid = CalculatorVarsFragment.isValidValue(value);
if (Strings.isEmpty(value)) {
// value is empty => undefined variable
varBuilder.setName(name);
varBuilder.setDescription(description);
varBuilder.setValue(null);
error = null;
} else {
// value is not empty => must be a number
boolean valid = CalculatorVarsFragment.isValidValue(value);
if (valid) {
varBuilder.setName(name);
varBuilder.setDescription(description);
varBuilder.setValue(value);
error = null;
} else {
error = R.string.c_value_is_not_a_number;
}
}
} else {
error = R.string.c_var_name_clashes;
}
} else {
error = R.string.c_var_already_exists;
}
} else {
error = R.string.c_name_is_not_valid;
}
if (valid) {
varBuilder.setName(name);
varBuilder.setDescription(description);
varBuilder.setValue(value);
error = null;
} else {
error = R.string.c_value_is_not_a_number;
}
}
} else {
error = R.string.c_var_name_clashes;
}
} else {
error = R.string.c_var_already_exists;
}
} else {
error = R.string.c_name_is_not_valid;
}
if (error != null) {
Locator.getInstance().getNotifier().showMessage(error, MessageType.error);
} else {
CalculatorVarsRegistry.saveVariable(mathRegistry, varBuilder, editedInstance, source, true);
}
}
if (error != null) {
Locator.getInstance().getNotifier().showMessage(error, MessageType.error);
} else {
CalculatorVarsRegistry.saveVariable(mathRegistry, varBuilder, editedInstance, source, true);
}
}
public static boolean isValidName(@Nullable String name) {
public static boolean isValidName(@Nullable String name) {
boolean result = false;
if (!Strings.isEmpty(name)) {

View File

@@ -13,11 +13,11 @@ import org.solovyev.android.calculator.R;
*/
public class CalculatorMatrixActivity extends CalculatorFragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
getActivityHelper().setFragment(this, CalculatorFragmentType.matrix_edit, null, R.id.main_layout);
}
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
getActivityHelper().setFragment(this, CalculatorFragmentType.matrix_edit, null, R.id.main_layout);
}
}

View File

@@ -19,119 +19,119 @@ import java.io.Serializable;
*/
public class CalculatorMatrixEditFragment extends CalculatorFragment implements Picker.OnChangedListener<Integer> {
/*
**********************************************************************
*
* CONSTANTS
*
**********************************************************************
*/
/*
**********************************************************************
*
* CONSTANTS
*
**********************************************************************
*/
private static final int MAX_COUNT = 10;
private static final int MIN_COUNT = 2;
private static final int DEFAULT_ROWS = 2;
private static final int DEFAULT_COLS = 2;
private static final int MAX_COUNT = 10;
private static final int MIN_COUNT = 2;
private static final int DEFAULT_ROWS = 2;
private static final int DEFAULT_COLS = 2;
private static final String MATRIX = "matrix";
private static final String MATRIX = "matrix";
/*
**********************************************************************
*
* CONSTRUCTORS
*
**********************************************************************
*/
/*
**********************************************************************
*
* CONSTRUCTORS
*
**********************************************************************
*/
public CalculatorMatrixEditFragment() {
super(CalculatorFragmentType.matrix_edit);
public CalculatorMatrixEditFragment() {
super(CalculatorFragmentType.matrix_edit);
setRetainInstance(true);
}
setRetainInstance(true);
}
/*
**********************************************************************
*
* METHODS
*
**********************************************************************
*/
/*
**********************************************************************
*
* METHODS
*
**********************************************************************
*/
@Override
public void onViewCreated(View root, @Nullable Bundle in) {
super.onViewCreated(root, in);
@Override
public void onViewCreated(View root, @Nullable Bundle in) {
super.onViewCreated(root, in);
final Picker<Integer> matrixRowsCountPicker = (Picker<Integer>) root.findViewById(R.id.matrix_rows_count_picker);
initPicker(matrixRowsCountPicker);
final Picker<Integer> matrixColsCountPicker = (Picker<Integer>) root.findViewById(R.id.matrix_cols_count_picker);
initPicker(matrixColsCountPicker);
final Picker<Integer> matrixRowsCountPicker = (Picker<Integer>) root.findViewById(R.id.matrix_rows_count_picker);
initPicker(matrixRowsCountPicker);
final Picker<Integer> matrixColsCountPicker = (Picker<Integer>) root.findViewById(R.id.matrix_cols_count_picker);
initPicker(matrixColsCountPicker);
Matrix matrix = null;
if (in != null) {
final Object matrixObject = in.getSerializable(MATRIX);
if (matrixObject instanceof Matrix) {
matrix = (Matrix) matrixObject;
}
}
Matrix matrix = null;
if (in != null) {
final Object matrixObject = in.getSerializable(MATRIX);
if (matrixObject instanceof Matrix) {
matrix = (Matrix) matrixObject;
}
}
final MatrixView matrixView = getMatrixView(root);
if (matrix == null) {
matrixView.setMatrixDimensions(DEFAULT_ROWS, DEFAULT_COLS);
} else {
matrixView.setMatrix(matrix.bakingArray);
}
matrixRowsCountPicker.setCurrent(matrixView.getRows());
matrixColsCountPicker.setCurrent(matrixView.getCols());
}
final MatrixView matrixView = getMatrixView(root);
if (matrix == null) {
matrixView.setMatrixDimensions(DEFAULT_ROWS, DEFAULT_COLS);
} else {
matrixView.setMatrix(matrix.bakingArray);
}
matrixRowsCountPicker.setCurrent(matrixView.getRows());
matrixColsCountPicker.setCurrent(matrixView.getCols());
}
@Override
public void onSaveInstanceState(@NotNull Bundle out) {
super.onSaveInstanceState(out);
@Override
public void onSaveInstanceState(@NotNull Bundle out) {
super.onSaveInstanceState(out);
out.putSerializable(MATRIX, new Matrix(getMatrixView(getView()).toMatrix()));
}
out.putSerializable(MATRIX, new Matrix(getMatrixView(getView()).toMatrix()));
}
@NotNull
private MatrixView getMatrixView(@NotNull View root) {
return (MatrixView) root.findViewById(R.id.matrix_layout);
}
@NotNull
private MatrixView getMatrixView(@NotNull View root) {
return (MatrixView) root.findViewById(R.id.matrix_layout);
}
private void initPicker(@NotNull Picker<Integer> picker) {
picker.setRange(new IntegerRange(MIN_COUNT, MAX_COUNT, 1, 0, null));
picker.setOnChangeListener(this);
}
private void initPicker(@NotNull Picker<Integer> picker) {
picker.setRange(new IntegerRange(MIN_COUNT, MAX_COUNT, 1, 0, null));
picker.setOnChangeListener(this);
}
@Override
public void onChanged(@NotNull Picker picker, @NotNull Integer value) {
switch (picker.getId()) {
case R.id.matrix_rows_count_picker:
onRowsCountChange(value);
break;
case R.id.matrix_cols_count_picker:
onColsCountChange(value);
break;
}
}
@Override
public void onChanged(@NotNull Picker picker, @NotNull Integer value) {
switch (picker.getId()) {
case R.id.matrix_rows_count_picker:
onRowsCountChange(value);
break;
case R.id.matrix_cols_count_picker:
onColsCountChange(value);
break;
}
}
private void onColsCountChange(@NotNull Integer newCols) {
getMatrixView(getView()).setMatrixCols(newCols);
}
private void onColsCountChange(@NotNull Integer newCols) {
getMatrixView(getView()).setMatrixCols(newCols);
}
private void onRowsCountChange(@NotNull Integer newRows) {
getMatrixView(getView()).setMatrixRows(newRows);
}
private void onRowsCountChange(@NotNull Integer newRows) {
getMatrixView(getView()).setMatrixRows(newRows);
}
public static class Matrix implements Serializable {
public static class Matrix implements Serializable {
@NotNull
private String[][] bakingArray;
@NotNull
private String[][] bakingArray;
public Matrix() {
}
public Matrix() {
}
public Matrix(@NotNull String[][] bakingArray) {
this.bakingArray = bakingArray;
}
}
public Matrix(@NotNull String[][] bakingArray) {
this.bakingArray = bakingArray;
}
}
}

View File

@@ -18,272 +18,272 @@ import org.jetbrains.annotations.Nullable;
*/
public class MatrixView extends TableLayout {
/*
**********************************************************************
*
* CONSTANTS
*
**********************************************************************
*/
/*
**********************************************************************
*
* CONSTANTS
*
**********************************************************************
*/
private static final CharSequence DEFAULT_CELL_TEXT = "0";
private static final int NUMBER_INDEX = -1;
private static final CharSequence DEFAULT_CELL_TEXT = "0";
private static final int NUMBER_INDEX = -1;
/*
**********************************************************************
*
* FIELDS
*
**********************************************************************
*/
/*
**********************************************************************
*
* FIELDS
*
**********************************************************************
*/
private int rows = 0;
private int cols = 0;
private int rows = 0;
private int cols = 0;
@Nullable
private CharSequence defaultCellText = DEFAULT_CELL_TEXT;
@Nullable
private CharSequence defaultCellText = DEFAULT_CELL_TEXT;
private boolean initialized = false;
private boolean initialized = false;
/*
**********************************************************************
*
* CONSTRUCTORS
*
**********************************************************************
*/
/*
**********************************************************************
*
* CONSTRUCTORS
*
**********************************************************************
*/
public MatrixView(Context context) {
super(context);
}
public MatrixView(Context context) {
super(context);
}
public MatrixView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MatrixView(Context context, AttributeSet attrs) {
super(context, attrs);
}
/*
**********************************************************************
*
* METHODS
*
**********************************************************************
*/
/*
**********************************************************************
*
* METHODS
*
**********************************************************************
*/
public int getRows() {
return rows;
}
public int getRows() {
return rows;
}
public int getCols() {
return cols;
}
public int getCols() {
return cols;
}
public void setMatrixCols(int newCols) {
setMatrixDimensions(rows, newCols);
}
public void setMatrixCols(int newCols) {
setMatrixDimensions(rows, newCols);
}
public void setMatrixRows(int newRows) {
setMatrixDimensions(newRows, cols);
}
public void setMatrixRows(int newRows) {
setMatrixDimensions(newRows, cols);
}
public void setMatrixDimensions(int newRows, int newCols) {
if (newRows <= 1) {
throw new IllegalArgumentException("Number of rows must be more than 1: " + newRows);
}
public void setMatrixDimensions(int newRows, int newCols) {
if (newRows <= 1) {
throw new IllegalArgumentException("Number of rows must be more than 1: " + newRows);
}
if (newCols <= 1) {
throw new IllegalArgumentException("Number of columns must be more than 1: " + newCols);
}
if (newCols <= 1) {
throw new IllegalArgumentException("Number of columns must be more than 1: " + newCols);
}
boolean rowsChanged = this.rows != newRows;
boolean colsChanged = this.cols != newCols;
boolean rowsChanged = this.rows != newRows;
boolean colsChanged = this.cols != newCols;
if (rowsChanged || colsChanged) {
if (!initialized) {
addRow(NUMBER_INDEX, 0);
initialized = true;
}
if (rowsChanged || colsChanged) {
if (!initialized) {
addRow(NUMBER_INDEX, 0);
initialized = true;
}
if (this.cols > newCols) {
removeCols(newCols);
} else if (this.cols < newCols) {
addCols(newCols);
}
if (this.cols > newCols) {
removeCols(newCols);
} else if (this.cols < newCols) {
addCols(newCols);
}
this.cols = newCols;
this.cols = newCols;
if (this.rows > newRows) {
removeRows(newRows);
} else if (this.rows < newRows) {
addRows(newRows);
}
if (this.rows > newRows) {
removeRows(newRows);
} else if (this.rows < newRows) {
addRows(newRows);
}
this.rows = newRows;
}
}
this.rows = newRows;
}
}
public void setMatrix(@NotNull Object[][] matrix) {
final int rows = matrix.length;
final int cols = matrix[0].length;
public void setMatrix(@NotNull Object[][] matrix) {
final int rows = matrix.length;
final int cols = matrix[0].length;
setMatrixDimensions(rows, cols);
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
setCell(row, col, matrix[row][col]);
}
}
}
setMatrixDimensions(rows, cols);
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
setCell(row, col, matrix[row][col]);
}
}
}
@NotNull
public String[][] toMatrix() {
final String[][] result = new String[rows][cols];
@NotNull
public String[][] toMatrix() {
final String[][] result = new String[rows][cols];
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
final TextView cellTextView = (TextView) getCell(this, row, col);
if (cellTextView != null) {
result[row][col] = cellTextView.getText().toString();
}
}
}
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
final TextView cellTextView = (TextView) getCell(this, row, col);
if (cellTextView != null) {
result[row][col] = cellTextView.getText().toString();
}
}
}
return result;
}
return result;
}
private void setCell(int row, int col, @Nullable Object o) {
final TextView cellTextView = (TextView) getCell(this, row, col);
if (cellTextView != null) {
if (o == null) {
cellTextView.setText(null);
} else {
cellTextView.setText(String.valueOf(o));
}
}
}
private void setCell(int row, int col, @Nullable Object o) {
final TextView cellTextView = (TextView) getCell(this, row, col);
if (cellTextView != null) {
if (o == null) {
cellTextView.setText(null);
} else {
cellTextView.setText(String.valueOf(o));
}
}
}
/*
**********************************************************************
*
* PRIVATE METHODS
*
**********************************************************************
*/
/*
**********************************************************************
*
* PRIVATE METHODS
*
**********************************************************************
*/
private void addRows(int newRows) {
for (int row = this.rows; row < newRows; row++) {
addRow(row, cols);
}
}
private void addRows(int newRows) {
for (int row = this.rows; row < newRows; row++) {
addRow(row, cols);
}
}
private void removeRows(int newRows) {
for (int row = this.rows - 1; row >= newRows; row--) {
removeRow(row);
}
}
private void removeRows(int newRows) {
for (int row = this.rows - 1; row >= newRows; row--) {
removeRow(row);
}
}
private void addCols(int newCols) {
for (int row = NUMBER_INDEX; row < rows; row++) {
final ViewGroup rowView = getRow(row);
if (rowView != null) {
for (int col = this.cols; col < newCols; col++) {
rowView.addView(createCellView(row, col));
}
}
}
}
private void addCols(int newCols) {
for (int row = NUMBER_INDEX; row < rows; row++) {
final ViewGroup rowView = getRow(row);
if (rowView != null) {
for (int col = this.cols; col < newCols; col++) {
rowView.addView(createCellView(row, col));
}
}
}
}
private void removeCols(int newCols) {
for (int row = NUMBER_INDEX; row < rows; row++) {
final ViewGroup rowView = getRow(row);
if (rowView != null) {
for (int col = this.cols - 1; col >= newCols; col--) {
final View cellView = getCell(rowView, row, col);
if (cellView != null) {
rowView.removeView(cellView);
}
}
}
}
}
private void removeCols(int newCols) {
for (int row = NUMBER_INDEX; row < rows; row++) {
final ViewGroup rowView = getRow(row);
if (rowView != null) {
for (int col = this.cols - 1; col >= newCols; col--) {
final View cellView = getCell(rowView, row, col);
if (cellView != null) {
rowView.removeView(cellView);
}
}
}
}
}
private void addRow(int row, int newCols) {
this.addView(createRowView(row, newCols));
}
private void addRow(int row, int newCols) {
this.addView(createRowView(row, newCols));
}
private void removeRow(int row) {
final View rowView = getRow(row);
if (rowView != null) {
this.removeView(rowView);
}
}
private void removeRow(int row) {
final View rowView = getRow(row);
if (rowView != null) {
this.removeView(rowView);
}
}
@Nullable
private TableRow getRow(int row) {
return (TableRow) this.findViewWithTag(getRowTag(row));
}
@Nullable
private TableRow getRow(int row) {
return (TableRow) this.findViewWithTag(getRowTag(row));
}
@Nullable
private View getCell(@NotNull View view, int row, int col) {
return view.findViewWithTag(getCellTag(row, col));
}
@Nullable
private View getCell(@NotNull View view, int row, int col) {
return view.findViewWithTag(getCellTag(row, col));
}
@NotNull
private String getRowTag(int row) {
if (row != NUMBER_INDEX) {
return "row_" + row;
} else {
return "row_index";
}
}
@NotNull
private String getRowTag(int row) {
if (row != NUMBER_INDEX) {
return "row_" + row;
} else {
return "row_index";
}
}
@NotNull
private View createRowView(int row, int cols) {
final ViewGroup rowView = new TableRow(this.getContext());
@NotNull
private View createRowView(int row, int cols) {
final ViewGroup rowView = new TableRow(this.getContext());
rowView.setTag(getRowTag(row));
rowView.setTag(getRowTag(row));
if (row != NUMBER_INDEX) {
rowView.addView(createCellView(row, NUMBER_INDEX));
} else {
// empty cell
rowView.addView(new View(this.getContext()));
}
if (row != NUMBER_INDEX) {
rowView.addView(createCellView(row, NUMBER_INDEX));
} else {
// empty cell
rowView.addView(new View(this.getContext()));
}
for (int col = 0; col < cols; col++) {
rowView.addView(createCellView(row, col));
}
return rowView;
}
for (int col = 0; col < cols; col++) {
rowView.addView(createCellView(row, col));
}
return rowView;
}
@NotNull
private View createCellView(int row, int col) {
final TextView result;
@NotNull
private View createCellView(int row, int col) {
final TextView result;
if (row != NUMBER_INDEX && col != NUMBER_INDEX) {
result = new EditText(this.getContext());
result.setText(defaultCellText);
} else {
result = new TextView(this.getContext());
if (row == NUMBER_INDEX) {
result.setText(String.valueOf(col + 1));
} else {
result.setText(String.valueOf(row + 1));
}
}
if (row != NUMBER_INDEX && col != NUMBER_INDEX) {
result = new EditText(this.getContext());
result.setText(defaultCellText);
} else {
result = new TextView(this.getContext());
if (row == NUMBER_INDEX) {
result.setText(String.valueOf(col + 1));
} else {
result.setText(String.valueOf(row + 1));
}
}
result.setTag(getCellTag(row, col));
result.setTag(getCellTag(row, col));
return result;
return result;
}
}
@NotNull
private String getCellTag(int row, int col) {
if (row != NUMBER_INDEX) {
return "cell_" + row + "_" + col;
} else {
return "cell_index_" + col;
}
}
@NotNull
private String getCellTag(int row, int col) {
if (row != NUMBER_INDEX) {
return "cell_" + row + "_" + col;
} else {
return "cell_index_" + col;
}
}
}

View File

@@ -44,116 +44,116 @@ import java.util.concurrent.Executors;
*/
public abstract class AbstractCalculatorPlotFragment extends CalculatorFragment implements CalculatorEventListener, SharedPreferences.OnSharedPreferenceChangeListener {
/*
**********************************************************************
*
* CONSTANTS
*
**********************************************************************
*/
/*
**********************************************************************
*
* CONSTANTS
*
**********************************************************************
*/
protected static final String TAG = "CalculatorPlotFragment";
protected static final String TAG = "CalculatorPlotFragment";
/*
**********************************************************************
*
* FIELDS
*
**********************************************************************
*/
/*
**********************************************************************
*
* FIELDS
*
**********************************************************************
*/
private int bgColor;
@NotNull
private PlotData plotData = new PlotData(Collections.<PlotFunction>emptyList(), false, PlotBoundaries.newDefaultInstance());
private int bgColor;
@NotNull
private ActivityMenu<Menu, MenuItem> fragmentMenu;
private PlotData plotData = new PlotData(Collections.<PlotFunction>emptyList(), false, PlotBoundaries.newDefaultInstance());
// thread which calculated data for graph view
@NotNull
private final Executor plotExecutor = Executors.newSingleThreadExecutor();
@NotNull
private ActivityMenu<Menu, MenuItem> fragmentMenu;
@NotNull
private final CalculatorEventHolder lastEventHolder = new CalculatorEventHolder(CalculatorUtils.createFirstEventDataId());
// thread which calculated data for graph view
@NotNull
private final Executor plotExecutor = Executors.newSingleThreadExecutor();
@NotNull
private final CalculatorEventHolder lastEventHolder = new CalculatorEventHolder(CalculatorUtils.createFirstEventDataId());
public AbstractCalculatorPlotFragment() {
super(CalculatorApplication.getInstance().createFragmentHelper(R.layout.cpp_plot_fragment, R.string.c_graph, false));
}
public AbstractCalculatorPlotFragment() {
super(CalculatorApplication.getInstance().createFragmentHelper(R.layout.cpp_plot_fragment, R.string.c_graph, false));
}
@Override
public void onCreate(@Nullable Bundle in) {
super.onCreate(in);
@Override
public void onCreate(@Nullable Bundle in) {
super.onCreate(in);
if (isPaneFragment()) {
this.bgColor = getResources().getColor(R.color.cpp_pane_background);
} else {
this.bgColor = getResources().getColor(android.R.color.transparent);
}
if (isPaneFragment()) {
this.bgColor = getResources().getColor(R.color.cpp_pane_background);
} else {
this.bgColor = getResources().getColor(android.R.color.transparent);
}
setHasOptionsMenu(true);
}
}
private void savePlotBoundaries() {
final PlotBoundaries plotBoundaries = getPlotBoundaries();
if (plotBoundaries != null) {
Locator.getInstance().getPlotter().savePlotBoundaries(plotBoundaries);
}
}
private void savePlotBoundaries() {
final PlotBoundaries plotBoundaries = getPlotBoundaries();
if (plotBoundaries != null) {
Locator.getInstance().getPlotter().savePlotBoundaries(plotBoundaries);
}
}
@Nullable
protected abstract PlotBoundaries getPlotBoundaries();
@Nullable
protected abstract PlotBoundaries getPlotBoundaries();
@Override
public void onPause() {
PreferenceManager.getDefaultSharedPreferences(this.getActivity()).unregisterOnSharedPreferenceChangeListener(this);
@Override
public void onPause() {
PreferenceManager.getDefaultSharedPreferences(this.getActivity()).unregisterOnSharedPreferenceChangeListener(this);
savePlotBoundaries();
savePlotBoundaries();
super.onPause();
}
super.onPause();
}
@Override
public void onResume() {
super.onResume();
@Override
public void onResume() {
super.onResume();
PreferenceManager.getDefaultSharedPreferences(this.getActivity()).registerOnSharedPreferenceChangeListener(this);
PreferenceManager.getDefaultSharedPreferences(this.getActivity()).registerOnSharedPreferenceChangeListener(this);
plotData = Locator.getInstance().getPlotter().getPlotData();
updateChart(plotData, getSherlockActivity());
}
plotData = Locator.getInstance().getPlotter().getPlotData();
updateChart(plotData, getSherlockActivity());
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (AndroidCalculatorEngine.Preferences.angleUnit.getKey().equals(key)) {
updateChart(this.plotData, getSherlockActivity());
}
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (AndroidCalculatorEngine.Preferences.angleUnit.getKey().equals(key)) {
updateChart(this.plotData, getSherlockActivity());
}
}
@Override
public void onCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable final Object data) {
switch (calculatorEventType) {
case plot_data_changed:
final CalculatorEventHolder.Result result = this.lastEventHolder.apply(calculatorEventData);
if (result.isNewAfter()) {
onNewPlotData((PlotData) data);
}
break;
}
@Override
public void onCalculatorEvent(@NotNull CalculatorEventData calculatorEventData, @NotNull CalculatorEventType calculatorEventType, @Nullable final Object data) {
switch (calculatorEventType) {
case plot_data_changed:
final CalculatorEventHolder.Result result = this.lastEventHolder.apply(calculatorEventData);
if (result.isNewAfter()) {
onNewPlotData((PlotData) data);
}
break;
}
}
}
private void onNewPlotData(@NotNull final PlotData plotData) {
this.plotData = plotData;
private void onNewPlotData(@NotNull final PlotData plotData) {
this.plotData = plotData;
final SherlockFragmentActivity activity = getSherlockActivity();
updateChart(plotData, activity);
}
final SherlockFragmentActivity activity = getSherlockActivity();
updateChart(plotData, activity);
}
private void updateChart(@NotNull final PlotData plotData, @Nullable final SherlockFragmentActivity activity) {
Threads.tryRunOnUiThread(activity, new Runnable() {
private void updateChart(@NotNull final PlotData plotData, @Nullable final SherlockFragmentActivity activity) {
Threads.tryRunOnUiThread(activity, new Runnable() {
@Override
public void run() {
createChart(plotData);
@@ -166,95 +166,95 @@ public abstract class AbstractCalculatorPlotFragment extends CalculatorFragment
activity.invalidateOptionsMenu();
}
});
}
}
protected abstract void onError();
protected abstract void onError();
protected abstract void createGraphicalView(@NotNull View view, @NotNull PlotData plotData);
protected abstract void createGraphicalView(@NotNull View view, @NotNull PlotData plotData);
protected abstract void createChart(@NotNull PlotData plotData);
protected abstract void createChart(@NotNull PlotData plotData);
/*
**********************************************************************
*
* GETTERS
*
**********************************************************************
*/
/*
**********************************************************************
*
* GETTERS
*
**********************************************************************
*/
public int getBgColor() {
return bgColor;
}
public int getBgColor() {
return bgColor;
}
@NotNull
public Executor getPlotExecutor() {
return plotExecutor;
}
@NotNull
public Executor getPlotExecutor() {
return plotExecutor;
}
/*
**********************************************************************
*
* MENU
*
**********************************************************************
*/
/*
**********************************************************************
*
* MENU
*
**********************************************************************
*/
@Override
public void onCreateOptionsMenu(final Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
@Override
public void onCreateOptionsMenu(final Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
final List<IdentifiableMenuItem<MenuItem>> menuItems = new ArrayList<IdentifiableMenuItem<MenuItem>>();
menuItems.add(PlotMenu.preferences);
menuItems.add(PlotMenu.functions);
final List<IdentifiableMenuItem<MenuItem>> menuItems = new ArrayList<IdentifiableMenuItem<MenuItem>>();
menuItems.add(PlotMenu.preferences);
menuItems.add(PlotMenu.functions);
final IdentifiableMenuItem<MenuItem> plotRangeMenuItem = new IdentifiableMenuItem<MenuItem>() {
@NotNull
@Override
public Integer getItemId() {
return R.id.menu_plot_range;
}
final IdentifiableMenuItem<MenuItem> plotRangeMenuItem = new IdentifiableMenuItem<MenuItem>() {
@NotNull
@Override
public Integer getItemId() {
return R.id.menu_plot_range;
}
@Override
public void onClick(@NotNull MenuItem data, @NotNull Context context) {
savePlotBoundaries();
@Override
public void onClick(@NotNull MenuItem data, @NotNull Context context) {
savePlotBoundaries();
context.startActivity(new Intent(context, CalculatorPlotRangeActivity.class));
}
};
menuItems.add(plotRangeMenuItem);
context.startActivity(new Intent(context, CalculatorPlotRangeActivity.class));
}
};
menuItems.add(plotRangeMenuItem);
final IdentifiableMenuItem<MenuItem> plot3dMenuItem = new IdentifiableMenuItem<MenuItem>() {
@NotNull
@Override
public Integer getItemId() {
return R.id.menu_plot_3d;
}
final IdentifiableMenuItem<MenuItem> plot3dMenuItem = new IdentifiableMenuItem<MenuItem>() {
@NotNull
@Override
public Integer getItemId() {
return R.id.menu_plot_3d;
}
@Override
public void onClick(@NotNull MenuItem data, @NotNull Context context) {
savePlotBoundaries();
@Override
public void onClick(@NotNull MenuItem data, @NotNull Context context) {
savePlotBoundaries();
Locator.getInstance().getPlotter().setPlot3d(true);
}
};
menuItems.add(plot3dMenuItem);
Locator.getInstance().getPlotter().setPlot3d(true);
}
};
menuItems.add(plot3dMenuItem);
final IdentifiableMenuItem<MenuItem> plot2dMenuItem = new IdentifiableMenuItem<MenuItem>() {
@NotNull
@Override
public Integer getItemId() {
return R.id.menu_plot_2d;
}
final IdentifiableMenuItem<MenuItem> plot2dMenuItem = new IdentifiableMenuItem<MenuItem>() {
@NotNull
@Override
public Integer getItemId() {
return R.id.menu_plot_2d;
}
@Override
public void onClick(@NotNull MenuItem data, @NotNull Context context) {
savePlotBoundaries();
@Override
public void onClick(@NotNull MenuItem data, @NotNull Context context) {
savePlotBoundaries();
Locator.getInstance().getPlotter().setPlot3d(false);
}
};
menuItems.add(plot2dMenuItem);
Locator.getInstance().getPlotter().setPlot3d(false);
}
};
menuItems.add(plot2dMenuItem);
final IdentifiableMenuItem<MenuItem> captureScreenshotMenuItem = new IdentifiableMenuItem<MenuItem>() {
@NotNull
@@ -270,32 +270,32 @@ public abstract class AbstractCalculatorPlotFragment extends CalculatorFragment
};
menuItems.add(captureScreenshotMenuItem);
final boolean plotRangeVisible = !plotData.isPlot3d();
final boolean plot3dVisible = !plotData.isPlot3d() && is3dPlotSupported();
final boolean plot2dVisible = plotData.isPlot3d() && Locator.getInstance().getPlotter().is2dPlotPossible();
final boolean captureScreenshotVisible = isScreenshotSupported();
fragmentMenu = ListActivityMenu.fromResource(R.menu.plot_menu, menuItems, SherlockMenuHelper.getInstance(), new JPredicate<AMenuItem<MenuItem>>() {
@Override
public boolean apply(@Nullable AMenuItem<MenuItem> menuItem) {
if ( menuItem == plot3dMenuItem ) {
return !plot3dVisible;
} else if ( menuItem == plot2dMenuItem ) {
return !plot2dVisible;
} else if ( menuItem == captureScreenshotMenuItem ) {
final boolean plotRangeVisible = !plotData.isPlot3d();
final boolean plot3dVisible = !plotData.isPlot3d() && is3dPlotSupported();
final boolean plot2dVisible = plotData.isPlot3d() && Locator.getInstance().getPlotter().is2dPlotPossible();
final boolean captureScreenshotVisible = isScreenshotSupported();
fragmentMenu = ListActivityMenu.fromResource(R.menu.plot_menu, menuItems, SherlockMenuHelper.getInstance(), new JPredicate<AMenuItem<MenuItem>>() {
@Override
public boolean apply(@Nullable AMenuItem<MenuItem> menuItem) {
if (menuItem == plot3dMenuItem) {
return !plot3dVisible;
} else if (menuItem == plot2dMenuItem) {
return !plot2dVisible;
} else if (menuItem == captureScreenshotMenuItem) {
return !captureScreenshotVisible;
} else if ( menuItem == plotRangeMenuItem ) {
return !plotRangeVisible;
}
} else if (menuItem == plotRangeMenuItem) {
return !plotRangeVisible;
}
return false;
}
});
return false;
}
});
final FragmentActivity activity = this.getActivity();
if (activity != null) {
fragmentMenu.onCreateOptionsMenu(activity, menu);
}
}
final FragmentActivity activity = this.getActivity();
if (activity != null) {
fragmentMenu.onCreateOptionsMenu(activity, menu);
}
}
protected abstract boolean isScreenshotSupported();
@@ -303,7 +303,7 @@ public abstract class AbstractCalculatorPlotFragment extends CalculatorFragment
protected abstract Bitmap getScreehshot();
private void captureScreehshot() {
if ( isScreenshotSupported() ) {
if (isScreenshotSupported()) {
final Bitmap screenshot = getScreehshot();
final String screenShotFileName = generateScreenshotFileName();
final File externalFilesDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
@@ -326,69 +326,69 @@ public abstract class AbstractCalculatorPlotFragment extends CalculatorFragment
protected abstract boolean is3dPlotSupported();
@Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
@Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
final FragmentActivity activity = this.getActivity();
if (activity != null) {
fragmentMenu.onPrepareOptionsMenu(activity, menu);
}
}
final FragmentActivity activity = this.getActivity();
if (activity != null) {
fragmentMenu.onPrepareOptionsMenu(activity, menu);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item) || fragmentMenu.onOptionsItemSelected(this.getActivity(), item);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item) || fragmentMenu.onOptionsItemSelected(this.getActivity(), item);
}
/*
**********************************************************************
*
* STATIC
*
**********************************************************************
*/
/*
**********************************************************************
*
* STATIC
*
**********************************************************************
*/
private static enum PlotMenu implements IdentifiableMenuItem<MenuItem> {
private static enum PlotMenu implements IdentifiableMenuItem<MenuItem> {
functions(R.id.menu_plot_functions) {
@Override
public void onClick(@NotNull MenuItem data, @NotNull Context context) {
context.startActivity(new Intent(context, CalculatorPlotFunctionsActivity.class));
}
},
functions(R.id.menu_plot_functions) {
@Override
public void onClick(@NotNull MenuItem data, @NotNull Context context) {
context.startActivity(new Intent(context, CalculatorPlotFunctionsActivity.class));
}
},
preferences(R.id.menu_plot_settings) {
@Override
public void onClick(@NotNull MenuItem data, @NotNull Context context) {
context.startActivity(new Intent(context, CalculatorPlotPreferenceActivity.class));
}
};
preferences(R.id.menu_plot_settings) {
@Override
public void onClick(@NotNull MenuItem data, @NotNull Context context) {
context.startActivity(new Intent(context, CalculatorPlotPreferenceActivity.class));
}
};
private final int itemId;
private final int itemId;
private PlotMenu(int itemId) {
this.itemId = itemId;
}
private PlotMenu(int itemId) {
this.itemId = itemId;
}
@NotNull
@Override
public Integer getItemId() {
return itemId;
}
}
@NotNull
@Override
public Integer getItemId() {
return itemId;
}
}
public static void applyToPaint(@NotNull PlotLineDef plotLineDef, @NotNull Paint paint) {
paint.setColor(plotLineDef.getLineColor());
paint.setStyle(Paint.Style.STROKE);
public static void applyToPaint(@NotNull PlotLineDef plotLineDef, @NotNull Paint paint) {
paint.setColor(plotLineDef.getLineColor());
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(plotLineDef.getLineWidth());
paint.setStrokeWidth(plotLineDef.getLineWidth());
final AndroidPlotLineStyle androidPlotLineStyle = AndroidPlotLineStyle.valueOf(plotLineDef.getLineStyle());
if (androidPlotLineStyle != null) {
androidPlotLineStyle.applyToPaint(paint);
}
}
final AndroidPlotLineStyle androidPlotLineStyle = AndroidPlotLineStyle.valueOf(plotLineDef.getLineStyle());
if (androidPlotLineStyle != null) {
androidPlotLineStyle.applyToPaint(paint);
}
}
}

View File

@@ -9,98 +9,98 @@ import org.jetbrains.annotations.NotNull;
*/
public abstract class AbstractGraphCalculator implements GraphCalculator {
@NotNull
protected final GraphData next = GraphData.newEmptyInstance();
@NotNull
protected final GraphData next = GraphData.newEmptyInstance();
@NotNull
private final GraphData endGraph = GraphData.newEmptyInstance();
@NotNull
private final GraphData endGraph = GraphData.newEmptyInstance();
@NotNull
private final GraphData startGraph = GraphData.newEmptyInstance();
@NotNull
private final GraphData startGraph = GraphData.newEmptyInstance();
@Override
public final void computeGraph(@NotNull XyFunction f,
float xMin,
float xMax,
@NotNull GraphData graph,
@NotNull GraphsData graphsData,
@NotNull Graph2dDimensions dimensions) {
if (f.getArity() == 0) {
final float v = (float) f.eval();
graph.clear();
graph.push(xMin, v);
graph.push(xMax, v);
return;
}
@Override
public final void computeGraph(@NotNull XyFunction f,
float xMin,
float xMax,
@NotNull GraphData graph,
@NotNull GraphsData graphsData,
@NotNull Graph2dDimensions dimensions) {
if (f.getArity() == 0) {
final float v = (float) f.eval();
graph.clear();
graph.push(xMin, v);
graph.push(xMax, v);
return;
}
float yMin = graphsData.getLastYMin();
float yMax = graphsData.getLastYMax();
float yMin = graphsData.getLastYMin();
float yMax = graphsData.getLastYMax();
// prepare graph
if (!graph.empty()) {
if (xMin >= graphsData.getLastXMin()) {
// |------[---erased---|------data----|---erased--]------ old data
// |-------------------[------data----]------------------ new data
// xMin xMax
//
// OR
//
// |------[---erased---|------data----]----------- old data
// |-------------------[------data----<---->]----- new data
// xMin xMax
graph.eraseBefore(xMin);
if ( xMax <= graphsData.getLastXMax() ) {
graph.eraseAfter(xMax);
// nothing to compute
} else {
xMin = graph.getLastX();
compute(f, xMin, xMax, yMin, yMax, endGraph, dimensions);
}
} else {
// |--------------------[-----data----|---erased----]-- old data
// |------[<------------>-----data----]---------------- new data
// xMin xMax
//
// OR
//
// |--------------------[------data--]----|----------- old data
// |-------[<----------->------data--<--->]-----------new data
// xMin xMax
// prepare graph
if (!graph.empty()) {
if (xMin >= graphsData.getLastXMin()) {
// |------[---erased---|------data----|---erased--]------ old data
// |-------------------[------data----]------------------ new data
// xMin xMax
//
// OR
//
// |------[---erased---|------data----]----------- old data
// |-------------------[------data----<---->]----- new data
// xMin xMax
graph.eraseBefore(xMin);
if (xMax <= graphsData.getLastXMax()) {
graph.eraseAfter(xMax);
// nothing to compute
} else {
xMin = graph.getLastX();
compute(f, xMin, xMax, yMin, yMax, endGraph, dimensions);
}
} else {
// |--------------------[-----data----|---erased----]-- old data
// |------[<------------>-----data----]---------------- new data
// xMin xMax
//
// OR
//
// |--------------------[------data--]----|----------- old data
// |-------[<----------->------data--<--->]-----------new data
// xMin xMax
if ( xMax <= graphsData.getLastXMax() ) {
graph.eraseAfter(xMax);
xMax = graph.getFirstX();
compute(f, xMin, xMax, yMin, yMax, startGraph, dimensions);
} else {
compute(f, xMin, graph.getFirstX(), yMin, yMax, startGraph, dimensions);
compute(f, graph.getLastX(), xMax, yMin, yMax, endGraph, dimensions);
}
}
} else {
compute(f, xMin, xMax, yMin, yMax, graph, dimensions);
}
if (xMax <= graphsData.getLastXMax()) {
graph.eraseAfter(xMax);
xMax = graph.getFirstX();
compute(f, xMin, xMax, yMin, yMax, startGraph, dimensions);
} else {
compute(f, xMin, graph.getFirstX(), yMin, yMax, startGraph, dimensions);
compute(f, graph.getLastX(), xMax, yMin, yMax, endGraph, dimensions);
}
}
} else {
compute(f, xMin, xMax, yMin, yMax, graph, dimensions);
}
if (!endGraph.empty()) {
// first add ending because it's fast
graph.append(endGraph);
}
if (!endGraph.empty()) {
// first add ending because it's fast
graph.append(endGraph);
}
if (!startGraph.empty()) {
startGraph.append(graph);
graph.swap(startGraph);
}
if (!startGraph.empty()) {
startGraph.append(graph);
graph.swap(startGraph);
}
next.clear();
endGraph.clear();
startGraph.clear();
}
next.clear();
endGraph.clear();
startGraph.clear();
}
protected abstract void compute(@NotNull XyFunction f,
float xMin,
float xMax,
float yMin,
float yMax,
@NotNull GraphData graph,
@NotNull Graph2dDimensions dimensions);
protected abstract void compute(@NotNull XyFunction f,
float xMin,
float xMax,
float yMin,
float yMax,
@NotNull GraphData graph,
@NotNull Graph2dDimensions dimensions);
}

View File

@@ -17,385 +17,386 @@ import java.util.List;
public class CalculatorGraph3dView extends GLView implements GraphView {
/*
**********************************************************************
*
* CONSTANTS
*
**********************************************************************
*/
/*
**********************************************************************
*
* CONSTANTS
*
**********************************************************************
*/
/*
**********************************************************************
*
* FIELDS
*
**********************************************************************
*/
/*
**********************************************************************
*
* FIELDS
*
**********************************************************************
*/
private boolean useHighQuality3d = Build.VERSION.SDK_INT >= 5;
private boolean useHighQuality3d = Build.VERSION.SDK_INT >= 5;
private float lastTouchX, lastTouchY;
private TouchHandler touchHandler;
private ZoomButtonsController zoomController = new ZoomButtonsController(this);
private float lastTouchX, lastTouchY;
private TouchHandler touchHandler;
private ZoomButtonsController zoomController = new ZoomButtonsController(this);
private float zoomLevel = 1;
private float zoomTarget;
private float zoomStep = 0;
private float currentZoom;
private float zoomLevel = 1;
private float zoomTarget;
private float zoomStep = 0;
private float currentZoom;
@NotNull
private List<Graph3d> graphs = new ArrayList<Graph3d>();
@NotNull
private List<Graph3d> graphs = new ArrayList<Graph3d>();
@NotNull
private GraphViewHelper graphViewHelper = GraphViewHelper.newDefaultInstance();
@NotNull
private GraphViewHelper graphViewHelper = GraphViewHelper.newDefaultInstance();
@NotNull
private Graph2dDimensions dimensions = new Graph2dDimensions(this);
@NotNull
private Graph2dDimensions dimensions = new Graph2dDimensions(this);
/*
**********************************************************************
*
* CONSTRUCTORS
*
**********************************************************************
*/
/*
**********************************************************************
*
* CONSTRUCTORS
*
**********************************************************************
*/
public CalculatorGraph3dView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CalculatorGraph3dView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CalculatorGraph3dView(Context context) {
super(context);
touchHandler = new TouchHandler(this);
init();
}
public CalculatorGraph3dView(Context context) {
super(context);
touchHandler = new TouchHandler(this);
init();
}
private void init() {
startLooping();
zoomController.setOnZoomListener(this);
private void init() {
startLooping();
zoomController.setOnZoomListener(this);
Matrix.setIdentityM(matrix1, 0);
Matrix.rotateM(matrix1, 0, -75, 1, 0, 0);
}
Matrix.setIdentityM(matrix1, 0);
Matrix.rotateM(matrix1, 0, -75, 1, 0, 0);
}
/*
**********************************************************************
*
* METHODS
*
**********************************************************************
*/
/*
**********************************************************************
*
* METHODS
*
**********************************************************************
*/
protected void onSizeChanged(int w, int h, int ow, int oh) {
dimensions.setViewDimensions(w, h);
}
protected void onSizeChanged(int w, int h, int ow, int oh) {
dimensions.setViewDimensions(w, h);
}
@Override
protected void glDraw() {
@Override
protected void glDraw() {
if (zoomStep < 0 && zoomLevel > zoomTarget) {
zoomLevel += zoomStep;
} else if (zoomStep > 0 && zoomLevel < zoomTarget) {
zoomLevel += zoomStep;
} else if (zoomStep != 0) {
zoomStep = 0;
zoomLevel = zoomTarget;
dirty = true;
if (!shouldRotate()) {
stopLooping();
}
}
if (zoomStep < 0 && zoomLevel > zoomTarget) {
zoomLevel += zoomStep;
} else if (zoomStep > 0 && zoomLevel < zoomTarget) {
zoomLevel += zoomStep;
} else if (zoomStep != 0) {
zoomStep = 0;
zoomLevel = zoomTarget;
dirty = true;
if (!shouldRotate()) {
stopLooping();
}
}
super.glDraw();
}
super.glDraw();
}
@Override
public void onDetachedFromWindow() {
zoomController.setVisible(false);
super.onDetachedFromWindow();
}
@Override
public void onDetachedFromWindow() {
zoomController.setVisible(false);
super.onDetachedFromWindow();
}
// ----
// ----
private float[] matrix1 = new float[16], matrix2 = new float[16], matrix3 = new float[16];
private float angleX, angleY;
private boolean dirty;
private float[] matrix1 = new float[16], matrix2 = new float[16], matrix3 = new float[16];
private float angleX, angleY;
private boolean dirty;
private static final float DISTANCE = 15f;
private static final float DISTANCE = 15f;
void setRotation(float x, float y) {
angleX = x;
angleY = y;
}
void setRotation(float x, float y) {
angleX = x;
angleY = y;
}
boolean shouldRotate() {
final float limit = .5f;
return angleX < -limit || angleX > limit || angleY < -limit || angleY > limit;
}
boolean shouldRotate() {
final float limit = .5f;
return angleX < -limit || angleX > limit || angleY < -limit || angleY > limit;
}
@Override
public void init(@NotNull PlotViewDef plotViewDef) {
this.graphViewHelper = GraphViewHelper.newInstance(plotViewDef, Collections.<PlotFunction>emptyList());
}
@Override
public void init(@NotNull PlotViewDef plotViewDef) {
this.graphViewHelper = GraphViewHelper.newInstance(plotViewDef, Collections.<PlotFunction>emptyList());
}
@Override
public void setPlotFunctions(@NotNull List<PlotFunction> plotFunctions) {
for (PlotFunction plotFunction: plotFunctions) {
final int arity = plotFunction.getXyFunction().getArity();
if (arity != 0 && arity != 1 && arity != 2) {
throw new IllegalArgumentException("Function must have arity 0 or 1 or 2 for 3d plot!");
}
}
@Override
public void setPlotFunctions(@NotNull List<PlotFunction> plotFunctions) {
for (PlotFunction plotFunction : plotFunctions) {
final int arity = plotFunction.getXyFunction().getArity();
if (arity != 0 && arity != 1 && arity != 2) {
throw new IllegalArgumentException("Function must have arity 0 or 1 or 2 for 3d plot!");
}
}
this.graphViewHelper = this.graphViewHelper.copy(plotFunctions);
zoomLevel = 1;
dirty = true;
}
this.graphViewHelper = this.graphViewHelper.copy(plotFunctions);
zoomLevel = 1;
dirty = true;
}
@NotNull
@Override
public List<PlotFunction> getPlotFunctions() {
return this.graphViewHelper.getPlotFunctions();
}
@NotNull
@Override
public List<PlotFunction> getPlotFunctions() {
return this.graphViewHelper.getPlotFunctions();
}
@Override
public void onDestroy() {
onPause();
}
@Override
public void onDestroy() {
onPause();
}
@Override
public void setXRange(float xMin, float xMax) {
dimensions.setXRange(PlotBoundaries.DEFAULT_MIN_NUMBER, PlotBoundaries.DEFAULT_MAX_NUMBER);
dimensions.setXY(dimensions.getX0(), 0);
@Override
public void setXRange(float xMin, float xMax) {
dimensions.setXRange(PlotBoundaries.DEFAULT_MIN_NUMBER, PlotBoundaries.DEFAULT_MAX_NUMBER);
dimensions.setXY(dimensions.getX0(), 0);
zoomLevel = 1;
dirty = true;
}
zoomLevel = 1;
dirty = true;
}
@Override
public void setYRange(float yMin, float yMax) {
}
@Override
public void setYRange(float yMin, float yMax) {
}
@Override
public float getXMin() {
return dimensions.getXMin();
}
@Override
public float getXMin() {
return dimensions.getXMin();
}
@Override
public float getXMax() {
return dimensions.getXMax();
}
@Override
public float getXMax() {
return dimensions.getXMax();
}
@Override
public float getYMin() {
return dimensions.getYMin();
}
@Override
public float getYMin() {
return dimensions.getYMin();
}
@Override
public float getYMax() {
return dimensions.getYMax();
}
@Override
public float getYMax() {
return dimensions.getYMax();
}
@Override
public void invalidateGraphs() {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void invalidateGraphs() {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void onSurfaceCreated(GL10 gl, int width, int height) {
gl.glDisable(GL10.GL_DITHER);
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST);
@Override
public void onSurfaceCreated(GL10 gl, int width, int height) {
gl.glDisable(GL10.GL_DITHER);
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST);
final int backgroundColor = graphViewHelper.getPlotViewDef().getBackgroundColor();
gl.glClearColor(Color.red(backgroundColor) / 255f, Color.green(backgroundColor) / 255f, Color.blue(backgroundColor) / 255f, Color.alpha(backgroundColor) / 255f);
final int backgroundColor = graphViewHelper.getPlotViewDef().getBackgroundColor();
gl.glClearColor(Color.red(backgroundColor) / 255f, Color.green(backgroundColor) / 255f, Color.blue(backgroundColor) / 255f, Color.alpha(backgroundColor) / 255f);
gl.glShadeModel(useHighQuality3d ? GL10.GL_SMOOTH : GL10.GL_FLAT);
gl.glDisable(GL10.GL_LIGHTING);
ensureGraphsSize((GL11) gl);
dirty = true;
angleX = .5f;
angleY = 0;
gl.glShadeModel(useHighQuality3d ? GL10.GL_SMOOTH : GL10.GL_FLAT);
gl.glDisable(GL10.GL_LIGHTING);
ensureGraphsSize((GL11) gl);
dirty = true;
angleX = .5f;
angleY = 0;
gl.glViewport(0, 0, width, height);
initFrustum(gl, DISTANCE * zoomLevel);
currentZoom = zoomLevel;
}
gl.glViewport(0, 0, width, height);
initFrustum(gl, DISTANCE * zoomLevel);
currentZoom = zoomLevel;
}
@Override
public void onDrawFrame(GL10 gl10) {
GL11 gl = (GL11) gl10;
if (currentZoom != zoomLevel) {
initFrustum(gl, DISTANCE * zoomLevel);
currentZoom = zoomLevel;
}
if (dirty) {
ensureGraphsSize(gl);
@Override
public void onDrawFrame(GL10 gl10) {
GL11 gl = (GL11) gl10;
if (currentZoom != zoomLevel) {
initFrustum(gl, DISTANCE * zoomLevel);
currentZoom = zoomLevel;
}
if (dirty) {
ensureGraphsSize(gl);
final Graph2dDimensions dimensionsCopy = dimensions.copy();
dimensionsCopy.setGraphDimensions(dimensions.getGWidth() * zoomLevel / 4, dimensions.getGHeight() * zoomLevel / 4);
final Graph2dDimensions dimensionsCopy = dimensions.copy();
dimensionsCopy.setGraphDimensions(dimensions.getGWidth() * zoomLevel / 4, dimensions.getGHeight() * zoomLevel / 4);
for (int i = 0; i < graphViewHelper.getPlotFunctions().size(); i++) {
graphs.get(i).update(gl, graphViewHelper.getPlotFunctions().get(i), dimensionsCopy);
for (int i = 0; i < graphViewHelper.getPlotFunctions().size(); i++) {
graphs.get(i).update(gl, graphViewHelper.getPlotFunctions().get(i), dimensionsCopy);
}
dirty = false;
}
}
dirty = false;
}
/*if (fps.incFrame()) {
/*if (fps.incFrame()) {
Calculator.log("f/s " + fps.getValue());
}*/
gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();
gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();
gl.glTranslatef(0, 0, -DISTANCE * zoomLevel);
gl.glTranslatef(0, 0, -DISTANCE * zoomLevel);
Matrix.setIdentityM(matrix2, 0);
float ax = Math.abs(angleX);
float ay = Math.abs(angleY);
if (ay * 3 < ax) {
Matrix.rotateM(matrix2, 0, angleX, 0, 1, 0);
} else if (ax * 3 < ay) {
Matrix.rotateM(matrix2, 0, angleY, 1, 0, 0);
} else {
if (ax > ay) {
Matrix.rotateM(matrix2, 0, angleX, 0, 1, 0);
Matrix.rotateM(matrix2, 0, angleY, 1, 0, 0);
} else {
Matrix.rotateM(matrix2, 0, angleY, 1, 0, 0);
Matrix.rotateM(matrix2, 0, angleX, 0, 1, 0);
}
}
Matrix.multiplyMM(matrix3, 0, matrix2, 0, matrix1, 0);
gl.glMultMatrixf(matrix3, 0);
System.arraycopy(matrix3, 0, matrix1, 0, 16);
for (Graph3d graph : graphs) {
graph.draw(gl);
}
Matrix.setIdentityM(matrix2, 0);
float ax = Math.abs(angleX);
float ay = Math.abs(angleY);
if (ay * 3 < ax) {
Matrix.rotateM(matrix2, 0, angleX, 0, 1, 0);
} else if (ax * 3 < ay) {
Matrix.rotateM(matrix2, 0, angleY, 1, 0, 0);
} else {
if (ax > ay) {
Matrix.rotateM(matrix2, 0, angleX, 0, 1, 0);
Matrix.rotateM(matrix2, 0, angleY, 1, 0, 0);
} else {
Matrix.rotateM(matrix2, 0, angleY, 1, 0, 0);
Matrix.rotateM(matrix2, 0, angleX, 0, 1, 0);
}
}
Matrix.multiplyMM(matrix3, 0, matrix2, 0, matrix1, 0);
gl.glMultMatrixf(matrix3, 0);
System.arraycopy(matrix3, 0, matrix1, 0, 16);
for (Graph3d graph : graphs) {
graph.draw(gl);
}
}
}
private void ensureGraphsSize(@NotNull GL11 gl) {
while (graphViewHelper.getPlotFunctions().size() > graphs.size()) {
graphs.add(new Graph3d(gl, useHighQuality3d));
}
}
private void ensureGraphsSize(@NotNull GL11 gl) {
while (graphViewHelper.getPlotFunctions().size() > graphs.size()) {
graphs.add(new Graph3d(gl, useHighQuality3d));
}
}
private void initFrustum(GL10 gl, float distance) {
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
float near = distance * (1 / 3f);
float far = distance * 3f;
float dimen = near / 5f;
float h = dimen * height / width;
gl.glFrustumf(-dimen, dimen, -h, h, near, far);
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
}
private void initFrustum(GL10 gl, float distance) {
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
float near = distance * (1 / 3f);
float far = distance * 3f;
float dimen = near / 5f;
float h = dimen * height / width;
gl.glFrustumf(-dimen, dimen, -h, h, near, far);
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
}
private void printMatrix(float[] m, String name) {
StringBuilder b = new StringBuilder();
for (int i = 0; i < 16; ++i) {
b.append(m[i]).append(' ');
}
//Calculator.log(name + ' ' + b.toString());
}
private void printMatrix(float[] m, String name) {
StringBuilder b = new StringBuilder();
for (int i = 0; i < 16; ++i) {
b.append(m[i]).append(' ');
}
//Calculator.log(name + ' ' + b.toString());
}
/*
**********************************************************************
*
* ZOOM
*
**********************************************************************
*/
/*
**********************************************************************
*
* ZOOM
*
**********************************************************************
*/
public void onVisibilityChanged(boolean visible) {
}
public void onVisibilityChanged(boolean visible) {
}
public void onZoom(boolean zoomIn) {
boolean changed = false;
if (zoomIn) {
if (canZoomIn(zoomLevel)) {
zoomTarget = zoomLevel * .625f;
zoomStep = -zoomLevel / 40;
changed = true;
}
} else {
if (canZoomOut(zoomLevel)) {
zoomTarget = zoomLevel * 1.6f;
zoomStep = zoomLevel / 20;
changed = true;
}
}
public void onZoom(boolean zoomIn) {
boolean changed = false;
if (zoomIn) {
if (canZoomIn(zoomLevel)) {
zoomTarget = zoomLevel * .625f;
zoomStep = -zoomLevel / 40;
changed = true;
}
} else {
if (canZoomOut(zoomLevel)) {
zoomTarget = zoomLevel * 1.6f;
zoomStep = zoomLevel / 20;
changed = true;
}
}
if (changed) {
zoomController.setZoomInEnabled(canZoomIn(zoomTarget));
zoomController.setZoomOutEnabled(canZoomOut(zoomTarget));
if (!shouldRotate()) {
setRotation(0, 0);
}
startLooping();
}
}
if (changed) {
zoomController.setZoomInEnabled(canZoomIn(zoomTarget));
zoomController.setZoomOutEnabled(canZoomOut(zoomTarget));
if (!shouldRotate()) {
setRotation(0, 0);
}
startLooping();
}
}
private boolean canZoomIn(float zoom) {
return true;
}
private boolean canZoomIn(float zoom) {
return true;
}
private boolean canZoomOut(float zoom) {
return true;
}
private boolean canZoomOut(float zoom) {
return true;
}
/*
**********************************************************************
*
* TOUCH
*
**********************************************************************
*/
/*
**********************************************************************
*
* TOUCH
*
**********************************************************************
*/
public void onTouchDown(float x, float y) {
zoomController.setVisible(true);
stopLooping();
lastTouchX = x;
lastTouchY = y;
}
public void onTouchDown(float x, float y) {
zoomController.setVisible(true);
stopLooping();
lastTouchX = x;
lastTouchY = y;
}
public void onTouchMove(float x, float y) {
float deltaX = x - lastTouchX;
float deltaY = y - lastTouchY;
if (deltaX > 1 || deltaX < -1 || deltaY > 1 || deltaY < -1) {
setRotation(deltaX, deltaY);
glDraw();
lastTouchX = x;
lastTouchY = y;
}
}
public void onTouchMove(float x, float y) {
float deltaX = x - lastTouchX;
float deltaY = y - lastTouchY;
if (deltaX > 1 || deltaX < -1 || deltaY > 1 || deltaY < -1) {
setRotation(deltaX, deltaY);
glDraw();
lastTouchX = x;
lastTouchY = y;
}
}
public void onTouchUp(float x, float y) {
float vx = touchHandler.getXVelocity();
float vy = touchHandler.getYVelocity();
// Calculator.log("velocity " + vx + ' ' + vy);
setRotation(vx / 100, vy / 100);
if (shouldRotate()) {
startLooping();
}
}
public void onTouchUp(float x, float y) {
float vx = touchHandler.getXVelocity();
float vy = touchHandler.getYVelocity();
// Calculator.log("velocity " + vx + ' ' + vy);
setRotation(vx / 100, vy / 100);
if (shouldRotate()) {
startLooping();
}
}
public void onTouchZoomDown(float x1, float y1, float x2, float y2) {
public void onTouchZoomDown(float x1, float y1, float x2, float y2) {
}
}
public void onTouchZoomMove(float x1, float y1, float x2, float y2) {
public void onTouchZoomMove(float x1, float y1, float x2, float y2) {
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return touchHandler != null ? touchHandler.handleTouchEvent(event) : super.onTouchEvent(event);
}}
@Override
public boolean onTouchEvent(MotionEvent event) {
return touchHandler != null ? touchHandler.handleTouchEvent(event) : super.onTouchEvent(event);
}
}

View File

@@ -16,25 +16,25 @@ import org.solovyev.android.calculator.R;
*/
public class CalculatorPlotActivity extends CalculatorFragmentActivity {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Intent intent = getIntent();
final Intent intent = getIntent();
final Bundle arguments;
if (intent != null) {
arguments = intent.getExtras();
} else {
arguments = null;
}
final Bundle arguments;
if (intent != null) {
arguments = intent.getExtras();
} else {
arguments = null;
}
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
getActivityHelper().setFragment(this, getPlotterFragmentType(), arguments, R.id.main_layout);
}
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
getActivityHelper().setFragment(this, getPlotterFragmentType(), arguments, R.id.main_layout);
}
@NotNull
public static CalculatorFragmentType getPlotterFragmentType() {
return CalculatorFragmentType.plotter;
}
@NotNull
public static CalculatorFragmentType getPlotterFragmentType() {
return CalculatorFragmentType.plotter;
}
}

View File

@@ -15,52 +15,52 @@ import org.solovyev.android.calculator.R;
*/
public class CalculatorPlotFragment extends AbstractCalculatorPlotFragment {
@Nullable
private GraphView graphView;
@Nullable
private GraphView graphView;
@Nullable
@Override
protected PlotBoundaries getPlotBoundaries() {
if ( graphView instanceof CalculatorGraph2dView ) {
return PlotBoundaries.newInstance(graphView.getXMin(), graphView.getXMax(), graphView.getYMin(), graphView.getYMax());
} else {
return null;
}
}
@Nullable
@Override
protected PlotBoundaries getPlotBoundaries() {
if (graphView instanceof CalculatorGraph2dView) {
return PlotBoundaries.newInstance(graphView.getXMin(), graphView.getXMax(), graphView.getYMin(), graphView.getYMax());
} else {
return null;
}
}
@Override
protected void createGraphicalView(@NotNull View root, @NotNull PlotData plotData) {
@Override
protected void createGraphicalView(@NotNull View root, @NotNull PlotData plotData) {
// remove old
final ViewGroup graphContainer = (ViewGroup) root.findViewById(R.id.main_fragment_layout);
// remove old
final ViewGroup graphContainer = (ViewGroup) root.findViewById(R.id.main_fragment_layout);
if (graphView instanceof View) {
graphView.onDestroy();
graphContainer.removeView((View) graphView);
}
if (graphView instanceof View) {
graphView.onDestroy();
graphContainer.removeView((View) graphView);
}
if ( plotData.isPlot3d() ) {
graphView = new CalculatorGraph3dView(getActivity());
} else {
graphView = new CalculatorGraph2dView(getActivity());
}
if (plotData.isPlot3d()) {
graphView = new CalculatorGraph3dView(getActivity());
} else {
graphView = new CalculatorGraph2dView(getActivity());
}
graphView.init(PlotViewDef.newInstance(Color.WHITE, Color.WHITE, Color.DKGRAY, getBgColor()));
graphView.init(PlotViewDef.newInstance(Color.WHITE, Color.WHITE, Color.DKGRAY, getBgColor()));
final PlotBoundaries boundaries = plotData.getBoundaries();
graphView.setXRange(boundaries.getXMin(), boundaries.getXMax());
graphView.setYRange(boundaries.getYMin(), boundaries.getYMax());
final PlotBoundaries boundaries = plotData.getBoundaries();
graphView.setXRange(boundaries.getXMin(), boundaries.getXMax());
graphView.setYRange(boundaries.getYMin(), boundaries.getYMax());
graphView.setPlotFunctions(plotData.getFunctions());
graphView.setPlotFunctions(plotData.getFunctions());
if (graphView instanceof View) {
graphContainer.addView((View) graphView);
}
}
if (graphView instanceof View) {
graphContainer.addView((View) graphView);
}
}
@Override
protected void createChart(@NotNull PlotData plotData) {
}
@Override
protected void createChart(@NotNull PlotData plotData) {
}
@Override
protected boolean isScreenshotSupported() {
@@ -75,46 +75,46 @@ public class CalculatorPlotFragment extends AbstractCalculatorPlotFragment {
}
@Override
protected boolean is3dPlotSupported() {
return true;
}
protected boolean is3dPlotSupported() {
return true;
}
@Override
public void onResume() {
super.onResume();
if (this.graphView != null) {
this.graphView.onResume();
}
}
@Override
public void onResume() {
super.onResume();
if (this.graphView != null) {
this.graphView.onResume();
}
}
@Override
protected void onError() {
final View root = getView();
if (root != null && graphView instanceof View) {
final ViewGroup graphContainer = (ViewGroup) root.findViewById(R.id.main_fragment_layout);
graphContainer.removeView((View) graphView);
}
this.graphView = null;
}
@Override
protected void onError() {
final View root = getView();
if (root != null && graphView instanceof View) {
final ViewGroup graphContainer = (ViewGroup) root.findViewById(R.id.main_fragment_layout);
graphContainer.removeView((View) graphView);
}
this.graphView = null;
}
@Override
public void onPause() {
if (this.graphView != null) {
this.graphView.onPause();
}
@Override
public void onPause() {
if (this.graphView != null) {
this.graphView.onPause();
}
super.onPause();
}
super.onPause();
}
@Override
public void onDestroyView() {
if (this.graphView != null) {
this.graphView.onDestroy();
}
@Override
public void onDestroyView() {
if (this.graphView != null) {
this.graphView.onDestroy();
}
super.onDestroyView();
}
super.onDestroyView();
}
}

View File

@@ -21,152 +21,152 @@ import org.solovyev.android.fragments.FragmentUtils;
public class CalculatorPlotFunctionSettingsActivity extends SherlockFragmentActivity {
private static final String INPUT_FUNCTION_ID = "plot-function-id";
private static final String INPUT_FUNCTION_ID = "plot-function-id";
public static void startActivity(@NotNull Context context, @NotNull PlotFunction plotFunction) {
final Intent intent = new Intent(context, CalculatorPlotFunctionSettingsActivity.class);
intent.putExtra(INPUT_FUNCTION_ID, plotFunction.getXyFunction().getId());
context.startActivity(intent);
}
public static void startActivity(@NotNull Context context, @NotNull PlotFunction plotFunction) {
final Intent intent = new Intent(context, CalculatorPlotFunctionSettingsActivity.class);
intent.putExtra(INPUT_FUNCTION_ID, plotFunction.getXyFunction().getId());
context.startActivity(intent);
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cpp_plot_function_settings_dialog);
setContentView(R.layout.cpp_plot_function_settings_dialog);
final Intent intent = getIntent();
final Intent intent = getIntent();
if (intent != null) {
final String plotFunctionId = intent.getStringExtra(INPUT_FUNCTION_ID);
if (intent != null) {
final String plotFunctionId = intent.getStringExtra(INPUT_FUNCTION_ID);
if (plotFunctionId != null) {
final Bundle parameters = new Bundle();
parameters.putString(INPUT_FUNCTION_ID, plotFunctionId);
FragmentUtils.createFragment(this, CalculatorPlotFunctionSettingsFragment.class, R.id.dialog_layout, "plot-function-settings", parameters);
} else {
finish();
}
} else {
finish();
}
}
if (plotFunctionId != null) {
final Bundle parameters = new Bundle();
parameters.putString(INPUT_FUNCTION_ID, plotFunctionId);
FragmentUtils.createFragment(this, CalculatorPlotFunctionSettingsFragment.class, R.id.dialog_layout, "plot-function-settings", parameters);
} else {
finish();
}
} else {
finish();
}
}
public static class CalculatorPlotFunctionSettingsFragment extends CalculatorFragment {
public static class CalculatorPlotFunctionSettingsFragment extends CalculatorFragment {
/*
**********************************************************************
**********************************************************************
*
* STATIC
*
**********************************************************************
*/
@Nullable
private PlotFunction plotFunction;
@Nullable
private PlotFunction plotFunction;
@NotNull
private final CalculatorPlotter plotter = Locator.getInstance().getPlotter();
@NotNull
private final CalculatorPlotter plotter = Locator.getInstance().getPlotter();
public CalculatorPlotFunctionSettingsFragment() {
super(CalculatorFragmentType.plotter_function_settings);
}
public CalculatorPlotFunctionSettingsFragment() {
super(CalculatorFragmentType.plotter_function_settings);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final String functionId = getArguments().getString(INPUT_FUNCTION_ID);
if (functionId != null) {
plotFunction = Locator.getInstance().getPlotter().getFunctionById(functionId);
if (plotFunction != null) {
getActivity().setTitle(plotFunction.getXyFunction().getExpressionString());
}
}
}
final String functionId = getArguments().getString(INPUT_FUNCTION_ID);
if (functionId != null) {
plotFunction = Locator.getInstance().getPlotter().getFunctionById(functionId);
if (plotFunction != null) {
getActivity().setTitle(plotFunction.getXyFunction().getExpressionString());
}
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void onViewCreated(View root, Bundle savedInstanceState) {
super.onViewCreated(root, savedInstanceState);
@Override
public void onViewCreated(View root, Bundle savedInstanceState) {
super.onViewCreated(root, savedInstanceState);
final Spinner plotLineColorSpinner = (Spinner) root.findViewById(R.id.cpp_plot_function_line_color_spinner);
final Spinner plotLineColorTypeSpinner = (Spinner) root.findViewById(R.id.cpp_plot_function_line_color_type_spinner);
final Spinner plotLineStyleSpinner = (Spinner) root.findViewById(R.id.cpp_plot_function_line_style_spinner);
final SeekBar plotLineWidthSeekBar = (SeekBar) root.findViewById(R.id.cpp_plot_functions_line_width_seekbar);
final Button okButton = (Button) root.findViewById(R.id.cpp_apply_button);
final Spinner plotLineColorSpinner = (Spinner) root.findViewById(R.id.cpp_plot_function_line_color_spinner);
final Spinner plotLineColorTypeSpinner = (Spinner) root.findViewById(R.id.cpp_plot_function_line_color_type_spinner);
final Spinner plotLineStyleSpinner = (Spinner) root.findViewById(R.id.cpp_plot_function_line_style_spinner);
final SeekBar plotLineWidthSeekBar = (SeekBar) root.findViewById(R.id.cpp_plot_functions_line_width_seekbar);
final Button okButton = (Button) root.findViewById(R.id.cpp_apply_button);
plotLineWidthSeekBar.setMax(10);
plotLineWidthSeekBar.setMax(10);
if (plotFunction != null) {
plotLineWidthSeekBar.setProgress((int) plotFunction.getPlotLineDef().getLineWidth());
plotLineColorSpinner.setSelection(PlotLineColor.valueOf(plotFunction.getPlotLineDef().getLineColor()).ordinal());
plotLineColorTypeSpinner.setSelection(plotFunction.getPlotLineDef().getLineColorType().ordinal());
plotLineStyleSpinner.setSelection(plotFunction.getPlotLineDef().getLineStyle().ordinal());
if (plotFunction != null) {
plotLineWidthSeekBar.setProgress((int) plotFunction.getPlotLineDef().getLineWidth());
plotLineColorSpinner.setSelection(PlotLineColor.valueOf(plotFunction.getPlotLineDef().getLineColor()).ordinal());
plotLineColorTypeSpinner.setSelection(plotFunction.getPlotLineDef().getLineColorType().ordinal());
plotLineStyleSpinner.setSelection(plotFunction.getPlotLineDef().getLineStyle().ordinal());
okButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
okButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PlotFunction plotFunction = CalculatorPlotFunctionSettingsFragment.this.plotFunction;
PlotFunction plotFunction = CalculatorPlotFunctionSettingsFragment.this.plotFunction;
// color
final PlotLineColor newPlotLineColor = PlotLineColor.values()[plotLineColorSpinner.getSelectedItemPosition()];
int newLineColor = newPlotLineColor.getColor();
if (newLineColor != plotFunction.getPlotLineDef().getLineColor()) {
final PlotLineDef newPlotLineDef = PlotLineDef.changeLineColor(plotFunction.getPlotLineDef(), newLineColor);
plotFunction = PlotFunction.changePlotLineDef(plotFunction, newPlotLineDef);
}
// color
final PlotLineColor newPlotLineColor = PlotLineColor.values()[plotLineColorSpinner.getSelectedItemPosition()];
int newLineColor = newPlotLineColor.getColor();
if (newLineColor != plotFunction.getPlotLineDef().getLineColor()) {
final PlotLineDef newPlotLineDef = PlotLineDef.changeLineColor(plotFunction.getPlotLineDef(), newLineColor);
plotFunction = PlotFunction.changePlotLineDef(plotFunction, newPlotLineDef);
}
// color type
final PlotLineColorType newPlotLineColorType = PlotLineColorType.values()[plotLineColorTypeSpinner.getSelectedItemPosition()];
if (newPlotLineColorType != CalculatorPlotFunctionSettingsFragment.this.plotFunction.getPlotLineDef().getLineColorType()) {
final PlotLineDef newPlotLineDef = PlotLineDef.changeLineColorType(plotFunction.getPlotLineDef(), newPlotLineColorType);
plotFunction = PlotFunction.changePlotLineDef(plotFunction, newPlotLineDef);
}
// color type
final PlotLineColorType newPlotLineColorType = PlotLineColorType.values()[plotLineColorTypeSpinner.getSelectedItemPosition()];
if (newPlotLineColorType != CalculatorPlotFunctionSettingsFragment.this.plotFunction.getPlotLineDef().getLineColorType()) {
final PlotLineDef newPlotLineDef = PlotLineDef.changeLineColorType(plotFunction.getPlotLineDef(), newPlotLineColorType);
plotFunction = PlotFunction.changePlotLineDef(plotFunction, newPlotLineDef);
}
// line style
final PlotLineStyle newPlotLineStyle = PlotLineStyle.values()[plotLineStyleSpinner.getSelectedItemPosition()];
if (newPlotLineStyle != plotFunction.getPlotLineDef().getLineStyle()) {
final PlotLineDef newPlotLineDef = PlotLineDef.changeLineStyle(plotFunction.getPlotLineDef(), newPlotLineStyle);
plotFunction = PlotFunction.changePlotLineDef(plotFunction, newPlotLineDef);
}
// line style
final PlotLineStyle newPlotLineStyle = PlotLineStyle.values()[plotLineStyleSpinner.getSelectedItemPosition()];
if (newPlotLineStyle != plotFunction.getPlotLineDef().getLineStyle()) {
final PlotLineDef newPlotLineDef = PlotLineDef.changeLineStyle(plotFunction.getPlotLineDef(), newPlotLineStyle);
plotFunction = PlotFunction.changePlotLineDef(plotFunction, newPlotLineDef);
}
// width
// width
final int newPlotLineWidth = plotLineWidthSeekBar.getProgress();
if (((float) newPlotLineWidth) != plotFunction.getPlotLineDef().getLineWidth()) {
final PlotLineDef newPlotLineDef = PlotLineDef.changeLineWidth(plotFunction.getPlotLineDef(), newPlotLineWidth);
plotFunction = PlotFunction.changePlotLineDef(plotFunction, newPlotLineDef);
}
final int newPlotLineWidth = plotLineWidthSeekBar.getProgress();
if (((float) newPlotLineWidth) != plotFunction.getPlotLineDef().getLineWidth()) {
final PlotLineDef newPlotLineDef = PlotLineDef.changeLineWidth(plotFunction.getPlotLineDef(), newPlotLineWidth);
plotFunction = PlotFunction.changePlotLineDef(plotFunction, newPlotLineDef);
}
if (plotFunction != CalculatorPlotFunctionSettingsFragment.this.plotFunction) {
// if has been changed
if (plotFunction != CalculatorPlotFunctionSettingsFragment.this.plotFunction) {
// if has been changed
if (plotter.updateFunction(plotFunction)) {
CalculatorPlotFunctionSettingsFragment.this.plotFunction = plotFunction;
}
}
if (plotter.updateFunction(plotFunction)) {
CalculatorPlotFunctionSettingsFragment.this.plotFunction = plotFunction;
}
}
final Activity activity = getActivity();
if (activity != null) {
activity.finish();
}
}
});
final Activity activity = getActivity();
if (activity != null) {
activity.finish();
}
}
});
} else {
plotLineWidthSeekBar.setEnabled(false);
plotLineColorSpinner.setEnabled(false);
plotLineColorTypeSpinner.setEnabled(false);
plotLineStyleSpinner.setEnabled(false);
okButton.setEnabled(false);
}
}
}
} else {
plotLineWidthSeekBar.setEnabled(false);
plotLineColorSpinner.setEnabled(false);
plotLineColorTypeSpinner.setEnabled(false);
plotLineStyleSpinner.setEnabled(false);
okButton.setEnabled(false);
}
}
}
}

View File

@@ -21,14 +21,14 @@ import java.util.List;
*/
public class CalculatorPlotFunctionsActivity extends SherlockFragmentActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cpp_dialog);
setContentView(R.layout.cpp_dialog);
FragmentUtils.createFragment(this, CalculatorPlotFunctionsFragment.class, R.id.dialog_layout, "plot-functions");
}
FragmentUtils.createFragment(this, CalculatorPlotFunctionsFragment.class, R.id.dialog_layout, "plot-functions");
}
public static class CalculatorPlotFunctionsFragment extends CalculatorListFragment {

View File

@@ -11,11 +11,11 @@ import org.solovyev.android.calculator.R;
*/
public class CalculatorPlotPreferenceActivity extends SherlockPreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//noinspection deprecation
addPreferencesFromResource(R.xml.preferences_plot);
}
//noinspection deprecation
addPreferencesFromResource(R.xml.preferences_plot);
}
}

View File

@@ -20,72 +20,72 @@ import org.solovyev.common.msg.MessageType;
*/
public class CalculatorPlotRangeActivity extends SherlockFragmentActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cpp_dialog);
setContentView(R.layout.cpp_dialog);
FragmentUtils.createFragment(this, CalculatorPlotRangeFragment.class, R.id.dialog_layout, "plot-range");
}
FragmentUtils.createFragment(this, CalculatorPlotRangeFragment.class, R.id.dialog_layout, "plot-range");
}
public static class CalculatorPlotRangeFragment extends CalculatorFragment {
public static class CalculatorPlotRangeFragment extends CalculatorFragment {
public CalculatorPlotRangeFragment() {
super(CalculatorFragmentType.plotter_range);
}
public CalculatorPlotRangeFragment() {
super(CalculatorFragmentType.plotter_range);
}
@Override
public void onViewCreated(@NotNull View root, Bundle savedInstanceState) {
super.onViewCreated(root, savedInstanceState);
@Override
public void onViewCreated(@NotNull View root, Bundle savedInstanceState) {
super.onViewCreated(root, savedInstanceState);
final CalculatorPlotter plotter = Locator.getInstance().getPlotter();
final CalculatorPlotter plotter = Locator.getInstance().getPlotter();
final EditText xMinEditText = (EditText) root.findViewById(R.id.cpp_plot_range_x_min_editext);
final EditText xMaxEditText = (EditText) root.findViewById(R.id.cpp_plot_range_x_max_editext);
final EditText yMinEditText = (EditText) root.findViewById(R.id.cpp_plot_range_y_min_editext);
final EditText yMaxEditText = (EditText) root.findViewById(R.id.cpp_plot_range_y_max_editext);
final EditText xMinEditText = (EditText) root.findViewById(R.id.cpp_plot_range_x_min_editext);
final EditText xMaxEditText = (EditText) root.findViewById(R.id.cpp_plot_range_x_max_editext);
final EditText yMinEditText = (EditText) root.findViewById(R.id.cpp_plot_range_y_min_editext);
final EditText yMaxEditText = (EditText) root.findViewById(R.id.cpp_plot_range_y_max_editext);
final PlotData plotData = plotter.getPlotData();
final PlotBoundaries boundaries = plotData.getBoundaries();
final PlotData plotData = plotter.getPlotData();
final PlotBoundaries boundaries = plotData.getBoundaries();
xMinEditText.setText(String.valueOf(boundaries.getXMin()));
xMaxEditText.setText(String.valueOf(boundaries.getXMax()));
yMinEditText.setText(String.valueOf(boundaries.getYMin()));
yMaxEditText.setText(String.valueOf(boundaries.getYMax()));
xMinEditText.setText(String.valueOf(boundaries.getXMin()));
xMaxEditText.setText(String.valueOf(boundaries.getXMax()));
yMinEditText.setText(String.valueOf(boundaries.getYMin()));
yMaxEditText.setText(String.valueOf(boundaries.getYMax()));
root.findViewById(R.id.cpp_apply_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
root.findViewById(R.id.cpp_apply_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
final Float xMin = Float.valueOf(xMinEditText.getText().toString());
final Float xMax = Float.valueOf(xMaxEditText.getText().toString());
final Float yMin = Float.valueOf(yMinEditText.getText().toString());
final Float yMax = Float.valueOf(yMaxEditText.getText().toString());
try {
final Float xMin = Float.valueOf(xMinEditText.getText().toString());
final Float xMax = Float.valueOf(xMaxEditText.getText().toString());
final Float yMin = Float.valueOf(yMinEditText.getText().toString());
final Float yMax = Float.valueOf(yMaxEditText.getText().toString());
if ( xMin.equals(xMax) ) {
throw new IllegalArgumentException();
}
if (xMin.equals(xMax)) {
throw new IllegalArgumentException();
}
if ( yMin.equals(yMax) ) {
throw new IllegalArgumentException();
}
if (yMin.equals(yMax)) {
throw new IllegalArgumentException();
}
plotter.setPlotBoundaries(PlotBoundaries.newInstance(xMin, xMax, yMin, yMax));
plotter.setPlotBoundaries(PlotBoundaries.newInstance(xMin, xMax, yMin, yMax));
CalculatorPlotRangeFragment.this.getActivity().finish();
CalculatorPlotRangeFragment.this.getActivity().finish();
} catch (IllegalArgumentException e) {
if (e instanceof NumberFormatException) {
Locator.getInstance().getNotifier().showMessage(R.string.cpp_invalid_number, MessageType.error);
} else {
Locator.getInstance().getNotifier().showMessage(R.string.cpp_plot_boundaries_should_differ, MessageType.error);
}
}
}
});
}
}
} catch (IllegalArgumentException e) {
if (e instanceof NumberFormatException) {
Locator.getInstance().getNotifier().showMessage(R.string.cpp_invalid_number, MessageType.error);
} else {
Locator.getInstance().getNotifier().showMessage(R.string.cpp_plot_boundaries_should_differ, MessageType.error);
}
}
}
});
}
}
}

View File

@@ -1,22 +1,22 @@
package org.solovyev.android.calculator.plot;
class FPS {
private int drawCnt;
private long lastTime;
private int fps;
private int drawCnt;
private long lastTime;
private int fps;
boolean incFrame() {
if (--drawCnt > 0) {
return false;
}
drawCnt = 100;
long now = System.currentTimeMillis();
fps = Math.round(100000f / (now - lastTime));
lastTime = now;
return true;
}
boolean incFrame() {
if (--drawCnt > 0) {
return false;
}
drawCnt = 100;
long now = System.currentTimeMillis();
fps = Math.round(100000f / (now - lastTime));
lastTime = now;
return true;
}
int getValue() {
return fps;
}
int getValue() {
return fps;
}
}

View File

@@ -20,371 +20,382 @@ import javax.microedition.khronos.opengles.GL10;
public class GLText {
//--Constants--//
public final static int CHAR_START = 32; // First Character (ASCII Code)
public final static int CHAR_END = 126; // Last Character (ASCII Code)
public final static int CHAR_CNT = ( ( ( CHAR_END - CHAR_START ) + 1 ) + 1 ); // Character Count (Including Character to use for Unknown)
//--Constants--//
public final static int CHAR_START = 32; // First Character (ASCII Code)
public final static int CHAR_END = 126; // Last Character (ASCII Code)
public final static int CHAR_CNT = (((CHAR_END - CHAR_START) + 1) + 1); // Character Count (Including Character to use for Unknown)
public final static int CHAR_NONE = 32; // Character to Use for Unknown (ASCII Code)
public final static int CHAR_UNKNOWN = ( CHAR_CNT - 1 ); // Index of the Unknown Character
public final static int CHAR_NONE = 32; // Character to Use for Unknown (ASCII Code)
public final static int CHAR_UNKNOWN = (CHAR_CNT - 1); // Index of the Unknown Character
public final static int FONT_SIZE_MIN = 6; // Minumum Font Size (Pixels)
public final static int FONT_SIZE_MAX = 180; // Maximum Font Size (Pixels)
public final static int FONT_SIZE_MIN = 6; // Minumum Font Size (Pixels)
public final static int FONT_SIZE_MAX = 180; // Maximum Font Size (Pixels)
public final static int CHAR_BATCH_SIZE = 100; // Number of Characters to Render Per Batch
public final static int CHAR_BATCH_SIZE = 100; // Number of Characters to Render Per Batch
//--Members--//
GL10 gl; // GL10 Instance
AssetManager assets; // Asset Manager
SpriteBatch batch; // Batch Renderer
//--Members--//
GL10 gl; // GL10 Instance
AssetManager assets; // Asset Manager
SpriteBatch batch; // Batch Renderer
int fontPadX, fontPadY; // Font Padding (Pixels; On Each Side, ie. Doubled on Both X+Y Axis)
int fontPadX, fontPadY; // Font Padding (Pixels; On Each Side, ie. Doubled on Both X+Y Axis)
float fontHeight; // Font Height (Actual; Pixels)
float fontAscent; // Font Ascent (Above Baseline; Pixels)
float fontDescent; // Font Descent (Below Baseline; Pixels)
float fontHeight; // Font Height (Actual; Pixels)
float fontAscent; // Font Ascent (Above Baseline; Pixels)
float fontDescent; // Font Descent (Below Baseline; Pixels)
int textureId; // Font Texture ID [NOTE: Public for Testing Purposes Only!]
int textureSize; // Texture Size for Font (Square) [NOTE: Public for Testing Purposes Only!]
TextureRegion textureRgn; // Full Texture Region
int textureId; // Font Texture ID [NOTE: Public for Testing Purposes Only!]
int textureSize; // Texture Size for Font (Square) [NOTE: Public for Testing Purposes Only!]
TextureRegion textureRgn; // Full Texture Region
float charWidthMax; // Character Width (Maximum; Pixels)
float charHeight; // Character Height (Maximum; Pixels)
final float[] charWidths; // Width of Each Character (Actual; Pixels)
TextureRegion[] charRgn; // Region of Each Character (Texture Coordinates)
int cellWidth, cellHeight; // Character Cell Width/Height
int rowCnt, colCnt; // Number of Rows/Columns
float charWidthMax; // Character Width (Maximum; Pixels)
float charHeight; // Character Height (Maximum; Pixels)
final float[] charWidths; // Width of Each Character (Actual; Pixels)
TextureRegion[] charRgn; // Region of Each Character (Texture Coordinates)
int cellWidth, cellHeight; // Character Cell Width/Height
int rowCnt, colCnt; // Number of Rows/Columns
float scaleX, scaleY; // Font Scale (X,Y Axis)
float spaceX; // Additional (X,Y Axis) Spacing (Unscaled)
float scaleX, scaleY; // Font Scale (X,Y Axis)
float spaceX; // Additional (X,Y Axis) Spacing (Unscaled)
//--Constructor--//
// D: save GL instance + asset manager, create arrays, and initialize the members
// A: gl - OpenGL ES 10 Instance
public GLText(GL10 gl, AssetManager assets) {
this.gl = gl; // Save the GL10 Instance
this.assets = assets; // Save the Asset Manager Instance
//--Constructor--//
// D: save GL instance + asset manager, create arrays, and initialize the members
// A: gl - OpenGL ES 10 Instance
public GLText(GL10 gl, AssetManager assets) {
this.gl = gl; // Save the GL10 Instance
this.assets = assets; // Save the Asset Manager Instance
batch = new SpriteBatch( gl, CHAR_BATCH_SIZE ); // Create Sprite Batch (with Defined Size)
batch = new SpriteBatch(gl, CHAR_BATCH_SIZE); // Create Sprite Batch (with Defined Size)
charWidths = new float[CHAR_CNT]; // Create the Array of Character Widths
charRgn = new TextureRegion[CHAR_CNT]; // Create the Array of Character Regions
charWidths = new float[CHAR_CNT]; // Create the Array of Character Widths
charRgn = new TextureRegion[CHAR_CNT]; // Create the Array of Character Regions
// initialize remaining members
fontPadX = 0;
fontPadY = 0;
// initialize remaining members
fontPadX = 0;
fontPadY = 0;
fontHeight = 0.0f;
fontAscent = 0.0f;
fontDescent = 0.0f;
fontHeight = 0.0f;
fontAscent = 0.0f;
fontDescent = 0.0f;
textureId = -1;
textureSize = 0;
textureId = -1;
textureSize = 0;
charWidthMax = 0;
charHeight = 0;
charWidthMax = 0;
charHeight = 0;
cellWidth = 0;
cellHeight = 0;
rowCnt = 0;
colCnt = 0;
cellWidth = 0;
cellHeight = 0;
rowCnt = 0;
colCnt = 0;
scaleX = 1.0f; // Default Scale = 1 (Unscaled)
scaleY = 1.0f; // Default Scale = 1 (Unscaled)
spaceX = 0.0f;
}
scaleX = 1.0f; // Default Scale = 1 (Unscaled)
scaleY = 1.0f; // Default Scale = 1 (Unscaled)
spaceX = 0.0f;
}
//--Load Font--//
// description
// this will load the specified font file, create a texture for the defined
// character range, and setup all required values used to render with it.
// arguments:
// file - Filename of the font (.ttf, .otf) to use. In 'Assets' folder.
// size - Requested pixel size of font (height)
// padX, padY - Extra padding per character (X+Y Axis); to prevent overlapping characters.
public boolean load(String file, int size, int padX, int padY) {
//--Load Font--//
// description
// this will load the specified font file, create a texture for the defined
// character range, and setup all required values used to render with it.
// arguments:
// file - Filename of the font (.ttf, .otf) to use. In 'Assets' folder.
// size - Requested pixel size of font (height)
// padX, padY - Extra padding per character (X+Y Axis); to prevent overlapping characters.
public boolean load(String file, int size, int padX, int padY) {
// setup requested values
fontPadX = padX; // Set Requested X Axis Padding
fontPadY = padY; // Set Requested Y Axis Padding
// setup requested values
fontPadX = padX; // Set Requested X Axis Padding
fontPadY = padY; // Set Requested Y Axis Padding
// load the font and setup paint instance for drawing
Typeface tf = Typeface.createFromAsset( assets, file ); // Create the Typeface from Font File
Paint paint = new Paint(); // Create Android Paint Instance
paint.setAntiAlias( true ); // Enable Anti Alias
paint.setTextSize( size ); // Set Text Size
paint.setColor( 0xffffffff ); // Set ARGB (White, Opaque)
paint.setTypeface( tf ); // Set Typeface
// load the font and setup paint instance for drawing
Typeface tf = Typeface.createFromAsset(assets, file); // Create the Typeface from Font File
Paint paint = new Paint(); // Create Android Paint Instance
paint.setAntiAlias(true); // Enable Anti Alias
paint.setTextSize(size); // Set Text Size
paint.setColor(0xffffffff); // Set ARGB (White, Opaque)
paint.setTypeface(tf); // Set Typeface
// get font metrics
Paint.FontMetrics fm = paint.getFontMetrics(); // Get Font Metrics
fontHeight = (float)Math.ceil( Math.abs( fm.bottom ) + Math.abs( fm.top ) ); // Calculate Font Height
fontAscent = (float)Math.ceil( Math.abs( fm.ascent ) ); // Save Font Ascent
fontDescent = (float)Math.ceil( Math.abs( fm.descent ) ); // Save Font Descent
// get font metrics
Paint.FontMetrics fm = paint.getFontMetrics(); // Get Font Metrics
fontHeight = (float) Math.ceil(Math.abs(fm.bottom) + Math.abs(fm.top)); // Calculate Font Height
fontAscent = (float) Math.ceil(Math.abs(fm.ascent)); // Save Font Ascent
fontDescent = (float) Math.ceil(Math.abs(fm.descent)); // Save Font Descent
// determine the width of each character (including unknown character)
// also determine the maximum character width
char[] s = new char[2]; // Create Character Array
charWidthMax = charHeight = 0; // Reset Character Width/Height Maximums
float[] w = new float[2]; // Working Width Value
int cnt = 0; // Array Counter
for ( char c = CHAR_START; c <= CHAR_END; c++ ) { // FOR Each Character
s[0] = c; // Set Character
paint.getTextWidths( s, 0, 1, w ); // Get Character Bounds
charWidths[cnt] = w[0]; // Get Width
if ( charWidths[cnt] > charWidthMax ) // IF Width Larger Than Max Width
charWidthMax = charWidths[cnt]; // Save New Max Width
cnt++; // Advance Array Counter
}
s[0] = CHAR_NONE; // Set Unknown Character
paint.getTextWidths( s, 0, 1, w ); // Get Character Bounds
charWidths[cnt] = w[0]; // Get Width
if ( charWidths[cnt] > charWidthMax ) // IF Width Larger Than Max Width
charWidthMax = charWidths[cnt]; // Save New Max Width
cnt++; // Advance Array Counter
// determine the width of each character (including unknown character)
// also determine the maximum character width
char[] s = new char[2]; // Create Character Array
charWidthMax = charHeight = 0; // Reset Character Width/Height Maximums
float[] w = new float[2]; // Working Width Value
int cnt = 0; // Array Counter
for (char c = CHAR_START; c <= CHAR_END; c++) { // FOR Each Character
s[0] = c; // Set Character
paint.getTextWidths(s, 0, 1, w); // Get Character Bounds
charWidths[cnt] = w[0]; // Get Width
if (charWidths[cnt] > charWidthMax) // IF Width Larger Than Max Width
charWidthMax = charWidths[cnt]; // Save New Max Width
cnt++; // Advance Array Counter
}
s[0] = CHAR_NONE; // Set Unknown Character
paint.getTextWidths(s, 0, 1, w); // Get Character Bounds
charWidths[cnt] = w[0]; // Get Width
if (charWidths[cnt] > charWidthMax) // IF Width Larger Than Max Width
charWidthMax = charWidths[cnt]; // Save New Max Width
cnt++; // Advance Array Counter
// set character height to font height
charHeight = fontHeight; // Set Character Height
// set character height to font height
charHeight = fontHeight; // Set Character Height
// find the maximum size, validate, and setup cell sizes
cellWidth = (int)charWidthMax + ( 2 * fontPadX ); // Set Cell Width
cellHeight = (int)charHeight + ( 2 * fontPadY ); // Set Cell Height
int maxSize = cellWidth > cellHeight ? cellWidth : cellHeight; // Save Max Size (Width/Height)
if ( maxSize < FONT_SIZE_MIN || maxSize > FONT_SIZE_MAX ) // IF Maximum Size Outside Valid Bounds
return false; // Return Error
// find the maximum size, validate, and setup cell sizes
cellWidth = (int) charWidthMax + (2 * fontPadX); // Set Cell Width
cellHeight = (int) charHeight + (2 * fontPadY); // Set Cell Height
int maxSize = cellWidth > cellHeight ? cellWidth : cellHeight; // Save Max Size (Width/Height)
if (maxSize < FONT_SIZE_MIN || maxSize > FONT_SIZE_MAX) // IF Maximum Size Outside Valid Bounds
return false; // Return Error
// set texture size based on max font size (width or height)
// NOTE: these values are fixed, based on the defined characters. when
// changing start/end characters (CHAR_START/CHAR_END) this will need adjustment too!
if ( maxSize <= 24 ) // IF Max Size is 18 or Less
textureSize = 256; // Set 256 Texture Size
else if ( maxSize <= 40 ) // ELSE IF Max Size is 40 or Less
textureSize = 512; // Set 512 Texture Size
else if ( maxSize <= 80 ) // ELSE IF Max Size is 80 or Less
textureSize = 1024; // Set 1024 Texture Size
else // ELSE IF Max Size is Larger Than 80 (and Less than FONT_SIZE_MAX)
textureSize = 2048; // Set 2048 Texture Size
// set texture size based on max font size (width or height)
// NOTE: these values are fixed, based on the defined characters. when
// changing start/end characters (CHAR_START/CHAR_END) this will need adjustment too!
if (maxSize <= 24) // IF Max Size is 18 or Less
textureSize = 256; // Set 256 Texture Size
else if (maxSize <= 40) // ELSE IF Max Size is 40 or Less
textureSize = 512; // Set 512 Texture Size
else if (maxSize <= 80) // ELSE IF Max Size is 80 or Less
textureSize = 1024; // Set 1024 Texture Size
else // ELSE IF Max Size is Larger Than 80 (and Less than FONT_SIZE_MAX)
textureSize = 2048; // Set 2048 Texture Size
// create an empty bitmap (alpha only)
Bitmap bitmap = Bitmap.createBitmap( textureSize, textureSize, Bitmap.Config.ALPHA_8 ); // Create Bitmap
Canvas canvas = new Canvas( bitmap ); // Create Canvas for Rendering to Bitmap
bitmap.eraseColor( 0x00000000 ); // Set Transparent Background (ARGB)
// create an empty bitmap (alpha only)
Bitmap bitmap = Bitmap.createBitmap(textureSize, textureSize, Bitmap.Config.ALPHA_8); // Create Bitmap
Canvas canvas = new Canvas(bitmap); // Create Canvas for Rendering to Bitmap
bitmap.eraseColor(0x00000000); // Set Transparent Background (ARGB)
// calculate rows/columns
// NOTE: while not required for anything, these may be useful to have :)
colCnt = textureSize / cellWidth; // Calculate Number of Columns
rowCnt = (int)Math.ceil( (float)CHAR_CNT / (float)colCnt ); // Calculate Number of Rows
// calculate rows/columns
// NOTE: while not required for anything, these may be useful to have :)
colCnt = textureSize / cellWidth; // Calculate Number of Columns
rowCnt = (int) Math.ceil((float) CHAR_CNT / (float) colCnt); // Calculate Number of Rows
// render each of the characters to the canvas (ie. build the font map)
float x = fontPadX; // Set Start Position (X)
float y = ( cellHeight - 1 ) - fontDescent - fontPadY; // Set Start Position (Y)
for ( char c = CHAR_START; c <= CHAR_END; c++ ) { // FOR Each Character
s[0] = c; // Set Character to Draw
canvas.drawText( s, 0, 1, x, y, paint ); // Draw Character
x += cellWidth; // Move to Next Character
if ( ( x + cellWidth - fontPadX ) > textureSize ) { // IF End of Line Reached
x = fontPadX; // Set X for New Row
y += cellHeight; // Move Down a Row
}
}
s[0] = CHAR_NONE; // Set Character to Use for NONE
canvas.drawText( s, 0, 1, x, y, paint ); // Draw Character
// render each of the characters to the canvas (ie. build the font map)
float x = fontPadX; // Set Start Position (X)
float y = (cellHeight - 1) - fontDescent - fontPadY; // Set Start Position (Y)
for (char c = CHAR_START; c <= CHAR_END; c++) { // FOR Each Character
s[0] = c; // Set Character to Draw
canvas.drawText(s, 0, 1, x, y, paint); // Draw Character
x += cellWidth; // Move to Next Character
if ((x + cellWidth - fontPadX) > textureSize) { // IF End of Line Reached
x = fontPadX; // Set X for New Row
y += cellHeight; // Move Down a Row
}
}
s[0] = CHAR_NONE; // Set Character to Use for NONE
canvas.drawText(s, 0, 1, x, y, paint); // Draw Character
// generate a new texture
int[] textureIds = new int[1]; // Array to Get Texture Id
gl.glGenTextures( 1, textureIds, 0 ); // Generate New Texture
textureId = textureIds[0]; // Save Texture Id
// generate a new texture
int[] textureIds = new int[1]; // Array to Get Texture Id
gl.glGenTextures(1, textureIds, 0); // Generate New Texture
textureId = textureIds[0]; // Save Texture Id
// setup filters for texture
gl.glBindTexture( GL10.GL_TEXTURE_2D, textureId ); // Bind Texture
gl.glTexParameterf( GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST ); // Set Minification Filter
gl.glTexParameterf( GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR ); // Set Magnification Filter
gl.glTexParameterf( GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE ); // Set U Wrapping
gl.glTexParameterf( GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE ); // Set V Wrapping
// setup filters for texture
gl.glBindTexture(GL10.GL_TEXTURE_2D, textureId); // Bind Texture
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST); // Set Minification Filter
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); // Set Magnification Filter
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE); // Set U Wrapping
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE); // Set V Wrapping
// load the generated bitmap onto the texture
GLUtils.texImage2D( GL10.GL_TEXTURE_2D, 0, bitmap, 0 ); // Load Bitmap to Texture
gl.glBindTexture( GL10.GL_TEXTURE_2D, 0 ); // Unbind Texture
// load the generated bitmap onto the texture
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); // Load Bitmap to Texture
gl.glBindTexture(GL10.GL_TEXTURE_2D, 0); // Unbind Texture
// release the bitmap
bitmap.recycle(); // Release the Bitmap
// release the bitmap
bitmap.recycle(); // Release the Bitmap
// setup the array of character texture regions
x = 0; // Initialize X
y = 0; // Initialize Y
for ( int c = 0; c < CHAR_CNT; c++ ) { // FOR Each Character (On Texture)
charRgn[c] = new TextureRegion( textureSize, textureSize, x, y, cellWidth-1, cellHeight-1 ); // Create Region for Character
x += cellWidth; // Move to Next Char (Cell)
if ( x + cellWidth > textureSize ) {
x = 0; // Reset X Position to Start
y += cellHeight; // Move to Next Row (Cell)
}
}
// setup the array of character texture regions
x = 0; // Initialize X
y = 0; // Initialize Y
for (int c = 0; c < CHAR_CNT; c++) { // FOR Each Character (On Texture)
charRgn[c] = new TextureRegion(textureSize, textureSize, x, y, cellWidth - 1, cellHeight - 1); // Create Region for Character
x += cellWidth; // Move to Next Char (Cell)
if (x + cellWidth > textureSize) {
x = 0; // Reset X Position to Start
y += cellHeight; // Move to Next Row (Cell)
}
}
// create full texture region
textureRgn = new TextureRegion( textureSize, textureSize, 0, 0, textureSize, textureSize ); // Create Full Texture Region
// create full texture region
textureRgn = new TextureRegion(textureSize, textureSize, 0, 0, textureSize, textureSize); // Create Full Texture Region
// return success
return true; // Return Success
}
// return success
return true; // Return Success
}
//--Begin/End Text Drawing--//
// D: call these methods before/after (respectively all draw() calls using a text instance
// NOTE: color is set on a per-batch basis, and fonts should be 8-bit alpha only!!!
// A: red, green, blue - RGB values for font (default = 1.0)
// alpha - optional alpha value for font (default = 1.0)
// R: [none]
public void begin() {
begin( 1.0f, 1.0f, 1.0f, 1.0f ); // Begin with White Opaque
}
public void begin(float alpha) {
begin( 1.0f, 1.0f, 1.0f, alpha ); // Begin with White (Explicit Alpha)
}
public void begin(float red, float green, float blue, float alpha) {
gl.glColor4f( red, green, blue, alpha ); // Set Color+Alpha
gl.glBindTexture( GL10.GL_TEXTURE_2D, textureId ); // Bind the Texture
batch.beginBatch(); // Begin Batch
}
public void end() {
batch.endBatch(); // End Batch
gl.glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); // Restore Default Color/Alpha
}
//--Begin/End Text Drawing--//
// D: call these methods before/after (respectively all draw() calls using a text instance
// NOTE: color is set on a per-batch basis, and fonts should be 8-bit alpha only!!!
// A: red, green, blue - RGB values for font (default = 1.0)
// alpha - optional alpha value for font (default = 1.0)
// R: [none]
public void begin() {
begin(1.0f, 1.0f, 1.0f, 1.0f); // Begin with White Opaque
}
//--Draw Text--//
// D: draw text at the specified x,y position
// A: text - the string to draw
// x, y - the x,y position to draw text at (bottom left of text; including descent)
// R: [none]
public void draw(String text, float x, float y) {
float chrHeight = cellHeight * scaleY; // Calculate Scaled Character Height
float chrWidth = cellWidth * scaleX; // Calculate Scaled Character Width
int len = text.length(); // Get String Length
x += ( chrWidth / 2.0f ) - ( fontPadX * scaleX ); // Adjust Start X
y += ( chrHeight / 2.0f ) - ( fontPadY * scaleY ); // Adjust Start Y
for ( int i = 0; i < len; i++ ) { // FOR Each Character in String
int c = (int)text.charAt( i ) - CHAR_START; // Calculate Character Index (Offset by First Char in Font)
if ( c < 0 || c >= CHAR_CNT ) // IF Character Not In Font
c = CHAR_UNKNOWN; // Set to Unknown Character Index
batch.drawSprite( x, y, chrWidth, chrHeight, charRgn[c] ); // Draw the Character
x += ( charWidths[c] + spaceX ) * scaleX; // Advance X Position by Scaled Character Width
}
}
public void begin(float alpha) {
begin(1.0f, 1.0f, 1.0f, alpha); // Begin with White (Explicit Alpha)
}
//--Draw Text Centered--//
// D: draw text CENTERED at the specified x,y position
// A: text - the string to draw
// x, y - the x,y position to draw text at (bottom left of text)
// R: the total width of the text that was drawn
public float drawC(String text, float x, float y) {
float len = getLength( text ); // Get Text Length
draw( text, x - ( len / 2.0f ), y - ( getCharHeight() / 2.0f ) ); // Draw Text Centered
return len; // Return Length
}
public float drawCX(String text, float x, float y) {
float len = getLength( text ); // Get Text Length
draw( text, x - ( len / 2.0f ), y ); // Draw Text Centered (X-Axis Only)
return len; // Return Length
}
public void drawCY(String text, float x, float y) {
draw( text, x, y - ( getCharHeight() / 2.0f ) ); // Draw Text Centered (Y-Axis Only)
}
public void begin(float red, float green, float blue, float alpha) {
gl.glColor4f(red, green, blue, alpha); // Set Color+Alpha
gl.glBindTexture(GL10.GL_TEXTURE_2D, textureId); // Bind the Texture
batch.beginBatch(); // Begin Batch
}
//--Set Scale--//
// D: set the scaling to use for the font
// A: scale - uniform scale for both x and y axis scaling
// sx, sy - separate x and y axis scaling factors
// R: [none]
public void setScale(float scale) {
scaleX = scaleY = scale; // Set Uniform Scale
}
public void setScale(float sx, float sy) {
scaleX = sx; // Set X Scale
scaleY = sy; // Set Y Scale
}
public void end() {
batch.endBatch(); // End Batch
gl.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); // Restore Default Color/Alpha
}
//--Get Scale--//
// D: get the current scaling used for the font
// A: [none]
// R: the x/y scale currently used for scale
public float getScaleX() {
return scaleX; // Return X Scale
}
public float getScaleY() {
return scaleY; // Return Y Scale
}
//--Draw Text--//
// D: draw text at the specified x,y position
// A: text - the string to draw
// x, y - the x,y position to draw text at (bottom left of text; including descent)
// R: [none]
public void draw(String text, float x, float y) {
float chrHeight = cellHeight * scaleY; // Calculate Scaled Character Height
float chrWidth = cellWidth * scaleX; // Calculate Scaled Character Width
int len = text.length(); // Get String Length
x += (chrWidth / 2.0f) - (fontPadX * scaleX); // Adjust Start X
y += (chrHeight / 2.0f) - (fontPadY * scaleY); // Adjust Start Y
for (int i = 0; i < len; i++) { // FOR Each Character in String
int c = (int) text.charAt(i) - CHAR_START; // Calculate Character Index (Offset by First Char in Font)
if (c < 0 || c >= CHAR_CNT) // IF Character Not In Font
c = CHAR_UNKNOWN; // Set to Unknown Character Index
batch.drawSprite(x, y, chrWidth, chrHeight, charRgn[c]); // Draw the Character
x += (charWidths[c] + spaceX) * scaleX; // Advance X Position by Scaled Character Width
}
}
//--Set Space--//
// D: set the spacing (unscaled; ie. pixel size) to use for the font
// A: space - space for x axis spacing
// R: [none]
public void setSpace(float space) {
spaceX = space; // Set Space
}
//--Draw Text Centered--//
// D: draw text CENTERED at the specified x,y position
// A: text - the string to draw
// x, y - the x,y position to draw text at (bottom left of text)
// R: the total width of the text that was drawn
public float drawC(String text, float x, float y) {
float len = getLength(text); // Get Text Length
draw(text, x - (len / 2.0f), y - (getCharHeight() / 2.0f)); // Draw Text Centered
return len; // Return Length
}
//--Get Space--//
// D: get the current spacing used for the font
// A: [none]
// R: the x/y space currently used for scale
public float getSpace() {
return spaceX; // Return X Space
}
public float drawCX(String text, float x, float y) {
float len = getLength(text); // Get Text Length
draw(text, x - (len / 2.0f), y); // Draw Text Centered (X-Axis Only)
return len; // Return Length
}
//--Get Length of a String--//
// D: return the length of the specified string if rendered using current settings
// A: text - the string to get length for
// R: the length of the specified string (pixels)
public float getLength(String text) {
float len = 0.0f; // Working Length
int strLen = text.length(); // Get String Length (Characters)
for ( int i = 0; i < strLen; i++ ) { // For Each Character in String (Except Last
int c = (int)text.charAt( i ) - CHAR_START; // Calculate Character Index (Offset by First Char in Font)
len += ( charWidths[c] * scaleX ); // Add Scaled Character Width to Total Length
}
len += ( strLen > 1 ? ( ( strLen - 1 ) * spaceX ) * scaleX : 0 ); // Add Space Length
return len; // Return Total Length
}
public void drawCY(String text, float x, float y) {
draw(text, x, y - (getCharHeight() / 2.0f)); // Draw Text Centered (Y-Axis Only)
}
//--Get Width/Height of Character--//
// D: return the scaled width/height of a character, or max character width
// NOTE: since all characters are the same height, no character index is required!
// NOTE: excludes spacing!!
// A: chr - the character to get width for
// R: the requested character size (scaled)
public float getCharWidth(char chr) {
int c = chr - CHAR_START; // Calculate Character Index (Offset by First Char in Font)
return ( charWidths[c] * scaleX ); // Return Scaled Character Width
}
public float getCharWidthMax() {
return ( charWidthMax * scaleX ); // Return Scaled Max Character Width
}
public float getCharHeight() {
return ( charHeight * scaleY ); // Return Scaled Character Height
}
//--Set Scale--//
// D: set the scaling to use for the font
// A: scale - uniform scale for both x and y axis scaling
// sx, sy - separate x and y axis scaling factors
// R: [none]
public void setScale(float scale) {
scaleX = scaleY = scale; // Set Uniform Scale
}
//--Get Font Metrics--//
// D: return the specified (scaled) font metric
// A: [none]
// R: the requested font metric (scaled)
public float getAscent() {
return ( fontAscent * scaleY ); // Return Font Ascent
}
public float getDescent() {
return ( fontDescent * scaleY ); // Return Font Descent
}
public float getHeight() {
return ( fontHeight * scaleY ); // Return Font Height (Actual)
}
public void setScale(float sx, float sy) {
scaleX = sx; // Set X Scale
scaleY = sy; // Set Y Scale
}
//--Draw Font Texture--//
// D: draw the entire font texture (NOTE: for testing purposes only)
// A: width, height - the width and height of the area to draw to. this is used
// to draw the texture to the top-left corner.
public void drawTexture(int width, int height) {
batch.beginBatch( textureId ); // Begin Batch (Bind Texture)
batch.drawSprite( textureSize / 2, height - ( textureSize / 2 ), textureSize, textureSize, textureRgn ); // Draw
batch.endBatch(); // End Batch
}
//--Get Scale--//
// D: get the current scaling used for the font
// A: [none]
// R: the x/y scale currently used for scale
public float getScaleX() {
return scaleX; // Return X Scale
}
public float getScaleY() {
return scaleY; // Return Y Scale
}
//--Set Space--//
// D: set the spacing (unscaled; ie. pixel size) to use for the font
// A: space - space for x axis spacing
// R: [none]
public void setSpace(float space) {
spaceX = space; // Set Space
}
//--Get Space--//
// D: get the current spacing used for the font
// A: [none]
// R: the x/y space currently used for scale
public float getSpace() {
return spaceX; // Return X Space
}
//--Get Length of a String--//
// D: return the length of the specified string if rendered using current settings
// A: text - the string to get length for
// R: the length of the specified string (pixels)
public float getLength(String text) {
float len = 0.0f; // Working Length
int strLen = text.length(); // Get String Length (Characters)
for (int i = 0; i < strLen; i++) { // For Each Character in String (Except Last
int c = (int) text.charAt(i) - CHAR_START; // Calculate Character Index (Offset by First Char in Font)
len += (charWidths[c] * scaleX); // Add Scaled Character Width to Total Length
}
len += (strLen > 1 ? ((strLen - 1) * spaceX) * scaleX : 0); // Add Space Length
return len; // Return Total Length
}
//--Get Width/Height of Character--//
// D: return the scaled width/height of a character, or max character width
// NOTE: since all characters are the same height, no character index is required!
// NOTE: excludes spacing!!
// A: chr - the character to get width for
// R: the requested character size (scaled)
public float getCharWidth(char chr) {
int c = chr - CHAR_START; // Calculate Character Index (Offset by First Char in Font)
return (charWidths[c] * scaleX); // Return Scaled Character Width
}
public float getCharWidthMax() {
return (charWidthMax * scaleX); // Return Scaled Max Character Width
}
public float getCharHeight() {
return (charHeight * scaleY); // Return Scaled Character Height
}
//--Get Font Metrics--//
// D: return the specified (scaled) font metric
// A: [none]
// R: the requested font metric (scaled)
public float getAscent() {
return (fontAscent * scaleY); // Return Font Ascent
}
public float getDescent() {
return (fontDescent * scaleY); // Return Font Descent
}
public float getHeight() {
return (fontHeight * scaleY); // Return Font Height (Actual)
}
//--Draw Font Texture--//
// D: draw the entire font texture (NOTE: for testing purposes only)
// A: width, height - the width and height of the area to draw to. this is used
// to draw the texture to the top-left corner.
public void drawTexture(int width, int height) {
batch.beginBatch(textureId); // Begin Batch (Bind Texture)
batch.drawSprite(textureSize / 2, height - (textureSize / 2), textureSize, textureSize, textureRgn); // Draw
batch.endBatch(); // End Batch
}
}

View File

@@ -12,12 +12,7 @@ import android.view.SurfaceHolder;
import android.view.SurfaceView;
import org.jetbrains.annotations.NotNull;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGL11;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.egl.EGLSurface;
import javax.microedition.khronos.egl.*;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
import java.nio.ByteBuffer;
@@ -25,181 +20,181 @@ import java.nio.ByteOrder;
import java.nio.ShortBuffer;
abstract class GLView extends SurfaceView implements SurfaceHolder.Callback {
private boolean hasSurface;
private boolean paused;
private EGL10 egl;
private EGLDisplay display;
private EGLConfig config;
private EGLSurface surface;
private EGLContext eglContext;
private GL11 gl;
protected int width, height;
private volatile boolean looping;
private boolean hasSurface;
private boolean paused;
private EGL10 egl;
private EGLDisplay display;
private EGLConfig config;
private EGLSurface surface;
private EGLContext eglContext;
private GL11 gl;
protected int width, height;
private volatile boolean looping;
abstract void onDrawFrame(GL10 gl);
abstract void onDrawFrame(GL10 gl);
abstract void onSurfaceCreated(GL10 gl, int width, int height);
abstract void onSurfaceCreated(GL10 gl, int width, int height);
@NotNull
public Bitmap captureScreenshot() {
final Bitmap result = getRawPixels(gl, width, height);
bitmapBGRtoRGB(result, width, height);
public Bitmap captureScreenshot() {
final Bitmap result = getRawPixels(gl, width, height);
bitmapBGRtoRGB(result, width, height);
return result;
}
}
private static Bitmap getRawPixels(GL10 gl, int width, int height) {
int size = width * height;
ByteBuffer buf = ByteBuffer.allocateDirect(size * 4);
buf.order(ByteOrder.nativeOrder());
gl.glReadPixels(0, 0, width, height, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, buf);
int data[] = new int[size];
buf.asIntBuffer().get(data);
buf = null;
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
bitmap.setPixels(data, size - width, -width, 0, 0, width, height);
return bitmap;
}
private static Bitmap getRawPixels(GL10 gl, int width, int height) {
int size = width * height;
ByteBuffer buf = ByteBuffer.allocateDirect(size * 4);
buf.order(ByteOrder.nativeOrder());
gl.glReadPixels(0, 0, width, height, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, buf);
int data[] = new int[size];
buf.asIntBuffer().get(data);
buf = null;
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
bitmap.setPixels(data, size - width, -width, 0, 0, width, height);
return bitmap;
}
@NotNull
private final Handler uiHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
glDraw();
break;
default:
Log.e("GLView", "Incorrect message id: " + msg.what);
}
}
};
@NotNull
private final Handler uiHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
glDraw();
break;
default:
Log.e("GLView", "Incorrect message id: " + msg.what);
}
}
};
public GLView(Context context) {
super(context);
init();
}
public GLView(Context context) {
super(context);
init();
}
public GLView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public GLView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
final SurfaceHolder holder = getHolder();
holder.setType(SurfaceHolder.SURFACE_TYPE_GPU);
holder.addCallback(this);
}
private void init() {
final SurfaceHolder holder = getHolder();
holder.setType(SurfaceHolder.SURFACE_TYPE_GPU);
holder.addCallback(this);
}
public void onResume() {
paused = false;
if (hasSurface) {
initGL();
}
}
public void onResume() {
paused = false;
if (hasSurface) {
initGL();
}
}
public void onPause() {
deinitGL();
}
public void onPause() {
deinitGL();
}
private void initGL() {
egl = (EGL10) EGLContext.getEGL();
display = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
int[] ver = new int[2];
egl.eglInitialize(display, ver);
private void initGL() {
egl = (EGL10) EGLContext.getEGL();
display = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
int[] ver = new int[2];
egl.eglInitialize(display, ver);
int[] configSpec = {EGL10.EGL_NONE};
EGLConfig[] configOut = new EGLConfig[1];
int[] nConfig = new int[1];
egl.eglChooseConfig(display, configSpec, configOut, 1, nConfig);
config = configOut[0];
eglContext = egl.eglCreateContext(display, config, EGL10.EGL_NO_CONTEXT, null);
surface = egl.eglCreateWindowSurface(display, config, getHolder(), null);
egl.eglMakeCurrent(display, surface, surface, eglContext);
gl = (GL11) eglContext.getGL();
onSurfaceCreated(gl, width, height);
requestDraw();
}
int[] configSpec = {EGL10.EGL_NONE};
EGLConfig[] configOut = new EGLConfig[1];
int[] nConfig = new int[1];
egl.eglChooseConfig(display, configSpec, configOut, 1, nConfig);
config = configOut[0];
eglContext = egl.eglCreateContext(display, config, EGL10.EGL_NO_CONTEXT, null);
surface = egl.eglCreateWindowSurface(display, config, getHolder(), null);
egl.eglMakeCurrent(display, surface, surface, eglContext);
gl = (GL11) eglContext.getGL();
onSurfaceCreated(gl, width, height);
requestDraw();
}
private void deinitGL() {
paused = true;
if (display != null) {
egl.eglMakeCurrent(display, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
egl.eglDestroySurface(display, surface);
egl.eglDestroyContext(display, eglContext);
egl.eglTerminate(display);
private void deinitGL() {
paused = true;
if (display != null) {
egl.eglMakeCurrent(display, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
egl.eglDestroySurface(display, surface);
egl.eglDestroyContext(display, eglContext);
egl.eglTerminate(display);
egl = null;
config = null;
eglContext = null;
surface = null;
display = null;
gl = null;
}
}
egl = null;
config = null;
eglContext = null;
surface = null;
display = null;
gl = null;
}
}
protected void glDraw() {
if (hasSurface && !paused) {
onDrawFrame(gl);
if (!egl.eglSwapBuffers(display, surface)) {
}
if (egl.eglGetError() == EGL11.EGL_CONTEXT_LOST) {
paused = true;
}
if (looping) {
requestDraw();
}
}
}
protected void glDraw() {
if (hasSurface && !paused) {
onDrawFrame(gl);
if (!egl.eglSwapBuffers(display, surface)) {
}
if (egl.eglGetError() == EGL11.EGL_CONTEXT_LOST) {
paused = true;
}
if (looping) {
requestDraw();
}
}
}
public void surfaceCreated(SurfaceHolder holder) {
}
public void surfaceCreated(SurfaceHolder holder) {
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
this.width = width;
this.height = height;
boolean doInit = !hasSurface && !paused;
hasSurface = true;
if (doInit) {
initGL();
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
this.width = width;
this.height = height;
boolean doInit = !hasSurface && !paused;
hasSurface = true;
if (doInit) {
initGL();
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
hasSurface = false;
deinitGL();
}
public void surfaceDestroyed(SurfaceHolder holder) {
hasSurface = false;
deinitGL();
}
public void startLooping() {
if (!looping) {
looping = true;
glDraw();
}
}
public void startLooping() {
if (!looping) {
looping = true;
glDraw();
}
}
public void stopLooping() {
if (looping) {
looping = false;
}
}
public void stopLooping() {
if (looping) {
looping = false;
}
}
public boolean isLooping() {
return looping;
}
public boolean isLooping() {
return looping;
}
public void requestDraw() {
uiHandler.sendEmptyMessage(1);
}
public void requestDraw() {
uiHandler.sendEmptyMessage(1);
}
static void bitmapBGRtoRGB(Bitmap bitmap, int width, int height) {
int size = width * height;
short data[] = new short[size];
ShortBuffer buf = ShortBuffer.wrap(data);
bitmap.copyPixelsToBuffer(buf);
for (int i = 0; i < size; ++i) {
//BGR-565 to RGB-565
short v = data[i];
data[i] = (short) (((v & 0x1f) << 11) | (v & 0x7e0) | ((v & 0xf800) >> 11));
}
buf.rewind();
bitmap.copyPixelsFromBuffer(buf);
}
static void bitmapBGRtoRGB(Bitmap bitmap, int width, int height) {
int size = width * height;
short data[] = new short[size];
ShortBuffer buf = ShortBuffer.wrap(data);
bitmap.copyPixelsToBuffer(buf);
for (int i = 0; i < size; ++i) {
//BGR-565 to RGB-565
short v = data[i];
data[i] = (short) (((v & 0x1f) << 11) | (v & 0x7e0) | ((v & 0xf800) >> 11));
}
buf.rewind();
bitmap.copyPixelsFromBuffer(buf);
}
}

View File

@@ -11,231 +11,231 @@ import org.solovyev.common.math.Point2d;
*/
public class Graph2dDimensions {
// |<--------------gWidth-------------->|
// xMin xMax
// -------------------|------------------------------------|--------------------
// |<-------------vWidthPxs------------>|
//
/*
*
*
* yMax ------0------------------------------------|--> xPxs
* ^ |
* | |
* v | y
* H | ^
* e | |
* i | |
* g | |
* h |------------------0-----------------|--> x
* t | |
* | | |
* | | |
* v | |
* yMin ------- -
* | |
* v
* yPxs
*
* */
// |<--------------gWidth-------------->|
// xMin xMax
// -------------------|------------------------------------|--------------------
// |<-------------vWidthPxs------------>|
//
/*
*
*
* yMax ------0------------------------------------|--> xPxs
* ^ |
* | |
* v | y
* H | ^
* e | |
* i | |
* g | |
* h |------------------0-----------------|--> x
* t | |
* | | |
* | | |
* v | |
* yMin ------- -
* | |
* v
* yPxs
*
* */
@NotNull
private GraphView graphView;
@NotNull
private GraphView graphView;
// view width and height in pixels
private int vWidthPxs;
private int vHeightPxs;
// view width and height in pixels
private int vWidthPxs;
private int vHeightPxs;
// current position of camera in graph coordinates
private float x0;
private float y0;
// current position of camera in graph coordinates
private float x0;
private float y0;
// graph width and height in function units (NOT screen pixels)
private float gWidth = 20;
private float gHeight = 20;
// graph width and height in function units (NOT screen pixels)
private float gWidth = 20;
private float gHeight = 20;
public Graph2dDimensions(@NotNull GraphView graphView) {
this.graphView = graphView;
}
public Graph2dDimensions(@NotNull GraphView graphView) {
this.graphView = graphView;
}
/*
**********************************************************************
*
* METHODS
*
**********************************************************************
*/
/*
**********************************************************************
*
* METHODS
*
**********************************************************************
*/
@NotNull
Point2d toGraphCoordinates(float xPxs, float yPxs) {
return new Point2d( scaleXPxs(xPxs) + getXMin(), (getGHeight() - scaleYPxs(yPxs)) + getYMin() );
}
@NotNull
Point2d toGraphCoordinates(float xPxs, float yPxs) {
return new Point2d(scaleXPxs(xPxs) + getXMin(), (getGHeight() - scaleYPxs(yPxs)) + getYMin());
}
private float scaleXPxs(float pxs) {
return pxs * getXGraphToViewScale();
}
private float scaleXPxs(float pxs) {
return pxs * getXGraphToViewScale();
}
private float scaleYPxs(float pxs) {
return pxs * getYGraphToViewScale();
}
private float scaleYPxs(float pxs) {
return pxs * getYGraphToViewScale();
}
// X
// X
public float getXMin() {
return x0 - gWidth / 2;
}
public float getXMin() {
return x0 - gWidth / 2;
}
float getXMax(float minX) {
return minX + gWidth;
}
float getXMax(float minX) {
return minX + gWidth;
}
public float getXMax() {
return getXMax(getXMin());
}
public float getXMax() {
return getXMax(getXMin());
}
// Y
// Y
public float getYMin() {
return y0 - gHeight / 2;
}
public float getYMin() {
return y0 - gHeight / 2;
}
public float getYMax() {
return getYMax(getYMin());
}
public float getYMax() {
return getYMax(getYMin());
}
public float getYMax(float yMin) {
return yMin + gHeight;
}
public float getYMax(float yMin) {
return yMin + gHeight;
}
float getXGraphToViewScale() {
if (vWidthPxs != 0) {
return gWidth / ((float)vWidthPxs);
} else {
return 0f;
}
}
float getXGraphToViewScale() {
if (vWidthPxs != 0) {
return gWidth / ((float) vWidthPxs);
} else {
return 0f;
}
}
float getYGraphToViewScale() {
if (vHeightPxs != 0) {
return gHeight / ((float)vHeightPxs);
} else {
return 0f;
}
}
float getYGraphToViewScale() {
if (vHeightPxs != 0) {
return gHeight / ((float) vHeightPxs);
} else {
return 0f;
}
}
private float getViewAspectRatio() {
if (vWidthPxs != 0) {
return ((float) vHeightPxs) / vWidthPxs;
} else {
return 0f;
}
}
private float getViewAspectRatio() {
if (vWidthPxs != 0) {
return ((float) vHeightPxs) / vWidthPxs;
} else {
return 0f;
}
}
public int getVWidthPxs() {
return vWidthPxs;
}
public int getVWidthPxs() {
return vWidthPxs;
}
public int getVHeightPxs() {
return vHeightPxs;
}
public int getVHeightPxs() {
return vHeightPxs;
}
public float getX0() {
return x0;
}
public float getX0() {
return x0;
}
public float getY0() {
return y0;
}
public float getY0() {
return y0;
}
public float getGWidth() {
return gWidth;
}
public float getGWidth() {
return gWidth;
}
float getGHeight() {
return gHeight;
}
float getGHeight() {
return gHeight;
}
/*
**********************************************************************
*
* SETTERS
*
**********************************************************************
*/
/*
**********************************************************************
*
* SETTERS
*
**********************************************************************
*/
public void setXRange(float xMin, float xMax) {
setXRange0(xMin, xMax);
public void setXRange(float xMin, float xMax) {
setXRange0(xMin, xMax);
this.graphView.invalidateGraphs();
}
this.graphView.invalidateGraphs();
}
private void setXRange0(float xMin, float xMax) {
this.gWidth = xMax - xMin;
this.x0 = xMin + gWidth / 2;
}
private void setXRange0(float xMin, float xMax) {
this.gWidth = xMax - xMin;
this.x0 = xMin + gWidth / 2;
}
public void setYRange(float yMin, float yMax) {
setYRange0(yMin, yMax);
public void setYRange(float yMin, float yMax) {
setYRange0(yMin, yMax);
this.graphView.invalidateGraphs();
}
this.graphView.invalidateGraphs();
}
private void setYRange0(float yMin, float yMax) {
this.gHeight = yMax - yMin;
this.y0 = yMin + gHeight / 2;
}
private void setYRange0(float yMin, float yMax) {
this.gHeight = yMax - yMin;
this.y0 = yMin + gHeight / 2;
}
public void setRanges(float xMin, float xMax, float yMin, float yMax) {
setXRange0(xMin, xMax);
setYRange0(yMin, yMax);
public void setRanges(float xMin, float xMax, float yMin, float yMax) {
setXRange0(xMin, xMax);
setYRange0(yMin, yMax);
this.graphView.invalidateGraphs();
}
this.graphView.invalidateGraphs();
}
public void setViewDimensions(@NotNull View view) {
this.vWidthPxs = view.getWidth();
this.vHeightPxs = view.getHeight();
public void setViewDimensions(@NotNull View view) {
this.vWidthPxs = view.getWidth();
this.vHeightPxs = view.getHeight();
this.graphView.invalidateGraphs();
}
this.graphView.invalidateGraphs();
}
public void setGraphDimensions(float gWidth, float gHeight) {
this.gWidth = gWidth;
this.gHeight = gHeight;
public void setGraphDimensions(float gWidth, float gHeight) {
this.gWidth = gWidth;
this.gHeight = gHeight;
this.graphView.invalidateGraphs();
}
this.graphView.invalidateGraphs();
}
public void setViewDimensions(int vWidthPxs, int vHeightPxs) {
this.vWidthPxs = vWidthPxs;
this.vHeightPxs = vHeightPxs;
public void setViewDimensions(int vWidthPxs, int vHeightPxs) {
this.vWidthPxs = vWidthPxs;
this.vHeightPxs = vHeightPxs;
this.graphView.invalidateGraphs();
}
this.graphView.invalidateGraphs();
}
void setXY(float x0, float y0) {
this.x0 = x0;
this.y0 = y0;
}
void setXY(float x0, float y0) {
this.x0 = x0;
this.y0 = y0;
}
public void increaseXY(float dx, float dy) {
this.x0 += dx;
this.y0 += dy;
}
public void increaseXY(float dx, float dy) {
this.x0 += dx;
this.y0 += dy;
}
@NotNull
public Graph2dDimensions copy() {
final Graph2dDimensions copy = new Graph2dDimensions(this.graphView);
@NotNull
public Graph2dDimensions copy() {
final Graph2dDimensions copy = new Graph2dDimensions(this.graphView);
copy.vWidthPxs = this.vWidthPxs;
copy.vHeightPxs = this.vHeightPxs;
copy.x0 = this.x0;
copy.y0 = this.y0;
copy.gWidth = this.gWidth;
copy.gHeight = this.gHeight;
copy.vWidthPxs = this.vWidthPxs;
copy.vHeightPxs = this.vHeightPxs;
copy.x0 = this.x0;
copy.y0 = this.y0;
copy.gWidth = this.gWidth;
copy.gHeight = this.gHeight;
return copy;
}
return copy;
}
}

View File

@@ -14,344 +14,344 @@ import java.nio.ShortBuffer;
class Graph3d {
// vertices count per polygon (triangle = 3)
public static final int VERTICES_COUNT = 3;
// vertices count per polygon (triangle = 3)
public static final int VERTICES_COUNT = 3;
// color components count per color
public static final int COLOR_COMPONENTS_COUNT = 4;
// color components count per color
public static final int COLOR_COMPONENTS_COUNT = 4;
// linear polygons count
private final int n;
// linear polygons count
private final int n;
private final boolean useHighQuality3d;
private ShortBuffer verticeIdx;
private FloatBuffer vertexBuf;
private ByteBuffer colorBuf;
private int vertexVbo, colorVbo, vertexElementVbo;
private boolean useVBO;
private int polygonsⁿ;
private final boolean useHighQuality3d;
private ShortBuffer verticeIdx;
private FloatBuffer vertexBuf;
private ByteBuffer colorBuf;
private int vertexVbo, colorVbo, vertexElementVbo;
private boolean useVBO;
private int polygonsⁿ;
Graph3d(GL11 gl, boolean useHighQuality3d) {
this.useHighQuality3d = useHighQuality3d;
this.n = useHighQuality3d ? 36 : 24;
Graph3d(GL11 gl, boolean useHighQuality3d) {
this.useHighQuality3d = useHighQuality3d;
this.n = useHighQuality3d ? 36 : 24;
short[] b = new short[n * n];
int p = 0;
for (int i = 0; i < n; i++) {
short v = 0;
for (int j = 0; j < n; v += n + n, j += 2) {
b[p++] = (short) (v + i);
b[p++] = (short) (v + n + n - 1 - i);
}
v = (short) (n * (n - 2));
i++;
for (int j = n - 1; j >= 0; v -= n + n, j -= 2) {
b[p++] = (short) (v + n + n - 1 - i);
b[p++] = (short) (v + i);
}
}
verticeIdx = buildBuffer(b);
short[] b = new short[n * n];
int p = 0;
for (int i = 0; i < n; i++) {
short v = 0;
for (int j = 0; j < n; v += n + n, j += 2) {
b[p++] = (short) (v + i);
b[p++] = (short) (v + n + n - 1 - i);
}
v = (short) (n * (n - 2));
i++;
for (int j = n - 1; j >= 0; v -= n + n, j -= 2) {
b[p++] = (short) (v + n + n - 1 - i);
b[p++] = (short) (v + i);
}
}
verticeIdx = buildBuffer(b);
String extensions = gl.glGetString(GL10.GL_EXTENSIONS);
useVBO = extensions.indexOf("vertex_buffer_object") != -1;
//Calculator.log("VBOs support: " + useVBO + " version " + gl.glGetString(GL10.GL_VERSION));
String extensions = gl.glGetString(GL10.GL_EXTENSIONS);
useVBO = extensions.indexOf("vertex_buffer_object") != -1;
//Calculator.log("VBOs support: " + useVBO + " version " + gl.glGetString(GL10.GL_VERSION));
if (useVBO) {
int[] out = new int[3];
gl.glGenBuffers(3, out, 0);
vertexVbo = out[0];
colorVbo = out[1];
vertexElementVbo = out[2];
}
}
if (useVBO) {
int[] out = new int[3];
gl.glGenBuffers(3, out, 0);
vertexVbo = out[0];
colorVbo = out[1];
vertexElementVbo = out[2];
}
}
private static FloatBuffer buildBuffer(float[] b) {
ByteBuffer bb = ByteBuffer.allocateDirect(b.length << 2);
bb.order(ByteOrder.nativeOrder());
FloatBuffer sb = bb.asFloatBuffer();
sb.put(b);
sb.position(0);
return sb;
}
private static FloatBuffer buildBuffer(float[] b) {
ByteBuffer bb = ByteBuffer.allocateDirect(b.length << 2);
bb.order(ByteOrder.nativeOrder());
FloatBuffer sb = bb.asFloatBuffer();
sb.put(b);
sb.position(0);
return sb;
}
private static ShortBuffer buildBuffer(short[] b) {
ByteBuffer bb = ByteBuffer.allocateDirect(b.length << 1);
bb.order(ByteOrder.nativeOrder());
ShortBuffer sb = bb.asShortBuffer();
sb.put(b);
sb.position(0);
return sb;
}
private static ShortBuffer buildBuffer(short[] b) {
ByteBuffer bb = ByteBuffer.allocateDirect(b.length << 1);
bb.order(ByteOrder.nativeOrder());
ShortBuffer sb = bb.asShortBuffer();
sb.put(b);
sb.position(0);
return sb;
}
private static ByteBuffer buildBuffer(byte[] b) {
ByteBuffer bb = ByteBuffer.allocateDirect(b.length << 1);
bb.order(ByteOrder.nativeOrder());
bb.put(b);
bb.position(0);
return bb;
}
private static ByteBuffer buildBuffer(byte[] b) {
ByteBuffer bb = ByteBuffer.allocateDirect(b.length << 1);
bb.order(ByteOrder.nativeOrder());
bb.put(b);
bb.position(0);
return bb;
}
public void update(@NotNull GL11 gl, @NotNull PlotFunction fpd, @NotNull Graph2dDimensions dimensions) {
final XyFunction function = fpd.getXyFunction();
final PlotLineDef lineDef = fpd.getPlotLineDef();
final int NTICK = useHighQuality3d ? 5 : 0;
public void update(@NotNull GL11 gl, @NotNull PlotFunction fpd, @NotNull Graph2dDimensions dimensions) {
final XyFunction function = fpd.getXyFunction();
final PlotLineDef lineDef = fpd.getPlotLineDef();
final int NTICK = useHighQuality3d ? 5 : 0;
//Calculator.log("update VBOs " + vertexVbo + ' ' + colorVbo + ' ' + vertexElementVbo);
polygonsⁿ = n * n + 6 + 8 + NTICK * 6;
//Calculator.log("update VBOs " + vertexVbo + ' ' + colorVbo + ' ' + vertexElementVbo);
polygonsⁿ = n * n + 6 + 8 + NTICK * 6;
// triangle polygon => 3 vertices per polygon
final float vertices[] = new float[polygonsⁿ * VERTICES_COUNT];
// triangle polygon => 3 vertices per polygon
final float vertices[] = new float[polygonsⁿ * VERTICES_COUNT];
float maxAbsZ = fillFunctionPolygonVertices(function, dimensions, vertices);
final byte[] colors = prepareFunctionPolygonColors(lineDef, vertices, maxAbsZ);
float maxAbsZ = fillFunctionPolygonVertices(function, dimensions, vertices);
final byte[] colors = prepareFunctionPolygonColors(lineDef, vertices, maxAbsZ);
int base = n * n * 3;
int colorBase = n * n * 4;
final int baseSize = 2;
int base = n * n * 3;
int colorBase = n * n * 4;
final int baseSize = 2;
fillBasePolygonVectors(vertices, colors, base, colorBase, baseSize);
fillBasePolygonVectors(vertices, colors, base, colorBase, baseSize);
base += 8 * 3;
colorBase += 8 * 4;
base += 8 * 3;
colorBase += 8 * 4;
fillAxisPolygonVectors(vertices, colors, base, colorBase);
fillAxisPolygonVectors(vertices, colors, base, colorBase);
base += 6 * 3;
colorBase += 6 * 4;
base += 6 * 3;
colorBase += 6 * 4;
fillAxisGridPolygonVectors(NTICK, vertices, colors, base, colorBase);
fillAxisGridPolygonVectors(NTICK, vertices, colors, base, colorBase);
vertexBuf = buildBuffer(vertices);
colorBuf = buildBuffer(colors);
vertexBuf = buildBuffer(vertices);
colorBuf = buildBuffer(colors);
if (useVBO) {
gl.glBindBuffer(GL11.GL_ARRAY_BUFFER, vertexVbo);
gl.glBufferData(GL11.GL_ARRAY_BUFFER, vertexBuf.capacity() * 4, vertexBuf, GL11.GL_STATIC_DRAW);
vertexBuf = null;
if (useVBO) {
gl.glBindBuffer(GL11.GL_ARRAY_BUFFER, vertexVbo);
gl.glBufferData(GL11.GL_ARRAY_BUFFER, vertexBuf.capacity() * 4, vertexBuf, GL11.GL_STATIC_DRAW);
vertexBuf = null;
gl.glBindBuffer(GL11.GL_ARRAY_BUFFER, colorVbo);
gl.glBufferData(GL11.GL_ARRAY_BUFFER, colorBuf.capacity(), colorBuf, GL11.GL_STATIC_DRAW);
gl.glBindBuffer(GL11.GL_ARRAY_BUFFER, 0);
colorBuf = null;
gl.glBindBuffer(GL11.GL_ARRAY_BUFFER, colorVbo);
gl.glBufferData(GL11.GL_ARRAY_BUFFER, colorBuf.capacity(), colorBuf, GL11.GL_STATIC_DRAW);
gl.glBindBuffer(GL11.GL_ARRAY_BUFFER, 0);
colorBuf = null;
gl.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, vertexElementVbo);
gl.glBufferData(GL11.GL_ELEMENT_ARRAY_BUFFER, verticeIdx.capacity() * 2, verticeIdx, GL11.GL_STATIC_DRAW);
gl.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0);
}
}
gl.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, vertexElementVbo);
gl.glBufferData(GL11.GL_ELEMENT_ARRAY_BUFFER, verticeIdx.capacity() * 2, verticeIdx, GL11.GL_STATIC_DRAW);
gl.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0);
}
}
private void fillAxisGridPolygonVectors(int NTICK, float[] vertices, byte[] colors, int base, int colorBase) {
int p = base;
final float tick = .03f;
final float offset = .01f;
for (int i = 1; i <= NTICK; ++i) {
vertices[p] = i - tick;
vertices[p + 1] = -offset;
vertices[p + 2] = -offset;
private void fillAxisGridPolygonVectors(int NTICK, float[] vertices, byte[] colors, int base, int colorBase) {
int p = base;
final float tick = .03f;
final float offset = .01f;
for (int i = 1; i <= NTICK; ++i) {
vertices[p] = i - tick;
vertices[p + 1] = -offset;
vertices[p + 2] = -offset;
vertices[p + 3] = i + tick;
vertices[p + 4] = offset;
vertices[p + 5] = offset;
p += 6;
vertices[p + 3] = i + tick;
vertices[p + 4] = offset;
vertices[p + 5] = offset;
p += 6;
vertices[p] = -offset;
vertices[p + 1] = i - tick;
vertices[p + 2] = -offset;
vertices[p] = -offset;
vertices[p + 1] = i - tick;
vertices[p + 2] = -offset;
vertices[p + 3] = offset;
vertices[p + 4] = i + tick;
vertices[p + 5] = offset;
p += 6;
vertices[p + 3] = offset;
vertices[p + 4] = i + tick;
vertices[p + 5] = offset;
p += 6;
vertices[p] = -offset;
vertices[p + 1] = -offset;
vertices[p + 2] = i - tick;
vertices[p] = -offset;
vertices[p + 1] = -offset;
vertices[p + 2] = i - tick;
vertices[p + 3] = offset;
vertices[p + 4] = offset;
vertices[p + 5] = i + tick;
p += 6;
vertices[p + 3] = offset;
vertices[p + 4] = offset;
vertices[p + 5] = i + tick;
p += 6;
}
for (int i = colorBase + NTICK * 6 * 4 - 1; i >= colorBase; --i) {
colors[i] = (byte) 255;
}
}
}
for (int i = colorBase + NTICK * 6 * 4 - 1; i >= colorBase; --i) {
colors[i] = (byte) 255;
}
}
private void fillAxisPolygonVectors(float[] vertices, byte[] colors, int base, int colorBase) {
final float unit = 2;
final float axis[] = {
0, 0, 0,
unit, 0, 0,
0, 0, 0,
0, unit, 0,
0, 0, 0,
0, 0, unit,
};
System.arraycopy(axis, 0, vertices, base, 6 * 3);
for (int i = colorBase; i < colorBase + 6 * 4; i += 4) {
colors[i] = (byte) 255;
colors[i + 1] = (byte) 255;
colors[i + 2] = (byte) 255;
colors[i + 3] = (byte) 255;
}
}
private void fillAxisPolygonVectors(float[] vertices, byte[] colors, int base, int colorBase) {
final float unit = 2;
final float axis[] = {
0, 0, 0,
unit, 0, 0,
0, 0, 0,
0, unit, 0,
0, 0, 0,
0, 0, unit,
};
System.arraycopy(axis, 0, vertices, base, 6 * 3);
for (int i = colorBase; i < colorBase + 6 * 4; i += 4) {
colors[i] = (byte) 255;
colors[i + 1] = (byte) 255;
colors[i + 2] = (byte) 255;
colors[i + 3] = (byte) 255;
}
}
private void fillBasePolygonVectors(float[] vertices, byte[] colors, int base, int colorBase, int baseSize) {
int p = base;
for (int i = -baseSize; i <= baseSize; i += 2 * baseSize) {
vertices[p] = i;
vertices[p + 1] = -baseSize;
vertices[p + 2] = 0;
p += 3;
vertices[p] = i;
vertices[p + 1] = baseSize;
vertices[p + 2] = 0;
p += 3;
vertices[p] = -baseSize;
vertices[p + 1] = i;
vertices[p + 2] = 0;
p += 3;
vertices[p] = baseSize;
vertices[p + 1] = i;
vertices[p + 2] = 0;
p += 3;
}
private void fillBasePolygonVectors(float[] vertices, byte[] colors, int base, int colorBase, int baseSize) {
int p = base;
for (int i = -baseSize; i <= baseSize; i += 2 * baseSize) {
vertices[p] = i;
vertices[p + 1] = -baseSize;
vertices[p + 2] = 0;
p += 3;
vertices[p] = i;
vertices[p + 1] = baseSize;
vertices[p + 2] = 0;
p += 3;
vertices[p] = -baseSize;
vertices[p + 1] = i;
vertices[p + 2] = 0;
p += 3;
vertices[p] = baseSize;
vertices[p + 1] = i;
vertices[p + 2] = 0;
p += 3;
}
for (int i = colorBase; i < colorBase + 8 * 4; i += 4) {
colors[i] = (byte) 255;
colors[i + 1] = (byte) 255;
colors[i + 2] = (byte) 255;
colors[i + 3] = (byte) 255;
}
}
for (int i = colorBase; i < colorBase + 8 * 4; i += 4) {
colors[i] = (byte) 255;
colors[i + 1] = (byte) 255;
colors[i + 2] = (byte) 255;
colors[i + 3] = (byte) 255;
}
}
private float fillFunctionPolygonVertices(XyFunction function, @NotNull Graph2dDimensions dimensions, float[] vertices) {
final int arity = function.getArity();
private float fillFunctionPolygonVertices(XyFunction function, @NotNull Graph2dDimensions dimensions, float[] vertices) {
final int arity = function.getArity();
final float xMin = dimensions.getXMin();
final float xMax = dimensions.getXMax();
final float xMin = dimensions.getXMin();
final float xMax = dimensions.getXMax();
final float yMin = dimensions.getXMin();
final float yMax = dimensions.getXMax();
final float yMin = dimensions.getXMin();
final float yMax = dimensions.getXMax();
float Δx = (xMax - xMin) / (n - 1);
float Δy = (yMax - yMin) / (n - 1);
float Δx = (xMax - xMin) / (n - 1);
float Δy = (yMax - yMin) / (n - 1);
float y = yMin;
float x = xMin - Δx;
float y = yMin;
float x = xMin - Δx;
float maxAbsZ = 0;
float maxAbsZ = 0;
float z = 0;
if (arity == 0) {
z = (float) function.eval();
}
float z = 0;
if (arity == 0) {
z = (float) function.eval();
}
int k = 0;
for (int i = 0; i < n; i++, y += Δy) {
float xinc = (i & 1) == 0 ? Δx : -Δx;
int k = 0;
for (int i = 0; i < n; i++, y += Δy) {
float xinc = (i & 1) == 0 ? Δx : -Δx;
x += xinc;
x += xinc;
if (arity == 1) {
z = (float) function.eval(y);
}
if (arity == 1) {
z = (float) function.eval(y);
}
for (int j = 0; j < n; j++, x += xinc, k += VERTICES_COUNT) {
for (int j = 0; j < n; j++, x += xinc, k += VERTICES_COUNT) {
if (arity == 2) {
z = (float) function.eval(y, x);
}
if (arity == 2) {
z = (float) function.eval(y, x);
}
vertices[k] = x;
vertices[k + 1] = y;
vertices[k + 2] = z;
vertices[k] = x;
vertices[k + 1] = y;
vertices[k + 2] = z;
if (!Float.isNaN(z)) {
final float absZ = Math.abs(z);
if (absZ > maxAbsZ) {
maxAbsZ = absZ;
}
} else {
vertices[k + 2] = 0;
}
}
}
if (!Float.isNaN(z)) {
final float absZ = Math.abs(z);
if (absZ > maxAbsZ) {
maxAbsZ = absZ;
}
} else {
vertices[k + 2] = 0;
}
}
}
return maxAbsZ;
}
return maxAbsZ;
}
private byte[] prepareFunctionPolygonColors(PlotLineDef lineDef, float[] vertices, float maxAbsZ) {
// 4 color components per polygon (color[i] = red, color[i+1] = green, color[i+2] = blue, color[i+3] = alpha )
final byte colors[] = new byte[polygonsⁿ * COLOR_COMPONENTS_COUNT];
private byte[] prepareFunctionPolygonColors(PlotLineDef lineDef, float[] vertices, float maxAbsZ) {
// 4 color components per polygon (color[i] = red, color[i+1] = green, color[i+2] = blue, color[i+3] = alpha )
final byte colors[] = new byte[polygonsⁿ * COLOR_COMPONENTS_COUNT];
final int lineColor = lineDef.getLineColor();
final int colorComponentsCount = n * n * COLOR_COMPONENTS_COUNT;
for (int i = 0, j = VERTICES_COUNT - 1; i < colorComponentsCount; i += COLOR_COMPONENTS_COUNT, j += VERTICES_COUNT) {
final float z = vertices[j];
final int lineColor = lineDef.getLineColor();
final int colorComponentsCount = n * n * COLOR_COMPONENTS_COUNT;
for (int i = 0, j = VERTICES_COUNT - 1; i < colorComponentsCount; i += COLOR_COMPONENTS_COUNT, j += VERTICES_COUNT) {
final float z = vertices[j];
if (!Float.isNaN(z)) {
if (lineDef.getLineColorType() == PlotLineColorType.color_map) {
final float color = z / maxAbsZ;
final float abs = Math.abs(color);
colors[i] = floatToByte(color);
colors[i + 1] = floatToByte(1 - abs * .3f);
colors[i + 2] = floatToByte(-color);
} else {
colors[i] = (byte) Color.red(lineColor);
colors[i + 1] = (byte) Color.green(lineColor);
colors[i + 2] = (byte) Color.blue(lineColor);
}
colors[i + 3] = (byte) 255;
} else {
colors[i] = 0;
colors[i + 1] = 0;
colors[i + 2] = 0;
colors[i + 3] = 0;
}
}
return colors;
}
if (!Float.isNaN(z)) {
if (lineDef.getLineColorType() == PlotLineColorType.color_map) {
final float color = z / maxAbsZ;
final float abs = Math.abs(color);
colors[i] = floatToByte(color);
colors[i + 1] = floatToByte(1 - abs * .3f);
colors[i + 2] = floatToByte(-color);
} else {
colors[i] = (byte) Color.red(lineColor);
colors[i + 1] = (byte) Color.green(lineColor);
colors[i + 2] = (byte) Color.blue(lineColor);
}
colors[i + 3] = (byte) 255;
} else {
colors[i] = 0;
colors[i + 1] = 0;
colors[i + 2] = 0;
colors[i + 3] = 0;
}
}
return colors;
}
private byte floatToByte(float v) {
if (v <= 0) {
return (byte) 0;
} else {
if (v >= 1) {
return (byte) 255;
} else {
return (byte) (v * 255);
}
}
}
private byte floatToByte(float v) {
if (v <= 0) {
return (byte) 0;
} else {
if (v >= 1) {
return (byte) 255;
} else {
return (byte) (v * 255);
}
}
}
public void draw(GL11 gl) {
if (useVBO) {
gl.glBindBuffer(GL11.GL_ARRAY_BUFFER, vertexVbo);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, 0);
public void draw(GL11 gl) {
if (useVBO) {
gl.glBindBuffer(GL11.GL_ARRAY_BUFFER, vertexVbo);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, 0);
gl.glBindBuffer(GL11.GL_ARRAY_BUFFER, colorVbo);
gl.glColorPointer(4, GL10.GL_UNSIGNED_BYTE, 0, 0);
gl.glBindBuffer(GL11.GL_ARRAY_BUFFER, colorVbo);
gl.glColorPointer(4, GL10.GL_UNSIGNED_BYTE, 0, 0);
gl.glBindBuffer(GL11.GL_ARRAY_BUFFER, 0);
// gl.glDrawArrays(GL10.GL_LINE_STRIP, 0, N*N);
gl.glBindBuffer(GL11.GL_ARRAY_BUFFER, 0);
// gl.glDrawArrays(GL10.GL_LINE_STRIP, 0, N*N);
gl.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, vertexElementVbo);
gl.glDrawElements(GL10.GL_LINE_STRIP, n * n, GL10.GL_UNSIGNED_SHORT, 0);
gl.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0);
} else {
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuf);
gl.glColorPointer(4, GL10.GL_UNSIGNED_BYTE, 0, colorBuf);
gl.glDrawElements(GL10.GL_LINE_STRIP, n * n, GL10.GL_UNSIGNED_SHORT, verticeIdx);
}
final int N2 = n * n;
gl.glDrawArrays(GL10.GL_LINE_STRIP, 0, N2);
gl.glDrawArrays(GL10.GL_LINES, N2, polygonsⁿ - N2);
}
gl.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, vertexElementVbo);
gl.glDrawElements(GL10.GL_LINE_STRIP, n * n, GL10.GL_UNSIGNED_SHORT, 0);
gl.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0);
} else {
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuf);
gl.glColorPointer(4, GL10.GL_UNSIGNED_BYTE, 0, colorBuf);
gl.glDrawElements(GL10.GL_LINE_STRIP, n * n, GL10.GL_UNSIGNED_SHORT, verticeIdx);
}
final int N2 = n * n;
gl.glDrawArrays(GL10.GL_LINE_STRIP, 0, N2);
gl.glDrawArrays(GL10.GL_LINES, N2, polygonsⁿ - N2);
}
public boolean isUseHighQuality3d() {
return useHighQuality3d;
}
public boolean isUseHighQuality3d() {
return useHighQuality3d;
}
}

View File

@@ -9,10 +9,10 @@ import org.jetbrains.annotations.NotNull;
*/
public interface GraphCalculator {
void computeGraph(@NotNull XyFunction f,
float xMin,
float xMax,
@NotNull GraphData graph,
@NotNull GraphsData graphsData,
@NotNull Graph2dDimensions dimensions);
void computeGraph(@NotNull XyFunction f,
float xMin,
float xMax,
@NotNull GraphData graph,
@NotNull GraphsData graphsData,
@NotNull Graph2dDimensions dimensions);
}

View File

@@ -9,93 +9,93 @@ import org.jetbrains.annotations.NotNull;
*/
public class GraphCalculatorImpl extends AbstractGraphCalculator {
@Override
protected void compute(@NotNull XyFunction f,
float xMin,
float xMax,
float yMin,
float yMax,
@NotNull GraphData graph,
@NotNull Graph2dDimensions dimensions) {
graph.push(xMin, (float)f.eval(xMin));
@Override
protected void compute(@NotNull XyFunction f,
float xMin,
float xMax,
float yMin,
float yMax,
@NotNull GraphData graph,
@NotNull Graph2dDimensions dimensions) {
graph.push(xMin, (float) f.eval(xMin));
final float xScale = dimensions.getXGraphToViewScale();
final float yScale = dimensions.getYGraphToViewScale();
final float maxStep = 15.8976f * xScale;
final float minStep = .05f * xScale;
final float xScale = dimensions.getXGraphToViewScale();
final float yScale = dimensions.getYGraphToViewScale();
final float maxStep = 15.8976f * xScale;
final float minStep = .05f * xScale;
float yTheta = yScale;
yTheta = yTheta * yTheta;
float yTheta = yScale;
yTheta = yTheta * yTheta;
float leftX;
float leftY;
float leftX;
float leftY;
float rightX = graph.getLastX();
float rightY = graph.getLastY();
float rightX = graph.getLastX();
float rightY = graph.getLastY();
while (true) {
leftX = rightX;
leftY = rightY;
while (true) {
leftX = rightX;
leftY = rightY;
if (leftX > xMax) {
break;
}
if (leftX > xMax) {
break;
}
if (next.empty()) {
float x = leftX + maxStep;
next.push(x, (float) f.eval(x));
}
if (next.empty()) {
float x = leftX + maxStep;
next.push(x, (float) f.eval(x));
}
rightX = next.getLastX();
rightY = next.getLastY();
next.pop();
rightX = next.getLastX();
rightY = next.getLastY();
next.pop();
if (Float.isNaN(leftY) || Float.isNaN(rightY)) {
continue;
}
if (Float.isNaN(leftY) || Float.isNaN(rightY)) {
continue;
}
float dx = rightX - leftX;
float middleX = (leftX + rightX) / 2;
float middleY = (float) f.eval(middleX);
float dx = rightX - leftX;
float middleX = (leftX + rightX) / 2;
float middleY = (float) f.eval(middleX);
boolean middleIsOutside = (middleY < leftY && middleY < rightY) || (leftY < middleY && rightY < middleY);
boolean middleIsOutside = (middleY < leftY && middleY < rightY) || (leftY < middleY && rightY < middleY);
if (dx < minStep) {
// Calculator.log("minStep");
if (middleIsOutside) {
graph.push(rightX, Float.NaN);
}
graph.push(rightX, rightY);
continue;
}
if (dx < minStep) {
// Calculator.log("minStep");
if (middleIsOutside) {
graph.push(rightX, Float.NaN);
}
graph.push(rightX, rightY);
continue;
}
if (middleIsOutside && ((leftY < yMin && rightY > yMax) || (leftY > yMax && rightY < yMin))) {
graph.push(rightX, Float.NaN);
graph.push(rightX, rightY);
// Calculator.log("+-inf");
continue;
}
if (middleIsOutside && ((leftY < yMin && rightY > yMax) || (leftY > yMax && rightY < yMin))) {
graph.push(rightX, Float.NaN);
graph.push(rightX, rightY);
// Calculator.log("+-inf");
continue;
}
if (!middleIsOutside) {
if (distance2(leftX, leftY, rightX, rightY, middleY) < yTheta) {
graph.push(rightX, rightY);
continue;
}
}
if (!middleIsOutside) {
if (distance2(leftX, leftY, rightX, rightY, middleY) < yTheta) {
graph.push(rightX, rightY);
continue;
}
}
next.push(rightX, rightY);
next.push(middleX, middleY);
rightX = leftX;
rightY = leftY;
}
}
next.push(rightX, rightY);
next.push(middleX, middleY);
rightX = leftX;
rightY = leftY;
}
}
// distance as above when x==(x1+x2)/2.
private float distance2(float x1, float y1, float x2, float y2, float y) {
final float dx = x2 - x1;
final float dy = y2 - y1;
final float up = dx * (y1 + y2 - y - y);
return up * up / (dx * dx + dy * dy);
}
// distance as above when x==(x1+x2)/2.
private float distance2(float x1, float y1, float x2, float y2, float y) {
final float dx = x2 - x1;
final float dy = y2 - y1;
final float up = dx * (y1 + y2 - y - y);
return up * up / (dx * dx + dy * dy);
}
}

View File

@@ -4,162 +4,162 @@ import org.jetbrains.annotations.NotNull;
class GraphData {
private int size = 0;
private int size = 0;
private int allocatedSize = 4;
private float[] xs = new float[allocatedSize];
private float[] ys = new float[allocatedSize];
private int allocatedSize = 4;
private float[] xs = new float[allocatedSize];
private float[] ys = new float[allocatedSize];
private GraphData() {
}
private GraphData() {
}
@NotNull
static GraphData newEmptyInstance() {
return new GraphData();
}
@NotNull
static GraphData newEmptyInstance() {
return new GraphData();
}
void swap(@NotNull GraphData that) {
float savedXs[] = that.xs;
float savedYs[] = that.ys;
int savedSize = that.size;
int savedAllocatedSize = that.allocatedSize;
void swap(@NotNull GraphData that) {
float savedXs[] = that.xs;
float savedYs[] = that.ys;
int savedSize = that.size;
int savedAllocatedSize = that.allocatedSize;
that.xs = this.xs;
that.ys = this.ys;
that.size = this.size;
that.allocatedSize = this.allocatedSize;
that.xs = this.xs;
that.ys = this.ys;
that.size = this.size;
that.allocatedSize = this.allocatedSize;
this.xs = savedXs;
this.ys = savedYs;
this.size = savedSize;
this.allocatedSize = savedAllocatedSize;
}
this.xs = savedXs;
this.ys = savedYs;
this.size = savedSize;
this.allocatedSize = savedAllocatedSize;
}
void push(float x, float y) {
if (size >= allocatedSize) {
makeSpaceAtTheEnd(size + 1);
}
void push(float x, float y) {
if (size >= allocatedSize) {
makeSpaceAtTheEnd(size + 1);
}
xs[size] = x;
ys[size] = y;
++size;
}
xs[size] = x;
ys[size] = y;
++size;
}
private void makeSpaceAtTheEnd(int newSize) {
int oldAllocatedSize = allocatedSize;
while (newSize > allocatedSize) {
allocatedSize += allocatedSize;
}
private void makeSpaceAtTheEnd(int newSize) {
int oldAllocatedSize = allocatedSize;
while (newSize > allocatedSize) {
allocatedSize += allocatedSize;
}
if (oldAllocatedSize != allocatedSize) {
float[] a = new float[allocatedSize];
System.arraycopy(xs, 0, a, 0, this.size);
xs = a;
a = new float[allocatedSize];
System.arraycopy(ys, 0, a, 0, this.size);
ys = a;
}
}
if (oldAllocatedSize != allocatedSize) {
float[] a = new float[allocatedSize];
System.arraycopy(xs, 0, a, 0, this.size);
xs = a;
a = new float[allocatedSize];
System.arraycopy(ys, 0, a, 0, this.size);
ys = a;
}
}
float getLastX() {
return xs[size - 1];
}
float getLastX() {
return xs[size - 1];
}
float getLastY() {
return ys[size - 1];
}
float getLastY() {
return ys[size - 1];
}
float getFirstX() {
return xs[0];
}
float getFirstX() {
return xs[0];
}
float getFirstY() {
return ys[0];
}
float getFirstY() {
return ys[0];
}
void pop() {
--size;
}
void pop() {
--size;
}
boolean empty() {
return size == 0;
}
boolean empty() {
return size == 0;
}
void clear() {
size = 0;
}
void clear() {
size = 0;
}
void eraseBefore(float x) {
int i = 0;
while (i < size && xs[i] < x) {
++i;
}
// step back as xs[i] >= x and xs[i-1] < x
--i;
void eraseBefore(float x) {
int i = 0;
while (i < size && xs[i] < x) {
++i;
}
// step back as xs[i] >= x and xs[i-1] < x
--i;
if (i > 0) {
size -= i;
System.arraycopy(xs, i, xs, 0, size);
System.arraycopy(ys, i, ys, 0, size);
}
}
if (i > 0) {
size -= i;
System.arraycopy(xs, i, xs, 0, size);
System.arraycopy(ys, i, ys, 0, size);
}
}
void eraseAfter(float x) {
int i = size - 1;
while (i >= 0 && x < xs[i]) {
--i;
}
void eraseAfter(float x) {
int i = size - 1;
while (i >= 0 && x < xs[i]) {
--i;
}
// step next as xs[i] > x and xs[i+1] <= x
++i;
// step next as xs[i] > x and xs[i+1] <= x
++i;
if (i < size - 1) {
size = i + 1;
}
}
if (i < size - 1) {
size = i + 1;
}
}
int findPositionAfter(float x, float y) {
int i = 0;
while (i < size && xs[i] <= x) {
++i;
}
int findPositionAfter(float x, float y) {
int i = 0;
while (i < size && xs[i] <= x) {
++i;
}
if (Float.isNaN(y)) {
while (i < size && Float.isNaN(ys[i])) {
++i;
}
}
if (Float.isNaN(y)) {
while (i < size && Float.isNaN(ys[i])) {
++i;
}
}
return i;
}
return i;
}
void append(GraphData that) {
makeSpaceAtTheEnd(size + that.size);
int position = that.findPositionAfter(xs[size - 1], ys[size - 1]);
System.arraycopy(that.xs, position, xs, size, that.size - position);
System.arraycopy(that.ys, position, ys, size, that.size - position);
size += that.size - position;
}
void append(GraphData that) {
makeSpaceAtTheEnd(size + that.size);
int position = that.findPositionAfter(xs[size - 1], ys[size - 1]);
System.arraycopy(that.xs, position, xs, size, that.size - position);
System.arraycopy(that.ys, position, ys, size, that.size - position);
size += that.size - position;
}
public String toString() {
StringBuilder b = new StringBuilder();
b.append(size).append(": ");
for (int i = 0; i < size; ++i) {
b.append(xs[i]).append(", ");
}
return b.toString();
}
public String toString() {
StringBuilder b = new StringBuilder();
b.append(size).append(": ");
for (int i = 0; i < size; ++i) {
b.append(xs[i]).append(", ");
}
return b.toString();
}
public float[] getXs() {
return xs;
}
public float[] getXs() {
return xs;
}
public float[] getYs() {
return ys;
}
public float[] getYs() {
return ys;
}
public int getSize() {
return size;
}
public int getSize() {
return size;
}
}

View File

@@ -8,43 +8,46 @@ import java.util.List;
public interface GraphView extends ZoomButtonsController.OnZoomListener, TouchHandler.TouchHandlerListener {
public void init(@NotNull PlotViewDef plotViewDef);
public void init(@NotNull PlotViewDef plotViewDef);
public void setPlotFunctions(@NotNull List<PlotFunction> plotFunctions);
@NotNull
public List<PlotFunction> getPlotFunctions();
public void onDestroy();
public void onPause();
public void onResume();
public void setPlotFunctions(@NotNull List<PlotFunction> plotFunctions);
@NotNull
public Bitmap captureScreenshot();
public List<PlotFunction> getPlotFunctions();
public void onDestroy();
public void onPause();
public void onResume();
@NotNull
public Bitmap captureScreenshot();
void setXRange(float xMin, float xMax);
void setYRange(float yMin, float yMax);
float getXMin();
float getXMin();
float getXMax();
float getXMax();
float getYMin();
float getYMin();
float getYMax();
float getYMax();
void invalidateGraphs();
void invalidateGraphs();
/* void increaseDensity();
void decreaseDensity();*/
/*
**********************************************************************
*
* CUSTOMIZATION
*
**********************************************************************
*/
/*
**********************************************************************
*
* CUSTOMIZATION
*
**********************************************************************
*/
/* void setBgColor(int color);
void setAxisColor(int color);*/

View File

@@ -12,48 +12,48 @@ import java.util.List;
*/
public class GraphViewHelper {
@NotNull
private PlotViewDef plotViewDef = PlotViewDef.newDefaultInstance();
@NotNull
private PlotViewDef plotViewDef = PlotViewDef.newDefaultInstance();
@NotNull
private List<PlotFunction> plotFunctions = Collections.emptyList();
@NotNull
private List<PlotFunction> plotFunctions = Collections.emptyList();
private GraphViewHelper() {
}
private GraphViewHelper() {
}
@NotNull
public static GraphViewHelper newDefaultInstance() {
return new GraphViewHelper();
}
@NotNull
public static GraphViewHelper newDefaultInstance() {
return new GraphViewHelper();
}
@NotNull
public static GraphViewHelper newInstance(@NotNull PlotViewDef plotViewDef,
@NotNull List<PlotFunction> plotFunctions) {
final GraphViewHelper result = new GraphViewHelper();
@NotNull
public static GraphViewHelper newInstance(@NotNull PlotViewDef plotViewDef,
@NotNull List<PlotFunction> plotFunctions) {
final GraphViewHelper result = new GraphViewHelper();
result.plotViewDef = plotViewDef;
result.plotFunctions = Collections.unmodifiableList(plotFunctions);
result.plotViewDef = plotViewDef;
result.plotFunctions = Collections.unmodifiableList(plotFunctions);
return result;
}
return result;
}
@NotNull
public GraphViewHelper copy(@NotNull List<PlotFunction> plotFunctions) {
final GraphViewHelper result = new GraphViewHelper();
@NotNull
public GraphViewHelper copy(@NotNull List<PlotFunction> plotFunctions) {
final GraphViewHelper result = new GraphViewHelper();
result.plotViewDef = plotViewDef;
result.plotFunctions = Collections.unmodifiableList(plotFunctions);
result.plotViewDef = plotViewDef;
result.plotFunctions = Collections.unmodifiableList(plotFunctions);
return result;
}
return result;
}
@NotNull
public List<PlotFunction> getPlotFunctions() {
return plotFunctions;
}
@NotNull
public List<PlotFunction> getPlotFunctions() {
return plotFunctions;
}
@NotNull
public PlotViewDef getPlotViewDef() {
return plotViewDef;
}
@NotNull
public PlotViewDef getPlotViewDef() {
return plotViewDef;
}
}

View File

@@ -12,77 +12,77 @@ import java.util.List;
*/
public class GraphsData {
@NotNull
private final GraphView graphView;
@NotNull
private final GraphView graphView;
@NotNull
private List<GraphData> graphs;
@NotNull
private List<GraphData> graphs;
private float lastXMin;
private float lastXMax;
private float lastXMin;
private float lastXMax;
private float lastYMin;
private float lastYMin;
private float lastYMax;
private float lastYMax;
public GraphsData(@NotNull GraphView graphView) {
this.graphView = graphView;
graphs = new ArrayList<GraphData>(graphView.getPlotFunctions().size());
}
public GraphsData(@NotNull GraphView graphView) {
this.graphView = graphView;
graphs = new ArrayList<GraphData>(graphView.getPlotFunctions().size());
}
public void clear() {
for (GraphData graph : graphs) {
graph.clear();
}
public void clear() {
for (GraphData graph : graphs) {
graph.clear();
}
while (graphView.getPlotFunctions().size() > graphs.size()) {
graphs.add(GraphData.newEmptyInstance());
}
while (graphView.getPlotFunctions().size() > graphs.size()) {
graphs.add(GraphData.newEmptyInstance());
}
lastYMin = 0;
lastYMax = 0;
}
lastYMin = 0;
lastYMax = 0;
}
@NotNull
public List<GraphData> getGraphs() {
return graphs;
}
@NotNull
public List<GraphData> getGraphs() {
return graphs;
}
public float getLastXMin() {
return lastXMin;
}
public float getLastXMin() {
return lastXMin;
}
public float getLastXMax() {
return lastXMax;
}
public float getLastXMax() {
return lastXMax;
}
public float getLastYMin() {
return lastYMin;
}
public float getLastYMin() {
return lastYMin;
}
public float getLastYMax() {
return lastYMax;
}
public float getLastYMax() {
return lastYMax;
}
void checkBoundaries(float graphHeight, float yMin, float yMax) {
if (yMin < lastYMin || yMax > lastYMax) {
float halfGraphHeight = graphHeight / 2;
clear();
lastYMin = yMin - halfGraphHeight;
lastYMax = yMax + halfGraphHeight;
}
}
void checkBoundaries(float graphHeight, float yMin, float yMax) {
if (yMin < lastYMin || yMax > lastYMax) {
float halfGraphHeight = graphHeight / 2;
clear();
lastYMin = yMin - halfGraphHeight;
lastYMax = yMax + halfGraphHeight;
}
}
public void setLastXMin(float lastXMin) {
this.lastXMin = lastXMin;
}
public void setLastXMin(float lastXMin) {
this.lastXMin = lastXMin;
}
public void setLastXMax(float lastXMax) {
this.lastXMax = lastXMax;
}
public void setLastXMax(float lastXMax) {
this.lastXMax = lastXMax;
}
@NotNull
public GraphData get(int i) {
return this.graphs.get(i);
}
@NotNull
public GraphData get(int i) {
return this.graphs.get(i);
}
}

View File

@@ -16,22 +16,22 @@ import org.solovyev.android.view.ViewFromLayoutBuilder;
public class PlotFunctionListItem implements ListItem {
private static final String PREFIX = "plot_function_";
private static final String PREFIX = "plot_function_";
@NotNull
@NotNull
private PlotFunction plotFunction;
@NotNull
private ViewBuilder<View> viewBuilder;
@NotNull
private String tag;
@NotNull
private String tag;
public PlotFunctionListItem(@NotNull PlotFunction plotFunction) {
public PlotFunctionListItem(@NotNull PlotFunction plotFunction) {
this.plotFunction = plotFunction;
this.viewBuilder = ViewFromLayoutBuilder.newInstance(R.layout.cpp_plot_function_list_item);
this.tag = PREFIX + plotFunction.getXyFunction().getExpressionString();
}
this.tag = PREFIX + plotFunction.getXyFunction().getExpressionString();
}
@Nullable
@Override
@@ -48,17 +48,17 @@ public class PlotFunctionListItem implements ListItem {
@NotNull
@Override
public View updateView(@NotNull Context context, @NotNull View view) {
final Object viewTag = view.getTag();
if ( viewTag instanceof String ) {
if ( this.tag.equals(viewTag) ) {
return view;
} else if (((String) viewTag).startsWith(PREFIX)) {
fillView(view, context);
return view;
} else {
return build(context);
}
}
final Object viewTag = view.getTag();
if (viewTag instanceof String) {
if (this.tag.equals(viewTag)) {
return view;
} else if (((String) viewTag).startsWith(PREFIX)) {
fillView(view, context);
return view;
} else {
return build(context);
}
}
return build(context);
}
@@ -71,51 +71,51 @@ public class PlotFunctionListItem implements ListItem {
return root;
}
private View buildView(@NotNull Context context) {
return viewBuilder.build(context);
}
private View buildView(@NotNull Context context) {
return viewBuilder.build(context);
}
private void fillView(@NotNull View root, @NotNull final Context context) {
root.setTag(tag);
private void fillView(@NotNull View root, @NotNull final Context context) {
root.setTag(tag);
final CalculatorPlotter plotter = Locator.getInstance().getPlotter();
final CalculatorPlotter plotter = Locator.getInstance().getPlotter();
final TextView expressionTextView = (TextView) root.findViewById(R.id.cpp_plot_function_expression_textview);
expressionTextView.setText(plotFunction.getXyFunction().getExpressionString());
final TextView expressionTextView = (TextView) root.findViewById(R.id.cpp_plot_function_expression_textview);
expressionTextView.setText(plotFunction.getXyFunction().getExpressionString());
final CheckBox pinnedCheckBox = (CheckBox) root.findViewById(R.id.cpp_plot_function_pinned_checkbox);
pinnedCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean pin) {
if (pin) {
if (!plotFunction.isPinned()) {
plotFunction = plotter.pin(plotFunction);
}
} else {
if (plotFunction.isPinned()) {
plotFunction = plotter.unpin(plotFunction);
}
}
}
});
pinnedCheckBox.setChecked(plotFunction.isPinned());
final CheckBox pinnedCheckBox = (CheckBox) root.findViewById(R.id.cpp_plot_function_pinned_checkbox);
pinnedCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean pin) {
if (pin) {
if (!plotFunction.isPinned()) {
plotFunction = plotter.pin(plotFunction);
}
} else {
if (plotFunction.isPinned()) {
plotFunction = plotter.unpin(plotFunction);
}
}
}
});
pinnedCheckBox.setChecked(plotFunction.isPinned());
final CheckBox visibleCheckBox = (CheckBox) root.findViewById(R.id.cpp_plot_function_visible_checkbox);
visibleCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean show) {
if (show) {
if (!plotFunction.isVisible()) {
plotFunction = plotter.show(plotFunction);
}
} else {
if (plotFunction.isVisible()) {
plotFunction = plotter.hide(plotFunction);
}
}
}
});
visibleCheckBox.setChecked(plotFunction.isVisible());
final CheckBox visibleCheckBox = (CheckBox) root.findViewById(R.id.cpp_plot_function_visible_checkbox);
visibleCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean show) {
if (show) {
if (!plotFunction.isVisible()) {
plotFunction = plotter.show(plotFunction);
}
} else {
if (plotFunction.isVisible()) {
plotFunction = plotter.hide(plotFunction);
}
}
}
});
visibleCheckBox.setChecked(plotFunction.isVisible());
final ImageButton settingsButton = (ImageButton) root.findViewById(R.id.cpp_plot_function_settings_button);
settingsButton.setOnClickListener(new View.OnClickListener() {
@@ -124,5 +124,5 @@ public class PlotFunctionListItem implements ListItem {
CalculatorPlotFunctionSettingsActivity.startActivity(context, plotFunction);
}
});
}
}
}

View File

@@ -10,67 +10,67 @@ import org.jetbrains.annotations.NotNull;
*/
public class PlotViewDef {
/*
**********************************************************************
*
* CONSTANTS
*
**********************************************************************
*/
/*
**********************************************************************
*
* CONSTANTS
*
**********************************************************************
*/
private static final int DEFAULT_AXIS_COLOR = 0xff00a000;
private static final int DEFAULT_GRID_COLOR = 0xff004000;
private static final int DEFAULT_BACKGROUND_COLOR = Color.BLACK;
private static final int DEFAULT_AXIS_COLOR = 0xff00a000;
private static final int DEFAULT_GRID_COLOR = 0xff004000;
private static final int DEFAULT_BACKGROUND_COLOR = Color.BLACK;
/*
**********************************************************************
*
* FIELDS
*
**********************************************************************
*/
/*
**********************************************************************
*
* FIELDS
*
**********************************************************************
*/
private int axisColor = DEFAULT_AXIS_COLOR;
private int axisColor = DEFAULT_AXIS_COLOR;
private int axisLabelsColor = DEFAULT_AXIS_COLOR;
private int axisLabelsColor = DEFAULT_AXIS_COLOR;
private int gridColor = DEFAULT_GRID_COLOR;
private int gridColor = DEFAULT_GRID_COLOR;
private int backgroundColor = DEFAULT_BACKGROUND_COLOR;
private int backgroundColor = DEFAULT_BACKGROUND_COLOR;
private PlotViewDef() {
}
private PlotViewDef() {
}
private PlotViewDef(int axisColor, int axisLabelColor, int gridColor, int backgroundColor) {
this.axisColor = axisColor;
this.axisLabelsColor = axisLabelColor;
this.gridColor = gridColor;
this.backgroundColor = backgroundColor;
}
private PlotViewDef(int axisColor, int axisLabelColor, int gridColor, int backgroundColor) {
this.axisColor = axisColor;
this.axisLabelsColor = axisLabelColor;
this.gridColor = gridColor;
this.backgroundColor = backgroundColor;
}
@NotNull
public static PlotViewDef newDefaultInstance() {
return new PlotViewDef();
}
@NotNull
public static PlotViewDef newDefaultInstance() {
return new PlotViewDef();
}
@NotNull
public static PlotViewDef newInstance(int axisColor, int axisLabelColor, int gridColor, int backgroundColor) {
return new PlotViewDef(axisColor, axisLabelColor, gridColor, backgroundColor);
}
@NotNull
public static PlotViewDef newInstance(int axisColor, int axisLabelColor, int gridColor, int backgroundColor) {
return new PlotViewDef(axisColor, axisLabelColor, gridColor, backgroundColor);
}
public int getAxisColor() {
return axisColor;
}
public int getAxisColor() {
return axisColor;
}
public int getAxisLabelsColor() {
return axisLabelsColor;
}
public int getAxisLabelsColor() {
return axisLabelsColor;
}
public int getGridColor() {
return gridColor;
}
public int getGridColor() {
return gridColor;
}
public int getBackgroundColor() {
return backgroundColor;
}
public int getBackgroundColor() {
return backgroundColor;
}
}

View File

@@ -4,117 +4,118 @@ import javax.microedition.khronos.opengles.GL10;
public class SpriteBatch {
//--Constants--//
final static int VERTEX_SIZE = 4; // Vertex Size (in Components) ie. (X,Y,U,V)
final static int VERTICES_PER_SPRITE = 4; // Vertices Per Sprite
final static int INDICES_PER_SPRITE = 6; // Indices Per Sprite
//--Constants--//
final static int VERTEX_SIZE = 4; // Vertex Size (in Components) ie. (X,Y,U,V)
final static int VERTICES_PER_SPRITE = 4; // Vertices Per Sprite
final static int INDICES_PER_SPRITE = 6; // Indices Per Sprite
//--Members--//
GL10 gl; // GL Instance
Vertices vertices; // Vertices Instance Used for Rendering
float[] vertexBuffer; // Vertex Buffer
int bufferIndex; // Vertex Buffer Start Index
int maxSprites; // Maximum Sprites Allowed in Buffer
int numSprites; // Number of Sprites Currently in Buffer
//--Members--//
GL10 gl; // GL Instance
Vertices vertices; // Vertices Instance Used for Rendering
float[] vertexBuffer; // Vertex Buffer
int bufferIndex; // Vertex Buffer Start Index
int maxSprites; // Maximum Sprites Allowed in Buffer
int numSprites; // Number of Sprites Currently in Buffer
//--Constructor--//
// D: prepare the sprite batcher for specified maximum number of sprites
// A: gl - the gl instance to use for rendering
// maxSprites - the maximum allowed sprites per batch
public SpriteBatch(GL10 gl, int maxSprites) {
this.gl = gl; // Save GL Instance
this.vertexBuffer = new float[maxSprites * VERTICES_PER_SPRITE * VERTEX_SIZE]; // Create Vertex Buffer
this.vertices = new Vertices( gl, maxSprites * VERTICES_PER_SPRITE, maxSprites * INDICES_PER_SPRITE, false, true, false ); // Create Rendering Vertices
this.bufferIndex = 0; // Reset Buffer Index
this.maxSprites = maxSprites; // Save Maximum Sprites
this.numSprites = 0; // Clear Sprite Counter
//--Constructor--//
// D: prepare the sprite batcher for specified maximum number of sprites
// A: gl - the gl instance to use for rendering
// maxSprites - the maximum allowed sprites per batch
public SpriteBatch(GL10 gl, int maxSprites) {
this.gl = gl; // Save GL Instance
this.vertexBuffer = new float[maxSprites * VERTICES_PER_SPRITE * VERTEX_SIZE]; // Create Vertex Buffer
this.vertices = new Vertices(gl, maxSprites * VERTICES_PER_SPRITE, maxSprites * INDICES_PER_SPRITE, false, true, false); // Create Rendering Vertices
this.bufferIndex = 0; // Reset Buffer Index
this.maxSprites = maxSprites; // Save Maximum Sprites
this.numSprites = 0; // Clear Sprite Counter
short[] indices = new short[maxSprites * INDICES_PER_SPRITE]; // Create Temp Index Buffer
int len = indices.length; // Get Index Buffer Length
short j = 0; // Counter
for ( int i = 0; i < len; i+= INDICES_PER_SPRITE, j += VERTICES_PER_SPRITE ) { // FOR Each Index Set (Per Sprite)
indices[i + 0] = (short)( j + 0 ); // Calculate Index 0
indices[i + 1] = (short)( j + 1 ); // Calculate Index 1
indices[i + 2] = (short)( j + 2 ); // Calculate Index 2
indices[i + 3] = (short)( j + 2 ); // Calculate Index 3
indices[i + 4] = (short)( j + 3 ); // Calculate Index 4
indices[i + 5] = (short)( j + 0 ); // Calculate Index 5
}
vertices.setIndices( indices, 0, len ); // Set Index Buffer for Rendering
}
short[] indices = new short[maxSprites * INDICES_PER_SPRITE]; // Create Temp Index Buffer
int len = indices.length; // Get Index Buffer Length
short j = 0; // Counter
for (int i = 0; i < len; i += INDICES_PER_SPRITE, j += VERTICES_PER_SPRITE) { // FOR Each Index Set (Per Sprite)
indices[i + 0] = (short) (j + 0); // Calculate Index 0
indices[i + 1] = (short) (j + 1); // Calculate Index 1
indices[i + 2] = (short) (j + 2); // Calculate Index 2
indices[i + 3] = (short) (j + 2); // Calculate Index 3
indices[i + 4] = (short) (j + 3); // Calculate Index 4
indices[i + 5] = (short) (j + 0); // Calculate Index 5
}
vertices.setIndices(indices, 0, len); // Set Index Buffer for Rendering
}
//--Begin Batch--//
// D: signal the start of a batch. set the texture and clear buffer
// NOTE: the overloaded (non-texture) version assumes that the texture is already bound!
// A: textureId - the ID of the texture to use for the batch
// R: [none]
public void beginBatch(int textureId) {
gl.glBindTexture( GL10.GL_TEXTURE_2D, textureId ); // Bind the Texture
numSprites = 0; // Empty Sprite Counter
bufferIndex = 0; // Reset Buffer Index (Empty)
}
public void beginBatch() {
numSprites = 0; // Empty Sprite Counter
bufferIndex = 0; // Reset Buffer Index (Empty)
}
//--Begin Batch--//
// D: signal the start of a batch. set the texture and clear buffer
// NOTE: the overloaded (non-texture) version assumes that the texture is already bound!
// A: textureId - the ID of the texture to use for the batch
// R: [none]
public void beginBatch(int textureId) {
gl.glBindTexture(GL10.GL_TEXTURE_2D, textureId); // Bind the Texture
numSprites = 0; // Empty Sprite Counter
bufferIndex = 0; // Reset Buffer Index (Empty)
}
//--End Batch--//
// D: signal the end of a batch. render the batched sprites
// A: [none]
// R: [none]
public void endBatch() {
if ( numSprites > 0 ) { // IF Any Sprites to Render
vertices.setVertices( vertexBuffer, 0, bufferIndex ); // Set Vertices from Buffer
vertices.bind(); // Bind Vertices
vertices.draw( GL10.GL_TRIANGLES, 0, numSprites * INDICES_PER_SPRITE ); // Render Batched Sprites
vertices.unbind(); // Unbind Vertices
}
}
public void beginBatch() {
numSprites = 0; // Empty Sprite Counter
bufferIndex = 0; // Reset Buffer Index (Empty)
}
//--Draw Sprite to Batch--//
// D: batch specified sprite to batch. adds vertices for sprite to vertex buffer
// NOTE: MUST be called after beginBatch(), and before endBatch()!
// NOTE: if the batch overflows, this will render the current batch, restart it,
// and then batch this sprite.
// A: x, y - the x,y position of the sprite (center)
// width, height - the width and height of the sprite
// region - the texture region to use for sprite
// R: [none]
public void drawSprite(float x, float y, float width, float height, TextureRegion region) {
if ( numSprites == maxSprites ) { // IF Sprite Buffer is Full
endBatch(); // End Batch
// NOTE: leave current texture bound!!
numSprites = 0; // Empty Sprite Counter
bufferIndex = 0; // Reset Buffer Index (Empty)
}
//--End Batch--//
// D: signal the end of a batch. render the batched sprites
// A: [none]
// R: [none]
public void endBatch() {
if (numSprites > 0) { // IF Any Sprites to Render
vertices.setVertices(vertexBuffer, 0, bufferIndex); // Set Vertices from Buffer
vertices.bind(); // Bind Vertices
vertices.draw(GL10.GL_TRIANGLES, 0, numSprites * INDICES_PER_SPRITE); // Render Batched Sprites
vertices.unbind(); // Unbind Vertices
}
}
float halfWidth = width / 2.0f; // Calculate Half Width
float halfHeight = height / 2.0f; // Calculate Half Height
float x1 = x - halfWidth; // Calculate Left X
float y1 = y - halfHeight; // Calculate Bottom Y
float x2 = x + halfWidth; // Calculate Right X
float y2 = y + halfHeight; // Calculate Top Y
//--Draw Sprite to Batch--//
// D: batch specified sprite to batch. adds vertices for sprite to vertex buffer
// NOTE: MUST be called after beginBatch(), and before endBatch()!
// NOTE: if the batch overflows, this will render the current batch, restart it,
// and then batch this sprite.
// A: x, y - the x,y position of the sprite (center)
// width, height - the width and height of the sprite
// region - the texture region to use for sprite
// R: [none]
public void drawSprite(float x, float y, float width, float height, TextureRegion region) {
if (numSprites == maxSprites) { // IF Sprite Buffer is Full
endBatch(); // End Batch
// NOTE: leave current texture bound!!
numSprites = 0; // Empty Sprite Counter
bufferIndex = 0; // Reset Buffer Index (Empty)
}
vertexBuffer[bufferIndex++] = x1; // Add X for Vertex 0
vertexBuffer[bufferIndex++] = y1; // Add Y for Vertex 0
vertexBuffer[bufferIndex++] = region.u1; // Add U for Vertex 0
vertexBuffer[bufferIndex++] = region.v2; // Add V for Vertex 0
float halfWidth = width / 2.0f; // Calculate Half Width
float halfHeight = height / 2.0f; // Calculate Half Height
float x1 = x - halfWidth; // Calculate Left X
float y1 = y - halfHeight; // Calculate Bottom Y
float x2 = x + halfWidth; // Calculate Right X
float y2 = y + halfHeight; // Calculate Top Y
vertexBuffer[bufferIndex++] = x2; // Add X for Vertex 1
vertexBuffer[bufferIndex++] = y1; // Add Y for Vertex 1
vertexBuffer[bufferIndex++] = region.u2; // Add U for Vertex 1
vertexBuffer[bufferIndex++] = region.v2; // Add V for Vertex 1
vertexBuffer[bufferIndex++] = x1; // Add X for Vertex 0
vertexBuffer[bufferIndex++] = y1; // Add Y for Vertex 0
vertexBuffer[bufferIndex++] = region.u1; // Add U for Vertex 0
vertexBuffer[bufferIndex++] = region.v2; // Add V for Vertex 0
vertexBuffer[bufferIndex++] = x2; // Add X for Vertex 2
vertexBuffer[bufferIndex++] = y2; // Add Y for Vertex 2
vertexBuffer[bufferIndex++] = region.u2; // Add U for Vertex 2
vertexBuffer[bufferIndex++] = region.v1; // Add V for Vertex 2
vertexBuffer[bufferIndex++] = x2; // Add X for Vertex 1
vertexBuffer[bufferIndex++] = y1; // Add Y for Vertex 1
vertexBuffer[bufferIndex++] = region.u2; // Add U for Vertex 1
vertexBuffer[bufferIndex++] = region.v2; // Add V for Vertex 1
vertexBuffer[bufferIndex++] = x1; // Add X for Vertex 3
vertexBuffer[bufferIndex++] = y2; // Add Y for Vertex 3
vertexBuffer[bufferIndex++] = region.u1; // Add U for Vertex 3
vertexBuffer[bufferIndex++] = region.v1; // Add V for Vertex 3
vertexBuffer[bufferIndex++] = x2; // Add X for Vertex 2
vertexBuffer[bufferIndex++] = y2; // Add Y for Vertex 2
vertexBuffer[bufferIndex++] = region.u2; // Add U for Vertex 2
vertexBuffer[bufferIndex++] = region.v1; // Add V for Vertex 2
numSprites++; // Increment Sprite Count
}
vertexBuffer[bufferIndex++] = x1; // Add X for Vertex 3
vertexBuffer[bufferIndex++] = y2; // Add Y for Vertex 3
vertexBuffer[bufferIndex++] = region.u1; // Add U for Vertex 3
vertexBuffer[bufferIndex++] = region.v1; // Add V for Vertex 3
numSprites++; // Increment Sprite Count
}
}

View File

@@ -9,81 +9,81 @@ import android.opengl.GLSurfaceView;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
public class TexampleRenderer implements GLSurfaceView.Renderer {
public class TexampleRenderer implements GLSurfaceView.Renderer {
private GLText glText; // A GLText Instance
private Context context; // Context (from Activity)
private GLText glText; // A GLText Instance
private Context context; // Context (from Activity)
private int width = 100; // Updated to the Current Width + Height in onSurfaceChanged()
private int height = 100;
private int width = 100; // Updated to the Current Width + Height in onSurfaceChanged()
private int height = 100;
public TexampleRenderer(Context context) {
super();
this.context = context; // Save Specified Context
}
public TexampleRenderer(Context context) {
super();
this.context = context; // Save Specified Context
}
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
// Set the background frame color
gl.glClearColor( 0.5f, 0.5f, 0.5f, 1.0f );
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
// Set the background frame color
gl.glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
// Create the GLText
glText = new GLText( gl, context.getAssets() );
// Create the GLText
glText = new GLText(gl, context.getAssets());
// Load the font from file (set size + padding), creates the texture
// NOTE: after a successful call to this the font is ready for rendering!
glText.load( "Roboto-Regular.ttf", 14, 2, 2 ); // Create Font (Height: 14 Pixels / X+Y Padding 2 Pixels)
}
// Load the font from file (set size + padding), creates the texture
// NOTE: after a successful call to this the font is ready for rendering!
glText.load("Roboto-Regular.ttf", 14, 2, 2); // Create Font (Height: 14 Pixels / X+Y Padding 2 Pixels)
}
public void onDrawFrame(GL10 gl) {
// Redraw background color
gl.glClear( GL10.GL_COLOR_BUFFER_BIT );
public void onDrawFrame(GL10 gl) {
// Redraw background color
gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
// Set to ModelView mode
gl.glMatrixMode( GL10.GL_MODELVIEW ); // Activate Model View Matrix
gl.glLoadIdentity(); // Load Identity Matrix
// Set to ModelView mode
gl.glMatrixMode(GL10.GL_MODELVIEW); // Activate Model View Matrix
gl.glLoadIdentity(); // Load Identity Matrix
// enable texture + alpha blending
// NOTE: this is required for text rendering! we could incorporate it into
// the GLText class, but then it would be called multiple times (which impacts performance).
gl.glEnable( GL10.GL_TEXTURE_2D ); // Enable Texture Mapping
gl.glEnable( GL10.GL_BLEND ); // Enable Alpha Blend
gl.glBlendFunc( GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA ); // Set Alpha Blend Function
// enable texture + alpha blending
// NOTE: this is required for text rendering! we could incorporate it into
// the GLText class, but then it would be called multiple times (which impacts performance).
gl.glEnable(GL10.GL_TEXTURE_2D); // Enable Texture Mapping
gl.glEnable(GL10.GL_BLEND); // Enable Alpha Blend
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); // Set Alpha Blend Function
// TEST: render the entire font texture
gl.glColor4f( 1.0f, 1.0f, 1.0f, 1.0f ); // Set Color to Use
glText.drawTexture( width, height ); // Draw the Entire Texture
// TEST: render the entire font texture
gl.glColor4f(1.0f, 1.0f, 1.0f, 1.0f); // Set Color to Use
glText.drawTexture(width, height); // Draw the Entire Texture
// TEST: render some strings with the font
glText.begin( 1.0f, 1.0f, 1.0f, 1.0f ); // Begin Text Rendering (Set Color WHITE)
glText.draw( "Test String :)", 0, 0 ); // Draw Test String
glText.draw( "Line 1", 50, 50 ); // Draw Test String
glText.draw( "Line 2", 100, 100 ); // Draw Test String
glText.end(); // End Text Rendering
// TEST: render some strings with the font
glText.begin(1.0f, 1.0f, 1.0f, 1.0f); // Begin Text Rendering (Set Color WHITE)
glText.draw("Test String :)", 0, 0); // Draw Test String
glText.draw("Line 1", 50, 50); // Draw Test String
glText.draw("Line 2", 100, 100); // Draw Test String
glText.end(); // End Text Rendering
glText.begin( 0.0f, 0.0f, 1.0f, 1.0f ); // Begin Text Rendering (Set Color BLUE)
glText.draw( "More Lines...", 50, 150 ); // Draw Test String
glText.draw( "The End.", 50, 150 + glText.getCharHeight() ); // Draw Test String
glText.end(); // End Text Rendering
glText.begin(0.0f, 0.0f, 1.0f, 1.0f); // Begin Text Rendering (Set Color BLUE)
glText.draw("More Lines...", 50, 150); // Draw Test String
glText.draw("The End.", 50, 150 + glText.getCharHeight()); // Draw Test String
glText.end(); // End Text Rendering
// disable texture + alpha
gl.glDisable( GL10.GL_BLEND ); // Disable Alpha Blend
gl.glDisable( GL10.GL_TEXTURE_2D ); // Disable Texture Mapping
}
// disable texture + alpha
gl.glDisable(GL10.GL_BLEND); // Disable Alpha Blend
gl.glDisable(GL10.GL_TEXTURE_2D); // Disable Texture Mapping
}
public void onSurfaceChanged(GL10 gl, int width, int height) {
gl.glViewport( 0, 0, width, height );
public void onSurfaceChanged(GL10 gl, int width, int height) {
gl.glViewport(0, 0, width, height);
// Setup orthographic projection
gl.glMatrixMode( GL10.GL_PROJECTION ); // Activate Projection Matrix
gl.glLoadIdentity(); // Load Identity Matrix
gl.glOrthof( // Set Ortho Projection (Left,Right,Bottom,Top,Front,Back)
0, width,
0, height,
1.0f, -1.0f
);
// Setup orthographic projection
gl.glMatrixMode(GL10.GL_PROJECTION); // Activate Projection Matrix
gl.glLoadIdentity(); // Load Identity Matrix
gl.glOrthof( // Set Ortho Projection (Left,Right,Bottom,Top,Front,Back)
0, width,
0, height,
1.0f, -1.0f
);
// Save width and height
this.width = width; // Save Current Width
this.height = height; // Save Current Height
}
// Save width and height
this.width = width; // Save Current Width
this.height = height; // Save Current Height
}
}

View File

@@ -2,19 +2,19 @@ package org.solovyev.android.calculator.plot;
class TextureRegion {
//--Members--//
public float u1, v1; // Top/Left U,V Coordinates
public float u2, v2; // Bottom/Right U,V Coordinates
//--Members--//
public float u1, v1; // Top/Left U,V Coordinates
public float u2, v2; // Bottom/Right U,V Coordinates
//--Constructor--//
// D: calculate U,V coordinates from specified texture coordinates
// A: texWidth, texHeight - the width and height of the texture the region is for
// x, y - the top/left (x,y) of the region on the texture (in pixels)
// width, height - the width and height of the region on the texture (in pixels)
public TextureRegion(float texWidth, float texHeight, float x, float y, float width, float height) {
this.u1 = x / texWidth; // Calculate U1
this.v1 = y / texHeight; // Calculate V1
this.u2 = this.u1 + ( width / texWidth ); // Calculate U2
this.v2 = this.v1 + ( height / texHeight ); // Calculate V2
}
//--Constructor--//
// D: calculate U,V coordinates from specified texture coordinates
// A: texWidth, texHeight - the width and height of the texture the region is for
// x, y - the top/left (x,y) of the region on the texture (in pixels)
// width, height - the width and height of the region on the texture (in pixels)
public TextureRegion(float texWidth, float texHeight, float x, float y, float width, float height) {
this.u1 = x / texWidth; // Calculate U1
this.v1 = y / texHeight; // Calculate V1
this.u2 = this.u1 + (width / texWidth); // Calculate U2
this.v2 = this.v1 + (height / texHeight); // Calculate V2
}
}

View File

@@ -9,90 +9,90 @@ import org.solovyev.android.Views;
class TouchHandler {
static interface TouchHandlerListener {
void onTouchDown(float x, float y);
static interface TouchHandlerListener {
void onTouchDown(float x, float y);
void onTouchMove(float x, float y);
void onTouchMove(float x, float y);
void onTouchUp(float x, float y);
void onTouchUp(float x, float y);
void onTouchZoomDown(float x1, float y1, float x2, float y2);
void onTouchZoomDown(float x1, float y1, float x2, float y2);
void onTouchZoomMove(float x1, float y1, float x2, float y2);
}
void onTouchZoomMove(float x1, float y1, float x2, float y2);
}
@NotNull
private final VelocityTracker velocityTracker = VelocityTracker.obtain();
@NotNull
private final VelocityTracker velocityTracker = VelocityTracker.obtain();
private boolean afterZoom;
private boolean afterZoom;
@NotNull
private TouchHandlerListener listener;
@NotNull
private TouchHandlerListener listener;
TouchHandler(@NotNull TouchHandlerListener listener) {
this.listener = listener;
}
TouchHandler(@NotNull TouchHandlerListener listener) {
this.listener = listener;
}
public boolean handleTouchEvent(@NotNull MotionEvent event) {
// Calculator.log("touch " + event + ' ' + event.getPointerCount() + event.getPointerId(0));
public boolean handleTouchEvent(@NotNull MotionEvent event) {
// Calculator.log("touch " + event + ' ' + event.getPointerCount() + event.getPointerId(0));
final int fullAction = event.getAction();
final int action = fullAction & MotionEvent.ACTION_MASK;
final int pointer = (fullAction & MotionEvent.ACTION_POINTER_ID_MASK) >> MotionEvent.ACTION_POINTER_ID_SHIFT;
final int fullAction = event.getAction();
final int action = fullAction & MotionEvent.ACTION_MASK;
final int pointer = (fullAction & MotionEvent.ACTION_POINTER_ID_MASK) >> MotionEvent.ACTION_POINTER_ID_SHIFT;
float x = event.getX();
float y = event.getY();
float x = event.getX();
float y = event.getY();
int pointerCount = Views.getPointerCountFromMotionEvent(event);
int pointerCount = Views.getPointerCountFromMotionEvent(event);
switch (action) {
case MotionEvent.ACTION_DOWN:
afterZoom = false;
velocityTracker.clear();
velocityTracker.addMovement(event);
listener.onTouchDown(x, y);
break;
switch (action) {
case MotionEvent.ACTION_DOWN:
afterZoom = false;
velocityTracker.clear();
velocityTracker.addMovement(event);
listener.onTouchDown(x, y);
break;
case MotionEvent.ACTION_MOVE:
if (pointerCount == 1) {
if (afterZoom) {
velocityTracker.clear();
listener.onTouchDown(x, y);
afterZoom = false;
}
velocityTracker.addMovement(event);
listener.onTouchMove(x, y);
} else if (pointerCount == 2) {
listener.onTouchZoomMove(x, y, Views.getXFromMotionEvent(event, 1), Views.getYFromMotionEvent(event, 1));
}
break;
case MotionEvent.ACTION_MOVE:
if (pointerCount == 1) {
if (afterZoom) {
velocityTracker.clear();
listener.onTouchDown(x, y);
afterZoom = false;
}
velocityTracker.addMovement(event);
listener.onTouchMove(x, y);
} else if (pointerCount == 2) {
listener.onTouchZoomMove(x, y, Views.getXFromMotionEvent(event, 1), Views.getYFromMotionEvent(event, 1));
}
break;
case MotionEvent.ACTION_UP:
velocityTracker.addMovement(event);
velocityTracker.computeCurrentVelocity(1000);
listener.onTouchUp(x, y);
break;
case MotionEvent.ACTION_UP:
velocityTracker.addMovement(event);
velocityTracker.computeCurrentVelocity(1000);
listener.onTouchUp(x, y);
break;
case MotionEvent.ACTION_POINTER_DOWN:
if (pointerCount == 2) {
listener.onTouchZoomDown(x, y, Views.getXFromMotionEvent(event, 1), Views.getYFromMotionEvent(event, 1));
}
break;
case MotionEvent.ACTION_POINTER_DOWN:
if (pointerCount == 2) {
listener.onTouchZoomDown(x, y, Views.getXFromMotionEvent(event, 1), Views.getYFromMotionEvent(event, 1));
}
break;
case MotionEvent.ACTION_POINTER_UP:
if (pointerCount == 2) {
afterZoom = true;
}
break;
}
return true;
}
case MotionEvent.ACTION_POINTER_UP:
if (pointerCount == 2) {
afterZoom = true;
}
break;
}
return true;
}
public float getXVelocity() {
return velocityTracker.getXVelocity();
}
public float getXVelocity() {
return velocityTracker.getXVelocity();
}
public float getYVelocity() {
return velocityTracker.getYVelocity();
}
public float getYVelocity() {
return velocityTracker.getYVelocity();
}
}

View File

@@ -1,257 +1,260 @@
package org.solovyev.android.calculator.plot;
import javax.microedition.khronos.opengles.GL10;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;
import javax.microedition.khronos.opengles.GL10;
public class Vertices {
//--Constants--//
final static int POSITION_CNT_2D = 2; // Number of Components in Vertex Position for 2D
final static int POSITION_CNT_3D = 3; // Number of Components in Vertex Position for 3D
final static int COLOR_CNT = 4; // Number of Components in Vertex Color
final static int TEXCOORD_CNT = 2; // Number of Components in Vertex Texture Coords
final static int NORMAL_CNT = 3; // Number of Components in Vertex Normal
//--Constants--//
final static int POSITION_CNT_2D = 2; // Number of Components in Vertex Position for 2D
final static int POSITION_CNT_3D = 3; // Number of Components in Vertex Position for 3D
final static int COLOR_CNT = 4; // Number of Components in Vertex Color
final static int TEXCOORD_CNT = 2; // Number of Components in Vertex Texture Coords
final static int NORMAL_CNT = 3; // Number of Components in Vertex Normal
final static int INDEX_SIZE = Short.SIZE / 8; // Index Byte Size (Short.SIZE = bits)
final static int INDEX_SIZE = Short.SIZE / 8; // Index Byte Size (Short.SIZE = bits)
//--Members--//
// NOTE: all members are constant, and initialized in constructor!
final GL10 gl; // GL Instance
final boolean hasColor; // Use Color in Vertices
final boolean hasTexCoords; // Use Texture Coords in Vertices
final boolean hasNormals; // Use Normals in Vertices
public final int positionCnt; // Number of Position Components (2=2D, 3=3D)
public final int vertexStride; // Vertex Stride (Element Size of a Single Vertex)
public final int vertexSize; // Bytesize of a Single Vertex
final IntBuffer vertices; // Vertex Buffer
final ShortBuffer indices; // Index Buffer
public int numVertices; // Number of Vertices in Buffer
public int numIndices; // Number of Indices in Buffer
final int[] tmpBuffer; // Temp Buffer for Vertex Conversion
//--Members--//
// NOTE: all members are constant, and initialized in constructor!
final GL10 gl; // GL Instance
final boolean hasColor; // Use Color in Vertices
final boolean hasTexCoords; // Use Texture Coords in Vertices
final boolean hasNormals; // Use Normals in Vertices
public final int positionCnt; // Number of Position Components (2=2D, 3=3D)
public final int vertexStride; // Vertex Stride (Element Size of a Single Vertex)
public final int vertexSize; // Bytesize of a Single Vertex
final IntBuffer vertices; // Vertex Buffer
final ShortBuffer indices; // Index Buffer
public int numVertices; // Number of Vertices in Buffer
public int numIndices; // Number of Indices in Buffer
final int[] tmpBuffer; // Temp Buffer for Vertex Conversion
//--Constructor--//
// D: create the vertices/indices as specified (for 2d/3d)
// A: gl - the gl instance to use
// maxVertices - maximum vertices allowed in buffer
// maxIndices - maximum indices allowed in buffer
// hasColor - use color values in vertices
// hasTexCoords - use texture coordinates in vertices
// hasNormals - use normals in vertices
// use3D - (false, default) use 2d positions (ie. x/y only)
// (true) use 3d positions (ie. x/y/z)
public Vertices(GL10 gl, int maxVertices, int maxIndices, boolean hasColor, boolean hasTexCoords, boolean hasNormals) {
this( gl, maxVertices, maxIndices, hasColor, hasTexCoords, hasNormals, false ); // Call Overloaded Constructor
}
public Vertices(GL10 gl, int maxVertices, int maxIndices, boolean hasColor, boolean hasTexCoords, boolean hasNormals, boolean use3D) {
this.gl = gl; // Save GL Instance
this.hasColor = hasColor; // Save Color Flag
this.hasTexCoords = hasTexCoords; // Save Texture Coords Flag
this.hasNormals = hasNormals; // Save Normals Flag
this.positionCnt = use3D ? POSITION_CNT_3D : POSITION_CNT_2D; // Set Position Component Count
this.vertexStride = this.positionCnt + ( hasColor ? COLOR_CNT : 0 ) + ( hasTexCoords ? TEXCOORD_CNT : 0 ) + ( hasNormals ? NORMAL_CNT : 0 ); // Calculate Vertex Stride
this.vertexSize = this.vertexStride * 4; // Calculate Vertex Byte Size
//--Constructor--//
// D: create the vertices/indices as specified (for 2d/3d)
// A: gl - the gl instance to use
// maxVertices - maximum vertices allowed in buffer
// maxIndices - maximum indices allowed in buffer
// hasColor - use color values in vertices
// hasTexCoords - use texture coordinates in vertices
// hasNormals - use normals in vertices
// use3D - (false, default) use 2d positions (ie. x/y only)
// (true) use 3d positions (ie. x/y/z)
public Vertices(GL10 gl, int maxVertices, int maxIndices, boolean hasColor, boolean hasTexCoords, boolean hasNormals) {
this(gl, maxVertices, maxIndices, hasColor, hasTexCoords, hasNormals, false); // Call Overloaded Constructor
}
ByteBuffer buffer = ByteBuffer.allocateDirect( maxVertices * vertexSize ); // Allocate Buffer for Vertices (Max)
buffer.order( ByteOrder.nativeOrder() ); // Set Native Byte Order
this.vertices = buffer.asIntBuffer(); // Save Vertex Buffer
public Vertices(GL10 gl, int maxVertices, int maxIndices, boolean hasColor, boolean hasTexCoords, boolean hasNormals, boolean use3D) {
this.gl = gl; // Save GL Instance
this.hasColor = hasColor; // Save Color Flag
this.hasTexCoords = hasTexCoords; // Save Texture Coords Flag
this.hasNormals = hasNormals; // Save Normals Flag
this.positionCnt = use3D ? POSITION_CNT_3D : POSITION_CNT_2D; // Set Position Component Count
this.vertexStride = this.positionCnt + (hasColor ? COLOR_CNT : 0) + (hasTexCoords ? TEXCOORD_CNT : 0) + (hasNormals ? NORMAL_CNT : 0); // Calculate Vertex Stride
this.vertexSize = this.vertexStride * 4; // Calculate Vertex Byte Size
if ( maxIndices > 0 ) { // IF Indices Required
buffer = ByteBuffer.allocateDirect( maxIndices * INDEX_SIZE ); // Allocate Buffer for Indices (MAX)
buffer.order( ByteOrder.nativeOrder() ); // Set Native Byte Order
this.indices = buffer.asShortBuffer(); // Save Index Buffer
}
else // ELSE Indices Not Required
indices = null; // No Index Buffer
ByteBuffer buffer = ByteBuffer.allocateDirect(maxVertices * vertexSize); // Allocate Buffer for Vertices (Max)
buffer.order(ByteOrder.nativeOrder()); // Set Native Byte Order
this.vertices = buffer.asIntBuffer(); // Save Vertex Buffer
numVertices = 0; // Zero Vertices in Buffer
numIndices = 0; // Zero Indices in Buffer
if (maxIndices > 0) { // IF Indices Required
buffer = ByteBuffer.allocateDirect(maxIndices * INDEX_SIZE); // Allocate Buffer for Indices (MAX)
buffer.order(ByteOrder.nativeOrder()); // Set Native Byte Order
this.indices = buffer.asShortBuffer(); // Save Index Buffer
} else // ELSE Indices Not Required
indices = null; // No Index Buffer
this.tmpBuffer = new int[maxVertices * vertexSize / 4]; // Create Temp Buffer
}
numVertices = 0; // Zero Vertices in Buffer
numIndices = 0; // Zero Indices in Buffer
//--Set Vertices--//
// D: set the specified vertices in the vertex buffer
// NOTE: optimized to use integer buffer!
// A: vertices - array of vertices (floats) to set
// offset - offset to first vertex in array
// length - number of floats in the vertex array (total)
// for easy setting use: vtx_cnt * (this.vertexSize / 4)
// R: [none]
public void setVertices(float[] vertices, int offset, int length) {
this.vertices.clear(); // Remove Existing Vertices
int last = offset + length; // Calculate Last Element
for ( int i = offset, j = 0; i < last; i++, j++ ) // FOR Each Specified Vertex
tmpBuffer[j] = Float.floatToRawIntBits( vertices[i] ); // Set Vertex as Raw Integer Bits in Buffer
this.vertices.put( tmpBuffer, 0, length ); // Set New Vertices
this.vertices.flip(); // Flip Vertex Buffer
this.numVertices = length / this.vertexStride; // Save Number of Vertices
//this.numVertices = length / ( this.vertexSize / 4 ); // Save Number of Vertices
}
this.tmpBuffer = new int[maxVertices * vertexSize / 4]; // Create Temp Buffer
}
//--Set Indices--//
// D: set the specified indices in the index buffer
// A: indices - array of indices (shorts) to set
// offset - offset to first index in array
// length - number of indices in array (from offset)
// R: [none]
public void setIndices(short[] indices, int offset, int length) {
this.indices.clear(); // Clear Existing Indices
this.indices.put( indices, offset, length ); // Set New Indices
this.indices.flip(); // Flip Index Buffer
this.numIndices = length; // Save Number of Indices
}
//--Set Vertices--//
// D: set the specified vertices in the vertex buffer
// NOTE: optimized to use integer buffer!
// A: vertices - array of vertices (floats) to set
// offset - offset to first vertex in array
// length - number of floats in the vertex array (total)
// for easy setting use: vtx_cnt * (this.vertexSize / 4)
// R: [none]
public void setVertices(float[] vertices, int offset, int length) {
this.vertices.clear(); // Remove Existing Vertices
int last = offset + length; // Calculate Last Element
for (int i = offset, j = 0; i < last; i++, j++) // FOR Each Specified Vertex
tmpBuffer[j] = Float.floatToRawIntBits(vertices[i]); // Set Vertex as Raw Integer Bits in Buffer
this.vertices.put(tmpBuffer, 0, length); // Set New Vertices
this.vertices.flip(); // Flip Vertex Buffer
this.numVertices = length / this.vertexStride; // Save Number of Vertices
//this.numVertices = length / ( this.vertexSize / 4 ); // Save Number of Vertices
}
//--Bind--//
// D: perform all required binding/state changes before rendering batches.
// USAGE: call once before calling draw() multiple times for this buffer.
// A: [none]
// R: [none]
public void bind() {
gl.glEnableClientState( GL10.GL_VERTEX_ARRAY ); // Enable Position in Vertices
vertices.position( 0 ); // Set Vertex Buffer to Position
gl.glVertexPointer( positionCnt, GL10.GL_FLOAT, vertexSize, vertices ); // Set Vertex Pointer
//--Set Indices--//
// D: set the specified indices in the index buffer
// A: indices - array of indices (shorts) to set
// offset - offset to first index in array
// length - number of indices in array (from offset)
// R: [none]
public void setIndices(short[] indices, int offset, int length) {
this.indices.clear(); // Clear Existing Indices
this.indices.put(indices, offset, length); // Set New Indices
this.indices.flip(); // Flip Index Buffer
this.numIndices = length; // Save Number of Indices
}
if ( hasColor ) { // IF Vertices Have Color
gl.glEnableClientState( GL10.GL_COLOR_ARRAY ); // Enable Color in Vertices
vertices.position( positionCnt ); // Set Vertex Buffer to Color
gl.glColorPointer( COLOR_CNT, GL10.GL_FLOAT, vertexSize, vertices ); // Set Color Pointer
}
//--Bind--//
// D: perform all required binding/state changes before rendering batches.
// USAGE: call once before calling draw() multiple times for this buffer.
// A: [none]
// R: [none]
public void bind() {
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); // Enable Position in Vertices
vertices.position(0); // Set Vertex Buffer to Position
gl.glVertexPointer(positionCnt, GL10.GL_FLOAT, vertexSize, vertices); // Set Vertex Pointer
if ( hasTexCoords ) { // IF Vertices Have Texture Coords
gl.glEnableClientState( GL10.GL_TEXTURE_COORD_ARRAY ); // Enable Texture Coords in Vertices
vertices.position( positionCnt + ( hasColor ? COLOR_CNT : 0 ) ); // Set Vertex Buffer to Texture Coords (NOTE: position based on whether color is also specified)
gl.glTexCoordPointer( TEXCOORD_CNT, GL10.GL_FLOAT, vertexSize, vertices ); // Set Texture Coords Pointer
}
if (hasColor) { // IF Vertices Have Color
gl.glEnableClientState(GL10.GL_COLOR_ARRAY); // Enable Color in Vertices
vertices.position(positionCnt); // Set Vertex Buffer to Color
gl.glColorPointer(COLOR_CNT, GL10.GL_FLOAT, vertexSize, vertices); // Set Color Pointer
}
if ( hasNormals ) {
gl.glEnableClientState( GL10.GL_NORMAL_ARRAY ); // Enable Normals in Vertices
vertices.position( positionCnt + ( hasColor ? COLOR_CNT : 0 ) + ( hasTexCoords ? TEXCOORD_CNT : 0 ) ); // Set Vertex Buffer to Normals (NOTE: position based on whether color/texcoords is also specified)
gl.glNormalPointer( GL10.GL_FLOAT, vertexSize, vertices ); // Set Normals Pointer
}
}
if (hasTexCoords) { // IF Vertices Have Texture Coords
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); // Enable Texture Coords in Vertices
vertices.position(positionCnt + (hasColor ? COLOR_CNT : 0)); // Set Vertex Buffer to Texture Coords (NOTE: position based on whether color is also specified)
gl.glTexCoordPointer(TEXCOORD_CNT, GL10.GL_FLOAT, vertexSize, vertices); // Set Texture Coords Pointer
}
//--Draw--//
// D: draw the currently bound vertices in the vertex/index buffers
// USAGE: can only be called after calling bind() for this buffer.
// A: primitiveType - the type of primitive to draw
// offset - the offset in the vertex/index buffer to start at
// numVertices - the number of vertices (indices) to draw
// R: [none]
public void draw(int primitiveType, int offset, int numVertices) {
if ( indices != null ) { // IF Indices Exist
indices.position( offset ); // Set Index Buffer to Specified Offset
gl.glDrawElements( primitiveType, numVertices, GL10.GL_UNSIGNED_SHORT, indices ); // Draw Indexed
}
else { // ELSE No Indices Exist
gl.glDrawArrays( primitiveType, offset, numVertices ); // Draw Direct (Array)
}
}
if (hasNormals) {
gl.glEnableClientState(GL10.GL_NORMAL_ARRAY); // Enable Normals in Vertices
vertices.position(positionCnt + (hasColor ? COLOR_CNT : 0) + (hasTexCoords ? TEXCOORD_CNT : 0)); // Set Vertex Buffer to Normals (NOTE: position based on whether color/texcoords is also specified)
gl.glNormalPointer(GL10.GL_FLOAT, vertexSize, vertices); // Set Normals Pointer
}
}
//--Unbind--//
// D: clear binding states when done rendering batches.
// USAGE: call once before calling draw() multiple times for this buffer.
// A: [none]
// R: [none]
public void unbind() {
if ( hasColor ) // IF Vertices Have Color
gl.glDisableClientState( GL10.GL_COLOR_ARRAY ); // Clear Color State
//--Draw--//
// D: draw the currently bound vertices in the vertex/index buffers
// USAGE: can only be called after calling bind() for this buffer.
// A: primitiveType - the type of primitive to draw
// offset - the offset in the vertex/index buffer to start at
// numVertices - the number of vertices (indices) to draw
// R: [none]
public void draw(int primitiveType, int offset, int numVertices) {
if (indices != null) { // IF Indices Exist
indices.position(offset); // Set Index Buffer to Specified Offset
gl.glDrawElements(primitiveType, numVertices, GL10.GL_UNSIGNED_SHORT, indices); // Draw Indexed
} else { // ELSE No Indices Exist
gl.glDrawArrays(primitiveType, offset, numVertices); // Draw Direct (Array)
}
}
if ( hasTexCoords ) // IF Vertices Have Texture Coords
gl.glDisableClientState( GL10.GL_TEXTURE_COORD_ARRAY ); // Clear Texture Coords State
//--Unbind--//
// D: clear binding states when done rendering batches.
// USAGE: call once before calling draw() multiple times for this buffer.
// A: [none]
// R: [none]
public void unbind() {
if (hasColor) // IF Vertices Have Color
gl.glDisableClientState(GL10.GL_COLOR_ARRAY); // Clear Color State
if ( hasNormals ) // IF Vertices Have Normals
gl.glDisableClientState( GL10.GL_NORMAL_ARRAY ); // Clear Normals State
}
if (hasTexCoords) // IF Vertices Have Texture Coords
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY); // Clear Texture Coords State
//--Draw Full--//
// D: draw the vertices in the vertex/index buffers
// NOTE: unoptimized version! use bind()/draw()/unbind() for batches
// A: primitiveType - the type of primitive to draw
// offset - the offset in the vertex/index buffer to start at
// numVertices - the number of vertices (indices) to draw
// R: [none]
public void drawFull(int primitiveType, int offset, int numVertices) {
gl.glEnableClientState( GL10.GL_VERTEX_ARRAY ); // Enable Position in Vertices
vertices.position( 0 ); // Set Vertex Buffer to Position
gl.glVertexPointer( positionCnt, GL10.GL_FLOAT, vertexSize, vertices ); // Set Vertex Pointer
if (hasNormals) // IF Vertices Have Normals
gl.glDisableClientState(GL10.GL_NORMAL_ARRAY); // Clear Normals State
}
if ( hasColor ) { // IF Vertices Have Color
gl.glEnableClientState( GL10.GL_COLOR_ARRAY ); // Enable Color in Vertices
vertices.position( positionCnt ); // Set Vertex Buffer to Color
gl.glColorPointer( COLOR_CNT, GL10.GL_FLOAT, vertexSize, vertices ); // Set Color Pointer
}
//--Draw Full--//
// D: draw the vertices in the vertex/index buffers
// NOTE: unoptimized version! use bind()/draw()/unbind() for batches
// A: primitiveType - the type of primitive to draw
// offset - the offset in the vertex/index buffer to start at
// numVertices - the number of vertices (indices) to draw
// R: [none]
public void drawFull(int primitiveType, int offset, int numVertices) {
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); // Enable Position in Vertices
vertices.position(0); // Set Vertex Buffer to Position
gl.glVertexPointer(positionCnt, GL10.GL_FLOAT, vertexSize, vertices); // Set Vertex Pointer
if ( hasTexCoords ) { // IF Vertices Have Texture Coords
gl.glEnableClientState( GL10.GL_TEXTURE_COORD_ARRAY ); // Enable Texture Coords in Vertices
vertices.position( positionCnt + ( hasColor ? COLOR_CNT : 0 ) ); // Set Vertex Buffer to Texture Coords (NOTE: position based on whether color is also specified)
gl.glTexCoordPointer( TEXCOORD_CNT, GL10.GL_FLOAT, vertexSize, vertices ); // Set Texture Coords Pointer
}
if (hasColor) { // IF Vertices Have Color
gl.glEnableClientState(GL10.GL_COLOR_ARRAY); // Enable Color in Vertices
vertices.position(positionCnt); // Set Vertex Buffer to Color
gl.glColorPointer(COLOR_CNT, GL10.GL_FLOAT, vertexSize, vertices); // Set Color Pointer
}
if ( indices != null ) { // IF Indices Exist
indices.position( offset ); // Set Index Buffer to Specified Offset
gl.glDrawElements( primitiveType, numVertices, GL10.GL_UNSIGNED_SHORT, indices ); // Draw Indexed
}
else { // ELSE No Indices Exist
gl.glDrawArrays( primitiveType, offset, numVertices ); // Draw Direct (Array)
}
if (hasTexCoords) { // IF Vertices Have Texture Coords
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); // Enable Texture Coords in Vertices
vertices.position(positionCnt + (hasColor ? COLOR_CNT : 0)); // Set Vertex Buffer to Texture Coords (NOTE: position based on whether color is also specified)
gl.glTexCoordPointer(TEXCOORD_CNT, GL10.GL_FLOAT, vertexSize, vertices); // Set Texture Coords Pointer
}
if ( hasTexCoords ) // IF Vertices Have Texture Coords
gl.glDisableClientState( GL10.GL_TEXTURE_COORD_ARRAY ); // Clear Texture Coords State
if (indices != null) { // IF Indices Exist
indices.position(offset); // Set Index Buffer to Specified Offset
gl.glDrawElements(primitiveType, numVertices, GL10.GL_UNSIGNED_SHORT, indices); // Draw Indexed
} else { // ELSE No Indices Exist
gl.glDrawArrays(primitiveType, offset, numVertices); // Draw Direct (Array)
}
if ( hasColor ) // IF Vertices Have Color
gl.glDisableClientState( GL10.GL_COLOR_ARRAY ); // Clear Color State
}
if (hasTexCoords) // IF Vertices Have Texture Coords
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY); // Clear Texture Coords State
//--Set Vertex Elements--//
// D: use these methods to alter the values (position, color, textcoords, normals) for vertices
// WARNING: these do NOT validate any values, ensure that the index AND specified
// elements EXIST before using!!
// A: x, y, z - the x,y,z position to set in buffer
// r, g, b, a - the r,g,b,a color to set in buffer
// u, v - the u,v texture coords to set in buffer
// nx, ny, nz - the x,y,z normal to set in buffer
// R: [none]
void setVtxPosition(int vtxIdx, float x, float y) {
int index = vtxIdx * vertexStride; // Calculate Actual Index
vertices.put( index + 0, Float.floatToRawIntBits( x ) ); // Set X
vertices.put( index + 1, Float.floatToRawIntBits( y ) ); // Set Y
}
void setVtxPosition(int vtxIdx, float x, float y, float z) {
int index = vtxIdx * vertexStride; // Calculate Actual Index
vertices.put( index + 0, Float.floatToRawIntBits( x ) ); // Set X
vertices.put( index + 1, Float.floatToRawIntBits( y ) ); // Set Y
vertices.put( index + 2, Float.floatToRawIntBits( z ) ); // Set Z
}
void setVtxColor(int vtxIdx, float r, float g, float b, float a) {
int index = ( vtxIdx * vertexStride ) + positionCnt; // Calculate Actual Index
vertices.put( index + 0, Float.floatToRawIntBits( r ) ); // Set Red
vertices.put( index + 1, Float.floatToRawIntBits( g ) ); // Set Green
vertices.put( index + 2, Float.floatToRawIntBits( b ) ); // Set Blue
vertices.put( index + 3, Float.floatToRawIntBits( a ) ); // Set Alpha
}
void setVtxColor(int vtxIdx, float r, float g, float b) {
int index = ( vtxIdx * vertexStride ) + positionCnt; // Calculate Actual Index
vertices.put( index + 0, Float.floatToRawIntBits( r ) ); // Set Red
vertices.put( index + 1, Float.floatToRawIntBits( g ) ); // Set Green
vertices.put( index + 2, Float.floatToRawIntBits( b ) ); // Set Blue
}
void setVtxColor(int vtxIdx, float a) {
int index = ( vtxIdx * vertexStride ) + positionCnt; // Calculate Actual Index
vertices.put( index + 3, Float.floatToRawIntBits( a ) ); // Set Alpha
}
void setVtxTexCoords(int vtxIdx, float u, float v) {
int index = ( vtxIdx * vertexStride ) + positionCnt + ( hasColor ? COLOR_CNT : 0 ); // Calculate Actual Index
vertices.put( index + 0, Float.floatToRawIntBits( u ) ); // Set U
vertices.put( index + 1, Float.floatToRawIntBits( v ) ); // Set V
}
void setVtxNormal(int vtxIdx, float x, float y, float z) {
int index = ( vtxIdx * vertexStride ) + positionCnt + ( hasColor ? COLOR_CNT : 0 ) + ( hasTexCoords ? TEXCOORD_CNT : 0 ); // Calculate Actual Index
vertices.put( index + 0, Float.floatToRawIntBits( x ) ); // Set X
vertices.put( index + 1, Float.floatToRawIntBits( y ) ); // Set Y
vertices.put( index + 2, Float.floatToRawIntBits( z ) ); // Set Z
}
if (hasColor) // IF Vertices Have Color
gl.glDisableClientState(GL10.GL_COLOR_ARRAY); // Clear Color State
}
//--Set Vertex Elements--//
// D: use these methods to alter the values (position, color, textcoords, normals) for vertices
// WARNING: these do NOT validate any values, ensure that the index AND specified
// elements EXIST before using!!
// A: x, y, z - the x,y,z position to set in buffer
// r, g, b, a - the r,g,b,a color to set in buffer
// u, v - the u,v texture coords to set in buffer
// nx, ny, nz - the x,y,z normal to set in buffer
// R: [none]
void setVtxPosition(int vtxIdx, float x, float y) {
int index = vtxIdx * vertexStride; // Calculate Actual Index
vertices.put(index + 0, Float.floatToRawIntBits(x)); // Set X
vertices.put(index + 1, Float.floatToRawIntBits(y)); // Set Y
}
void setVtxPosition(int vtxIdx, float x, float y, float z) {
int index = vtxIdx * vertexStride; // Calculate Actual Index
vertices.put(index + 0, Float.floatToRawIntBits(x)); // Set X
vertices.put(index + 1, Float.floatToRawIntBits(y)); // Set Y
vertices.put(index + 2, Float.floatToRawIntBits(z)); // Set Z
}
void setVtxColor(int vtxIdx, float r, float g, float b, float a) {
int index = (vtxIdx * vertexStride) + positionCnt; // Calculate Actual Index
vertices.put(index + 0, Float.floatToRawIntBits(r)); // Set Red
vertices.put(index + 1, Float.floatToRawIntBits(g)); // Set Green
vertices.put(index + 2, Float.floatToRawIntBits(b)); // Set Blue
vertices.put(index + 3, Float.floatToRawIntBits(a)); // Set Alpha
}
void setVtxColor(int vtxIdx, float r, float g, float b) {
int index = (vtxIdx * vertexStride) + positionCnt; // Calculate Actual Index
vertices.put(index + 0, Float.floatToRawIntBits(r)); // Set Red
vertices.put(index + 1, Float.floatToRawIntBits(g)); // Set Green
vertices.put(index + 2, Float.floatToRawIntBits(b)); // Set Blue
}
void setVtxColor(int vtxIdx, float a) {
int index = (vtxIdx * vertexStride) + positionCnt; // Calculate Actual Index
vertices.put(index + 3, Float.floatToRawIntBits(a)); // Set Alpha
}
void setVtxTexCoords(int vtxIdx, float u, float v) {
int index = (vtxIdx * vertexStride) + positionCnt + (hasColor ? COLOR_CNT : 0); // Calculate Actual Index
vertices.put(index + 0, Float.floatToRawIntBits(u)); // Set U
vertices.put(index + 1, Float.floatToRawIntBits(v)); // Set V
}
void setVtxNormal(int vtxIdx, float x, float y, float z) {
int index = (vtxIdx * vertexStride) + positionCnt + (hasColor ? COLOR_CNT : 0) + (hasTexCoords ? TEXCOORD_CNT : 0); // Calculate Actual Index
vertices.put(index + 0, Float.floatToRawIntBits(x)); // Set X
vertices.put(index + 1, Float.floatToRawIntBits(y)); // Set Y
vertices.put(index + 2, Float.floatToRawIntBits(z)); // Set Z
}
}

View File

@@ -2,57 +2,57 @@ package org.solovyev.android.calculator.plot;
class ZoomTracker {
private static final float EPS = 1.5f;
private static final float MIN_DISTANCE = distance(0f, 50f);
public static final String TAG = "ZoomTracker";
private static final float EPS = 1.5f;
private static final float MIN_DISTANCE = distance(0f, 50f);
public static final String TAG = "ZoomTracker";
private float initialXDistance;
private float initialYDistance;
private float initialXDistance;
private float initialYDistance;
private float initialXValue;
private float initialYValue;
private float initialXValue;
private float initialYValue;
float xValue;
float yValue;
float xValue;
float yValue;
void start(float xValue, float yValue,
float x1, float y1,
float x2, float y2) {
void start(float xValue, float yValue,
float x1, float y1,
float x2, float y2) {
initialXDistance = distance(x1, x2);
initialYDistance = distance(y1, y2);
initialXDistance = distance(x1, x2);
initialYDistance = distance(y1, y2);
initialXValue = xValue;
initialYValue = yValue;
initialXValue = xValue;
initialYValue = yValue;
this.xValue = xValue;
this.yValue = yValue;
}
this.xValue = xValue;
this.yValue = yValue;
}
boolean update(float x1, float y1, float x2, float y2) {
boolean result = false;
boolean update(float x1, float y1, float x2, float y2) {
boolean result = false;
if (initialXDistance > MIN_DISTANCE) {
final float xDistance = distance(x1, x2);
if (xDistance > EPS) {
xValue = initialXDistance / xDistance * initialXValue;
result = true;
}
}
if (initialXDistance > MIN_DISTANCE) {
final float xDistance = distance(x1, x2);
if (xDistance > EPS) {
xValue = initialXDistance / xDistance * initialXValue;
result = true;
}
}
if (initialYDistance > MIN_DISTANCE) {
final float yDistance = distance(y1, y2);
if (yDistance > EPS) {
yValue = initialYDistance / yDistance * initialYValue;
result = true;
}
}
if (initialYDistance > MIN_DISTANCE) {
final float yDistance = distance(y1, y2);
if (yDistance > EPS) {
yValue = initialYDistance / yDistance * initialYValue;
result = true;
}
}
return result;
}
return result;
}
private static float distance(float x1, float x2) {
final float dx = x1 - x2;
return dx * dx;
}
private static float distance(float x1, float x2) {
final float dx = x1 - x2;
return dx * dx;
}
}

View File

@@ -44,14 +44,14 @@ public class CalculatorPreferencesActivity extends SherlockPreferenceActivity im
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//noinspection deprecation
addPreferencesFromResource(R.xml.preferences);
//noinspection deprecation
addPreferencesFromResource(R.xml.preferences_calculations);
addPreferencesFromResource(R.xml.preferences_appearance);
addPreferencesFromResource(R.xml.preferences_plot);
addPreferencesFromResource(R.xml.preferences_other);
addPreferencesFromResource(R.xml.preferences_onscreen);
//noinspection deprecation
addPreferencesFromResource(R.xml.preferences);
//noinspection deprecation
addPreferencesFromResource(R.xml.preferences_calculations);
addPreferencesFromResource(R.xml.preferences_appearance);
addPreferencesFromResource(R.xml.preferences_plot);
addPreferencesFromResource(R.xml.preferences_other);
addPreferencesFromResource(R.xml.preferences_onscreen);
final Preference adFreePreference = findPreference(CalculatorApplication.AD_FREE_P_KEY);
adFreePreference.setEnabled(false);
@@ -98,9 +98,9 @@ public class CalculatorPreferencesActivity extends SherlockPreferenceActivity im
adFreePreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
final Context context = CalculatorPreferencesActivity.this;
context.startActivity(new Intent(context, CalculatorPurchaseDialogActivity.class));
return true;
final Context context = CalculatorPreferencesActivity.this;
context.startActivity(new Intent(context, CalculatorPurchaseDialogActivity.class));
return true;
}
});
adFreePreference.setEnabled(true);
@@ -113,7 +113,7 @@ public class CalculatorPreferencesActivity extends SherlockPreferenceActivity im
@Override
protected void onDestroy() {
BillingController.unregisterObserver(this);
PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(this);
PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(this);
super.onDestroy();
}
@@ -172,15 +172,15 @@ public class CalculatorPreferencesActivity extends SherlockPreferenceActivity im
@Override
public void onRequestPurchaseResponse(@NotNull String itemId, @NotNull ResponseCode response) {
final Preference adFreePreference = findPreference(CalculatorApplication.AD_FREE_P_KEY);
if (adFreePreference != null) {
if (response == ResponseCode.RESULT_OK) {
adFreePreference.setEnabled(false);
final Preference adFreePreference = findPreference(CalculatorApplication.AD_FREE_P_KEY);
if (adFreePreference != null) {
if (response == ResponseCode.RESULT_OK) {
adFreePreference.setEnabled(false);
final Message message = new AndroidMessage(R.string.cpp_purchase_thank_you_text, MessageType.info, App.getApplication());
Locator.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.show_message_dialog, MessageDialogData.newInstance(message, null));
}
}
final Message message = new AndroidMessage(R.string.cpp_purchase_thank_you_text, MessageType.info, App.getApplication());
Locator.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.show_message_dialog, MessageDialogData.newInstance(message, null));
}
}
}
@Override

View File

@@ -26,59 +26,59 @@ import org.solovyev.android.fragments.FragmentUtils;
*/
public class CalculatorPurchaseDialogActivity extends SherlockFragmentActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cpp_dialog);
setContentView(R.layout.cpp_dialog);
FragmentUtils.createFragment(this, PurchaseDialogFragment.class, R.id.dialog_layout, "purchase-dialog");
}
FragmentUtils.createFragment(this, PurchaseDialogFragment.class, R.id.dialog_layout, "purchase-dialog");
}
public static class PurchaseDialogFragment extends CalculatorFragment {
public static class PurchaseDialogFragment extends CalculatorFragment {
public PurchaseDialogFragment() {
super(CalculatorFragmentType.purchase_dialog);
}
public PurchaseDialogFragment() {
super(CalculatorFragmentType.purchase_dialog);
}
@Override
public void onViewCreated(@NotNull View root, Bundle savedInstanceState) {
super.onViewCreated(root, savedInstanceState);
@Override
public void onViewCreated(@NotNull View root, Bundle savedInstanceState) {
super.onViewCreated(root, savedInstanceState);
((TextView) root.findViewById(R.id.cpp_purchase_text)).setMovementMethod(ScrollingMovementMethod.getInstance());
root.findViewById(R.id.cpp_continue_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
((TextView) root.findViewById(R.id.cpp_purchase_text)).setMovementMethod(ScrollingMovementMethod.getInstance());
root.findViewById(R.id.cpp_continue_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Activity activity = getActivity();
final Activity activity = getActivity();
if (activity != null) {
// check billing availability
if (BillingController.checkBillingSupported(activity) != BillingController.BillingStatus.SUPPORTED) {
Log.d(CalculatorPreferencesActivity.class.getName(), "Billing is not supported - warn user!");
// warn about not supported billing
new AlertDialog.Builder(activity).setTitle(R.string.c_error).setMessage(R.string.c_billing_error).create().show();
} else {
Log.d(CalculatorPreferencesActivity.class.getName(), "Billing is supported - continue!");
if (!AdsController.getInstance().isAdFree(activity)) {
Log.d(CalculatorPreferencesActivity.class.getName(), "Item not purchased - try to purchase!");
if (activity != null) {
// check billing availability
if (BillingController.checkBillingSupported(activity) != BillingController.BillingStatus.SUPPORTED) {
Log.d(CalculatorPreferencesActivity.class.getName(), "Billing is not supported - warn user!");
// warn about not supported billing
new AlertDialog.Builder(activity).setTitle(R.string.c_error).setMessage(R.string.c_billing_error).create().show();
} else {
Log.d(CalculatorPreferencesActivity.class.getName(), "Billing is supported - continue!");
if (!AdsController.getInstance().isAdFree(activity)) {
Log.d(CalculatorPreferencesActivity.class.getName(), "Item not purchased - try to purchase!");
// not purchased => purchasing
Toast.makeText(activity, R.string.c_calc_purchasing, Toast.LENGTH_SHORT).show();
// not purchased => purchasing
Toast.makeText(activity, R.string.c_calc_purchasing, Toast.LENGTH_SHORT).show();
// show purchase window for user
BillingController.requestPurchase(activity, CalculatorApplication.AD_FREE_PRODUCT_ID, true);
} else {
// and show message to user
Toast.makeText(activity, R.string.c_calc_already_purchased, Toast.LENGTH_SHORT).show();
}
}
// show purchase window for user
BillingController.requestPurchase(activity, CalculatorApplication.AD_FREE_PRODUCT_ID, true);
} else {
// and show message to user
Toast.makeText(activity, R.string.c_calc_already_purchased, Toast.LENGTH_SHORT).show();
}
}
activity.finish();
}
}
});
}
}
activity.finish();
}
}
});
}
}
}

View File

@@ -41,7 +41,7 @@ public class CalculatorAdditionalTitle extends TextView implements SharedPrefere
@Override
public void onSharedPreferenceChanged(SharedPreferences preferences, @Nullable String key) {
setText(((AndroidCalculatorEngine) Locator.getInstance().getEngine()).getNumeralBaseFromPrefs(preferences)
+ " / " +
((AndroidCalculatorEngine) Locator.getInstance().getEngine()).getAngleUnitsFromPrefs(preferences));
+ " / " +
((AndroidCalculatorEngine) Locator.getInstance().getEngine()).getAngleUnitsFromPrefs(preferences));
}
}

View File

@@ -10,32 +10,32 @@ import org.solovyev.android.view.drag.OnDragListener;
import org.solovyev.android.view.drag.OnDragListenerWrapper;
/**
* User: serso
* Date: 4/20/12
* Time: 3:27 PM
*/
* User: serso
* Date: 4/20/12
* Time: 3:27 PM
*/
public class OnDragListenerVibrator extends OnDragListenerWrapper {
private static final float VIBRATION_TIME_SCALE = 0.5f;
private static final float VIBRATION_TIME_SCALE = 0.5f;
@NotNull
private final VibratorContainer vibrator;
@NotNull
private final VibratorContainer vibrator;
public OnDragListenerVibrator(@NotNull OnDragListener onDragListener,
@Nullable Vibrator vibrator,
@NotNull SharedPreferences preferences) {
super(onDragListener);
this.vibrator = new VibratorContainer(vibrator, preferences, VIBRATION_TIME_SCALE);
}
public OnDragListenerVibrator(@NotNull OnDragListener onDragListener,
@Nullable Vibrator vibrator,
@NotNull SharedPreferences preferences) {
super(onDragListener);
this.vibrator = new VibratorContainer(vibrator, preferences, VIBRATION_TIME_SCALE);
}
@Override
public boolean onDrag(@NotNull DragButton dragButton, @NotNull org.solovyev.android.view.drag.DragEvent event) {
boolean result = super.onDrag(dragButton, event);
@Override
public boolean onDrag(@NotNull DragButton dragButton, @NotNull org.solovyev.android.view.drag.DragEvent event) {
boolean result = super.onDrag(dragButton, event);
if (result) {
vibrator.vibrate();
}
if (result) {
vibrator.vibrate();
}
return result;
}
return result;
}
}

View File

@@ -26,69 +26,69 @@ public class FragmentUtils {
createFragment(activity, fragmentClass, parentViewId, tag, null);
}
public static void createFragment(@NotNull FragmentActivity activity,
@NotNull Class<? extends Fragment> fragmentClass,
int parentViewId,
@NotNull String tag,
@Nullable Bundle args) {
final FragmentManager fm = activity.getSupportFragmentManager();
public static void createFragment(@NotNull FragmentActivity activity,
@NotNull Class<? extends Fragment> fragmentClass,
int parentViewId,
@NotNull String tag,
@Nullable Bundle args) {
final FragmentManager fm = activity.getSupportFragmentManager();
Fragment messagesFragment = fm.findFragmentByTag(tag);
Fragment messagesFragment = fm.findFragmentByTag(tag);
final FragmentTransaction ft = fm.beginTransaction();
try {
if (messagesFragment == null) {
messagesFragment = Fragment.instantiate(activity, fragmentClass.getName(), args);
ft.add(parentViewId, messagesFragment, tag);
} else {
if (messagesFragment.isDetached()) {
ft.attach(messagesFragment);
}
}
} finally {
ft.commit();
}
}
final FragmentTransaction ft = fm.beginTransaction();
try {
if (messagesFragment == null) {
messagesFragment = Fragment.instantiate(activity, fragmentClass.getName(), args);
ft.add(parentViewId, messagesFragment, tag);
} else {
if (messagesFragment.isDetached()) {
ft.attach(messagesFragment);
}
}
} finally {
ft.commit();
}
}
public static void removeFragments(@NotNull SherlockFragmentActivity activity, @NotNull String... fragmentTags) {
removeFragments(activity, Collections.asList(fragmentTags));
}
public static void removeFragments(@NotNull SherlockFragmentActivity activity, @NotNull String... fragmentTags) {
removeFragments(activity, Collections.asList(fragmentTags));
}
public static void removeFragments(@NotNull SherlockFragmentActivity activity, @NotNull List<String> fragmentTags) {
for (String fragmentTag : fragmentTags) {
removeFragment(activity, fragmentTag);
}
}
public static void removeFragments(@NotNull SherlockFragmentActivity activity, @NotNull List<String> fragmentTags) {
for (String fragmentTag : fragmentTags) {
removeFragment(activity, fragmentTag);
}
}
public static void detachFragments(@NotNull SherlockFragmentActivity activity, @NotNull String... fragmentTags) {
detachFragments(activity, Collections.asList(fragmentTags));
}
public static void detachFragments(@NotNull SherlockFragmentActivity activity, @NotNull String... fragmentTags) {
detachFragments(activity, Collections.asList(fragmentTags));
}
public static void detachFragments(@NotNull SherlockFragmentActivity activity, @NotNull List<String> fragmentTags) {
for (String fragmentTag : fragmentTags) {
detachFragment(activity, fragmentTag);
}
}
public static void detachFragments(@NotNull SherlockFragmentActivity activity, @NotNull List<String> fragmentTags) {
for (String fragmentTag : fragmentTags) {
detachFragment(activity, fragmentTag);
}
}
public static void detachFragment(@NotNull SherlockFragmentActivity activity, @NotNull String fragmentTag) {
final Fragment fragment = activity.getSupportFragmentManager().findFragmentByTag(fragmentTag);
if ( fragment != null ) {
if ( !fragment.isDetached() ) {
FragmentTransaction ft = activity.getSupportFragmentManager().beginTransaction();
ft.detach(fragment);
ft.commit();
}
}
}
public static void detachFragment(@NotNull SherlockFragmentActivity activity, @NotNull String fragmentTag) {
final Fragment fragment = activity.getSupportFragmentManager().findFragmentByTag(fragmentTag);
if (fragment != null) {
if (!fragment.isDetached()) {
FragmentTransaction ft = activity.getSupportFragmentManager().beginTransaction();
ft.detach(fragment);
ft.commit();
}
}
}
public static void removeFragment(@NotNull SherlockFragmentActivity activity, @NotNull String fragmentTag) {
final Fragment fragment = activity.getSupportFragmentManager().findFragmentByTag(fragmentTag);
if ( fragment != null ) {
if ( fragment.isAdded()) {
FragmentTransaction ft = activity.getSupportFragmentManager().beginTransaction();
ft.remove(fragment);
ft.commit();
}
}
}
public static void removeFragment(@NotNull SherlockFragmentActivity activity, @NotNull String fragmentTag) {
final Fragment fragment = activity.getSupportFragmentManager().findFragmentByTag(fragmentTag);
if (fragment != null) {
if (fragment.isAdded()) {
FragmentTransaction ft = activity.getSupportFragmentManager().beginTransaction();
ft.remove(fragment);
ft.commit();
}
}
}
}