diff --git a/android-app-tests/src/test/java/org/solovyev/android/AndroidNumeralBaseTest.java b/android-app-tests/src/test/java/org/solovyev/android/AndroidNumeralBaseTest.java index 4e8196d0..a8428705 100644 --- a/android-app-tests/src/test/java/org/solovyev/android/AndroidNumeralBaseTest.java +++ b/android-app-tests/src/test/java/org/solovyev/android/AndroidNumeralBaseTest.java @@ -28,11 +28,11 @@ import org.solovyev.android.calculator.units.CalculatorNumeralBase; import org.solovyev.common.units.Unit; import org.solovyev.common.units.UnitConverter; -import javax.annotation.Nonnull; - import java.util.Date; import java.util.Random; +import javax.annotation.Nonnull; + import static org.junit.Assert.assertTrue; /** @@ -42,56 +42,56 @@ import static org.junit.Assert.assertTrue; */ public class AndroidNumeralBaseTest { - @Nonnull - private final UnitConverter c = CalculatorNumeralBase.getConverter(); + @Nonnull + private final UnitConverter c = CalculatorNumeralBase.getConverter(); - @Test - public void testIsSupported() throws Exception { - assertTrue(c.isSupported(CalculatorNumeralBase.bin, CalculatorNumeralBase.dec)); - } + @Test + public void testIsSupported() throws Exception { + assertTrue(c.isSupported(CalculatorNumeralBase.bin, CalculatorNumeralBase.dec)); + } - @Test - public void testConvertFromDec() throws Exception { + @Test + public void testConvertFromDec() throws Exception { - Assert.assertEquals("101", c.convert(CalculatorNumeralBase.dec.createUnit("5"), CalculatorNumeralBase.bin).getValue()); - Assert.assertEquals("1", c.convert(CalculatorNumeralBase.dec.createUnit("1"), CalculatorNumeralBase.bin).getValue()); - Assert.assertEquals("0", c.convert(CalculatorNumeralBase.dec.createUnit("0"), CalculatorNumeralBase.bin).getValue()); - Assert.assertEquals("1111100111", c.convert(CalculatorNumeralBase.dec.createUnit("999"), CalculatorNumeralBase.bin).getValue()); + Assert.assertEquals("101", c.convert(CalculatorNumeralBase.dec.createUnit("5"), CalculatorNumeralBase.bin).getValue()); + Assert.assertEquals("1", c.convert(CalculatorNumeralBase.dec.createUnit("1"), CalculatorNumeralBase.bin).getValue()); + Assert.assertEquals("0", c.convert(CalculatorNumeralBase.dec.createUnit("0"), CalculatorNumeralBase.bin).getValue()); + Assert.assertEquals("1111100111", c.convert(CalculatorNumeralBase.dec.createUnit("999"), CalculatorNumeralBase.bin).getValue()); - Assert.assertEquals("A23", c.convert(CalculatorNumeralBase.dec.createUnit("2595"), CalculatorNumeralBase.hex).getValue()); - Assert.assertEquals("AEE", c.convert(CalculatorNumeralBase.dec.createUnit("2798"), CalculatorNumeralBase.hex).getValue()); - Assert.assertEquals("15", c.convert(CalculatorNumeralBase.dec.createUnit("21"), CalculatorNumeralBase.hex).getValue()); - Assert.assertEquals("0", c.convert(CalculatorNumeralBase.dec.createUnit("0"), CalculatorNumeralBase.hex).getValue()); - Assert.assertEquals("3E7", c.convert(CalculatorNumeralBase.dec.createUnit("999"), CalculatorNumeralBase.hex).getValue()); + Assert.assertEquals("A23", c.convert(CalculatorNumeralBase.dec.createUnit("2595"), CalculatorNumeralBase.hex).getValue()); + Assert.assertEquals("AEE", c.convert(CalculatorNumeralBase.dec.createUnit("2798"), CalculatorNumeralBase.hex).getValue()); + Assert.assertEquals("15", c.convert(CalculatorNumeralBase.dec.createUnit("21"), CalculatorNumeralBase.hex).getValue()); + Assert.assertEquals("0", c.convert(CalculatorNumeralBase.dec.createUnit("0"), CalculatorNumeralBase.hex).getValue()); + Assert.assertEquals("3E7", c.convert(CalculatorNumeralBase.dec.createUnit("999"), CalculatorNumeralBase.hex).getValue()); - Assert.assertEquals("76", c.convert(CalculatorNumeralBase.dec.createUnit("62"), CalculatorNumeralBase.oct).getValue()); - Assert.assertEquals("12", c.convert(CalculatorNumeralBase.dec.createUnit("10"), CalculatorNumeralBase.oct).getValue()); - Assert.assertEquals("15", c.convert(CalculatorNumeralBase.dec.createUnit("13"), CalculatorNumeralBase.oct).getValue()); - Assert.assertEquals("0", c.convert(CalculatorNumeralBase.dec.createUnit("0"), CalculatorNumeralBase.oct).getValue()); - Assert.assertEquals("10445", c.convert(CalculatorNumeralBase.dec.createUnit("4389"), CalculatorNumeralBase.oct).getValue()); - } + Assert.assertEquals("76", c.convert(CalculatorNumeralBase.dec.createUnit("62"), CalculatorNumeralBase.oct).getValue()); + Assert.assertEquals("12", c.convert(CalculatorNumeralBase.dec.createUnit("10"), CalculatorNumeralBase.oct).getValue()); + Assert.assertEquals("15", c.convert(CalculatorNumeralBase.dec.createUnit("13"), CalculatorNumeralBase.oct).getValue()); + Assert.assertEquals("0", c.convert(CalculatorNumeralBase.dec.createUnit("0"), CalculatorNumeralBase.oct).getValue()); + Assert.assertEquals("10445", c.convert(CalculatorNumeralBase.dec.createUnit("4389"), CalculatorNumeralBase.oct).getValue()); + } - @Test - public void testRandomConvert() throws Exception { - final Random random = new Random(new Date().getTime()); - for (int i = 0; i < 100000; i++) { - final String value = String.valueOf(random.nextInt()); - Assert.assertEquals(value, convertChain(value, CalculatorNumeralBase.dec, CalculatorNumeralBase.oct, CalculatorNumeralBase.oct, CalculatorNumeralBase.bin, CalculatorNumeralBase.dec)); - Assert.assertEquals(value, convertChain(value, CalculatorNumeralBase.dec, CalculatorNumeralBase.bin, CalculatorNumeralBase.hex, CalculatorNumeralBase.dec, CalculatorNumeralBase.dec)); - Assert.assertEquals(value, convertChain(value, CalculatorNumeralBase.dec, CalculatorNumeralBase.dec, CalculatorNumeralBase.hex, CalculatorNumeralBase.oct, CalculatorNumeralBase.dec)); - Assert.assertEquals(value, convertChain(value, CalculatorNumeralBase.dec, CalculatorNumeralBase.hex, CalculatorNumeralBase.bin, CalculatorNumeralBase.oct, CalculatorNumeralBase.dec)); + @Test + public void testRandomConvert() throws Exception { + final Random random = new Random(new Date().getTime()); + for (int i = 0; i < 100000; i++) { + final String value = String.valueOf(random.nextInt()); + Assert.assertEquals(value, convertChain(value, CalculatorNumeralBase.dec, CalculatorNumeralBase.oct, CalculatorNumeralBase.oct, CalculatorNumeralBase.bin, CalculatorNumeralBase.dec)); + Assert.assertEquals(value, convertChain(value, CalculatorNumeralBase.dec, CalculatorNumeralBase.bin, CalculatorNumeralBase.hex, CalculatorNumeralBase.dec, CalculatorNumeralBase.dec)); + Assert.assertEquals(value, convertChain(value, CalculatorNumeralBase.dec, CalculatorNumeralBase.dec, CalculatorNumeralBase.hex, CalculatorNumeralBase.oct, CalculatorNumeralBase.dec)); + Assert.assertEquals(value, convertChain(value, CalculatorNumeralBase.dec, CalculatorNumeralBase.hex, CalculatorNumeralBase.bin, CalculatorNumeralBase.oct, CalculatorNumeralBase.dec)); - } - } + } + } - @Nonnull - private String convertChain(@Nonnull String value, @Nonnull CalculatorNumeralBase baseAndroid, @Nonnull CalculatorNumeralBase... typeAndroids) { - Unit unit = baseAndroid.createUnit(value); + @Nonnull + private String convertChain(@Nonnull String value, @Nonnull CalculatorNumeralBase baseAndroid, @Nonnull CalculatorNumeralBase... typeAndroids) { + Unit unit = baseAndroid.createUnit(value); - for (CalculatorNumeralBase typeAndroid : typeAndroids) { - unit = CalculatorNumeralBase.getConverter().convert(unit, typeAndroid); - } + for (CalculatorNumeralBase typeAndroid : typeAndroids) { + unit = CalculatorNumeralBase.getConverter().convert(unit, typeAndroid); + } - return unit.getValue(); - } + return unit.getValue(); + } } diff --git a/android-app-tests/src/test/java/org/solovyev/android/CalculatorTestRunner.java b/android-app-tests/src/test/java/org/solovyev/android/CalculatorTestRunner.java index 95380c04..f948940f 100644 --- a/android-app-tests/src/test/java/org/solovyev/android/CalculatorTestRunner.java +++ b/android-app-tests/src/test/java/org/solovyev/android/CalculatorTestRunner.java @@ -7,21 +7,21 @@ import org.robolectric.annotation.Config; import org.robolectric.res.Fs; public class CalculatorTestRunner extends RobolectricTestRunner { - private static final int MAX_SDK_SUPPORTED_BY_ROBOLECTRIC = 18; + private static final int MAX_SDK_SUPPORTED_BY_ROBOLECTRIC = 18; - public CalculatorTestRunner(Class testClass) throws InitializationError { - super(testClass); - } + public CalculatorTestRunner(Class testClass) throws InitializationError { + super(testClass); + } - @Override - protected AndroidManifest getAppManifest(Config config) { - final String manifestFilePath = "android-app/src/main/AndroidManifest.xml"; - final String resourcesFilePath = "android-app/src/main/res"; - return new AndroidManifest(Fs.fileFromPath(manifestFilePath), Fs.fileFromPath(resourcesFilePath)) { - @Override - public int getTargetSdkVersion() { - return MAX_SDK_SUPPORTED_BY_ROBOLECTRIC; - } - }; - } + @Override + protected AndroidManifest getAppManifest(Config config) { + final String manifestFilePath = "android-app/src/main/AndroidManifest.xml"; + final String resourcesFilePath = "android-app/src/main/res"; + return new AndroidManifest(Fs.fileFromPath(manifestFilePath), Fs.fileFromPath(resourcesFilePath)) { + @Override + public int getTargetSdkVersion() { + return MAX_SDK_SUPPORTED_BY_ROBOLECTRIC; + } + }; + } } diff --git a/android-app-tests/src/test/java/org/solovyev/android/calculator/AndroidCalculatorEditorViewTest.java b/android-app-tests/src/test/java/org/solovyev/android/calculator/AndroidCalculatorEditorViewTest.java index b81aa5c9..cdf270b7 100644 --- a/android-app-tests/src/test/java/org/solovyev/android/calculator/AndroidCalculatorEditorViewTest.java +++ b/android-app-tests/src/test/java/org/solovyev/android/calculator/AndroidCalculatorEditorViewTest.java @@ -44,68 +44,68 @@ import java.util.concurrent.atomic.AtomicBoolean; @RunWith(value = CalculatorTestRunner.class) public class AndroidCalculatorEditorViewTest { - @BeforeClass - public static void staticSetUp() throws Exception { - /*CalculatorTestUtils.staticSetUp(null);*/ - } + @BeforeClass + public static void staticSetUp() throws Exception { + /*CalculatorTestUtils.staticSetUp(null);*/ + } - @Before - public void setUp() throws Exception { + @Before + public void setUp() throws Exception { /* CalculatorActivity context = new CalculatorActivity(); CalculatorTestUtils.initViews(context);*/ - } + } - @Test - public void testCreation() throws Exception { - new AndroidCalculatorEditorView(CalculatorApplication.getInstance()); - } + @Test + public void testCreation() throws Exception { + new AndroidCalculatorEditorView(CalculatorApplication.getInstance()); + } - @Test - public void testAsyncWork() throws Exception { - final int threadNum = 10; - final int count = 10; - final int maxTextLength = 100; + @Test + public void testAsyncWork() throws Exception { + final int threadNum = 10; + final int count = 10; + final int maxTextLength = 100; - final Random random = new Random(new Date().getTime()); - final CountDownLatch startLatchLatch = new CountDownLatch(threadNum); - final CountDownLatch finishLatch = new CountDownLatch(threadNum * count); - final AtomicBoolean error = new AtomicBoolean(false); + final Random random = new Random(new Date().getTime()); + final CountDownLatch startLatchLatch = new CountDownLatch(threadNum); + final CountDownLatch finishLatch = new CountDownLatch(threadNum * count); + final AtomicBoolean error = new AtomicBoolean(false); - for (int i = 0; i < threadNum; i++) { - new Thread(new Runnable() { - @Override - public void run() { - try { - startLatchLatch.await(); - } catch (InterruptedException e) { - System.out.println(e); - error.set(true); - for (int j = 0; j < count; j++) { - finishLatch.countDown(); - } - return; - } + for (int i = 0; i < threadNum; i++) { + new Thread(new Runnable() { + @Override + public void run() { + try { + startLatchLatch.await(); + } catch (InterruptedException e) { + System.out.println(e); + error.set(true); + for (int j = 0; j < count; j++) { + finishLatch.countDown(); + } + return; + } - for (int j = 0; j < count; j++) { - try { - int textLength = random.nextInt(maxTextLength); - Locator.getInstance().getEditor().insert(Strings.generateRandomString(textLength), textLength); - } catch (Throwable e) { - System.out.println(e); - error.set(true); - } finally { - finishLatch.countDown(); - } - } - } - }).start(); - startLatchLatch.countDown(); - } + for (int j = 0; j < count; j++) { + try { + int textLength = random.nextInt(maxTextLength); + Locator.getInstance().getEditor().insert(Strings.generateRandomString(textLength), textLength); + } catch (Throwable e) { + System.out.println(e); + error.set(true); + } finally { + finishLatch.countDown(); + } + } + } + }).start(); + startLatchLatch.countDown(); + } - if (finishLatch.await(60, TimeUnit.SECONDS)) { - Assert.assertFalse(error.get()); - } else { - Assert.fail("Too long execution!"); - } - } + if (finishLatch.await(60, TimeUnit.SECONDS)) { + Assert.assertFalse(error.get()); + } else { + Assert.fail("Too long execution!"); + } + } } diff --git a/android-app-tests/src/test/java/org/solovyev/android/calculator/CalculatorBroadcasterTest.java b/android-app-tests/src/test/java/org/solovyev/android/calculator/CalculatorBroadcasterTest.java index 601689d3..0d1db113 100644 --- a/android-app-tests/src/test/java/org/solovyev/android/calculator/CalculatorBroadcasterTest.java +++ b/android-app-tests/src/test/java/org/solovyev/android/calculator/CalculatorBroadcasterTest.java @@ -4,6 +4,7 @@ import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; + import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.junit.Before; @@ -21,48 +22,50 @@ import static org.mockito.Mockito.verify; import static org.robolectric.Robolectric.application; import static org.solovyev.android.calculator.CalculatorBroadcaster.ACTION_DISPLAY_STATE_CHANGED; import static org.solovyev.android.calculator.CalculatorBroadcaster.ACTION_EDITOR_STATE_CHANGED; -import static org.solovyev.android.calculator.CalculatorEventType.*; +import static org.solovyev.android.calculator.CalculatorEventType.display_state_changed; +import static org.solovyev.android.calculator.CalculatorEventType.editor_state_changed; +import static org.solovyev.android.calculator.CalculatorEventType.editor_state_changed_light; @Config(manifest = Config.NONE) @RunWith(RobolectricTestRunner.class) public class CalculatorBroadcasterTest { - @Nonnull - private CalculatorBroadcaster broadcaster; + @Nonnull + private CalculatorBroadcaster broadcaster; - @Before - public void setUp() throws Exception { - broadcaster = new CalculatorBroadcaster(application, preferences); - } + @Before + public void setUp() throws Exception { + broadcaster = new CalculatorBroadcaster(application, preferences); + } - @Test - public void testShouldSendEditorStateChangedIntent() throws Exception { - assertIntentSent(editor_state_changed, ACTION_EDITOR_STATE_CHANGED); - } + @Test + public void testShouldSendEditorStateChangedIntent() throws Exception { + assertIntentSent(editor_state_changed, ACTION_EDITOR_STATE_CHANGED); + } - @Test - public void testShouldSendEditorStateChangedLiteIntent() throws Exception { - assertIntentSent(editor_state_changed_light, ACTION_EDITOR_STATE_CHANGED); - } + @Test + public void testShouldSendEditorStateChangedLiteIntent() throws Exception { + assertIntentSent(editor_state_changed_light, ACTION_EDITOR_STATE_CHANGED); + } - @Test - public void testShouldSendDisplayStateChangedIntent() throws Exception { - assertIntentSent(display_state_changed, ACTION_DISPLAY_STATE_CHANGED); - } + @Test + public void testShouldSendDisplayStateChangedIntent() throws Exception { + assertIntentSent(display_state_changed, ACTION_DISPLAY_STATE_CHANGED); + } - private void assertIntentSent(@Nonnull CalculatorEventType eventType, final String expectedAction) { - final BroadcastReceiver receiver = Mockito.mock(BroadcastReceiver.class); - application.registerReceiver(receiver, new IntentFilter(expectedAction)); - broadcaster.onCalculatorEvent(CalculatorEventDataImpl.newInstance(1L, 1L), eventType, null); - verify(receiver, times(1)).onReceive(Mockito.any(), argThat(new BaseMatcher() { - @Override - public boolean matches(Object o) { - return ((Intent) o).getAction().equals(expectedAction); - } + private void assertIntentSent(@Nonnull CalculatorEventType eventType, final String expectedAction) { + final BroadcastReceiver receiver = Mockito.mock(BroadcastReceiver.class); + application.registerReceiver(receiver, new IntentFilter(expectedAction)); + broadcaster.onCalculatorEvent(CalculatorEventDataImpl.newInstance(1L, 1L), eventType, null); + verify(receiver, times(1)).onReceive(Mockito.any(), argThat(new BaseMatcher() { + @Override + public boolean matches(Object o) { + return ((Intent) o).getAction().equals(expectedAction); + } - @Override - public void describeTo(Description description) { - } - })); - } + @Override + public void describeTo(Description description) { + } + })); + } } diff --git a/android-app-tests/src/test/java/org/solovyev/android/calculator/CalculatorReceiverTest.java b/android-app-tests/src/test/java/org/solovyev/android/calculator/CalculatorReceiverTest.java index 8a6a1d2b..2fe6de4d 100644 --- a/android-app-tests/src/test/java/org/solovyev/android/calculator/CalculatorReceiverTest.java +++ b/android-app-tests/src/test/java/org/solovyev/android/calculator/CalculatorReceiverTest.java @@ -1,41 +1,46 @@ package org.solovyev.android.calculator; import android.content.Intent; + import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; import static org.robolectric.Robolectric.application; import static org.solovyev.android.calculator.CalculatorButton.four; -import static org.solovyev.android.calculator.CalculatorReceiver.*; +import static org.solovyev.android.calculator.CalculatorReceiver.ACTION_BUTTON_ID_EXTRA; +import static org.solovyev.android.calculator.CalculatorReceiver.ACTION_BUTTON_PRESSED; +import static org.solovyev.android.calculator.CalculatorReceiver.newButtonClickedIntent; @Config(manifest = Config.NONE) @RunWith(RobolectricTestRunner.class) public class CalculatorReceiverTest { - @Test - public void testShouldPressButtonOnIntent() throws Exception { - Locator.setKeyboard(mock(CalculatorKeyboard.class)); + @Test + public void testShouldPressButtonOnIntent() throws Exception { + Locator.setKeyboard(mock(CalculatorKeyboard.class)); - final Intent intent = newButtonClickedIntent(application, four); - new CalculatorReceiver().onReceive(application, intent); + final Intent intent = newButtonClickedIntent(application, four); + new CalculatorReceiver().onReceive(application, intent); - verify(Locator.getInstance().getKeyboard(), times(1)).buttonPressed(Mockito.anyString()); - verify(Locator.getInstance().getKeyboard(), times(1)).buttonPressed("4"); - } + verify(Locator.getInstance().getKeyboard(), times(1)).buttonPressed(Mockito.anyString()); + verify(Locator.getInstance().getKeyboard(), times(1)).buttonPressed("4"); + } - @Test - public void testShouldDoNothingIfButtonInvalid() throws Exception { - Locator.setKeyboard(mock(CalculatorKeyboard.class)); + @Test + public void testShouldDoNothingIfButtonInvalid() throws Exception { + Locator.setKeyboard(mock(CalculatorKeyboard.class)); - final Intent intent = new Intent(application, CalculatorReceiver.class); - intent.setAction(ACTION_BUTTON_PRESSED); - intent.putExtra(ACTION_BUTTON_ID_EXTRA, "test!@"); - new CalculatorReceiver().onReceive(application, intent); + final Intent intent = new Intent(application, CalculatorReceiver.class); + intent.setAction(ACTION_BUTTON_PRESSED); + intent.putExtra(ACTION_BUTTON_ID_EXTRA, "test!@"); + new CalculatorReceiver().onReceive(application, intent); - verify(Locator.getInstance().getKeyboard(), times(0)).buttonPressed(Mockito.anyString()); - } + verify(Locator.getInstance().getKeyboard(), times(0)).buttonPressed(Mockito.anyString()); + } } diff --git a/android-app-tests/src/test/java/org/solovyev/android/calculator/CalculatorTestUtils.java b/android-app-tests/src/test/java/org/solovyev/android/calculator/CalculatorTestUtils.java index cb4859c2..a1986dbf 100644 --- a/android-app-tests/src/test/java/org/solovyev/android/calculator/CalculatorTestUtils.java +++ b/android-app-tests/src/test/java/org/solovyev/android/calculator/CalculatorTestUtils.java @@ -23,7 +23,6 @@ package org.solovyev.android.calculator; import android.content.Context; -import jscl.JsclMathEngine; import org.mockito.Mockito; import org.solovyev.android.calculator.history.CalculatorHistory; @@ -32,6 +31,8 @@ import org.solovyev.android.calculator.plot.CalculatorPlotter; import javax.annotation.Nonnull; import javax.annotation.Nullable; +import jscl.JsclMathEngine; + /** * User: serso * Date: 10/7/12 @@ -39,41 +40,41 @@ import javax.annotation.Nullable; */ public class CalculatorTestUtils { - public static void staticSetUp(@Nullable Context context) throws Exception { - Locator.getInstance().init(new CalculatorImpl(), newCalculatorEngine(), Mockito.mock(CalculatorClipboard.class), Mockito.mock(CalculatorNotifier.class), Mockito.mock(CalculatorHistory.class), new SystemOutCalculatorLogger(), Mockito.mock(CalculatorPreferenceService.class), Mockito.mock(CalculatorKeyboard.class), Mockito.mock(CalculatorPlotter.class), null); - Locator.getInstance().getEngine().init(); + public static void staticSetUp(@Nullable Context context) throws Exception { + Locator.getInstance().init(new CalculatorImpl(), newCalculatorEngine(), Mockito.mock(CalculatorClipboard.class), Mockito.mock(CalculatorNotifier.class), Mockito.mock(CalculatorHistory.class), new SystemOutCalculatorLogger(), Mockito.mock(CalculatorPreferenceService.class), Mockito.mock(CalculatorKeyboard.class), Mockito.mock(CalculatorPlotter.class), null); + Locator.getInstance().getEngine().init(); - if (context != null) { - initViews(context); - } - } + if (context != null) { + initViews(context); + } + } - public static void initViews(@Nonnull Context context) { - final AndroidCalculatorEditorView editor = new AndroidCalculatorEditorView(context); - editor.init(); - Locator.getInstance().getEditor().setView(editor); + public static void initViews(@Nonnull Context context) { + final AndroidCalculatorEditorView editor = new AndroidCalculatorEditorView(context); + editor.init(); + Locator.getInstance().getEditor().setView(editor); - final AndroidCalculatorDisplayView display = new AndroidCalculatorDisplayView(context); - display.init(context); - Locator.getInstance().getDisplay().setView(display); - } + final AndroidCalculatorDisplayView display = new AndroidCalculatorDisplayView(context); + display.init(context); + Locator.getInstance().getDisplay().setView(display); + } - public static void staticSetUp() throws Exception { - staticSetUp(null); - } + public static void staticSetUp() throws Exception { + staticSetUp(null); + } - @Nonnull - static CalculatorEngineImpl newCalculatorEngine() { - final MathEntityDao mathEntityDao = Mockito.mock(MathEntityDao.class); + @Nonnull + static CalculatorEngineImpl newCalculatorEngine() { + final MathEntityDao mathEntityDao = Mockito.mock(MathEntityDao.class); - final JsclMathEngine jsclEngine = JsclMathEngine.getInstance(); + final JsclMathEngine jsclEngine = JsclMathEngine.getInstance(); - final CalculatorVarsRegistry varsRegistry = new CalculatorVarsRegistry(jsclEngine.getConstantsRegistry(), mathEntityDao); - final CalculatorFunctionsMathRegistry functionsRegistry = new CalculatorFunctionsMathRegistry(jsclEngine.getFunctionsRegistry(), mathEntityDao); - final CalculatorOperatorsMathRegistry operatorsRegistry = new CalculatorOperatorsMathRegistry(jsclEngine.getOperatorsRegistry(), mathEntityDao); - final CalculatorPostfixFunctionsRegistry postfixFunctionsRegistry = new CalculatorPostfixFunctionsRegistry(jsclEngine.getPostfixFunctionsRegistry(), mathEntityDao); + final CalculatorVarsRegistry varsRegistry = new CalculatorVarsRegistry(jsclEngine.getConstantsRegistry(), mathEntityDao); + final CalculatorFunctionsMathRegistry functionsRegistry = new CalculatorFunctionsMathRegistry(jsclEngine.getFunctionsRegistry(), mathEntityDao); + final CalculatorOperatorsMathRegistry operatorsRegistry = new CalculatorOperatorsMathRegistry(jsclEngine.getOperatorsRegistry(), mathEntityDao); + final CalculatorPostfixFunctionsRegistry postfixFunctionsRegistry = new CalculatorPostfixFunctionsRegistry(jsclEngine.getPostfixFunctionsRegistry(), mathEntityDao); - return new CalculatorEngineImpl(jsclEngine, varsRegistry, functionsRegistry, operatorsRegistry, postfixFunctionsRegistry, null); - } + return new CalculatorEngineImpl(jsclEngine, varsRegistry, functionsRegistry, operatorsRegistry, postfixFunctionsRegistry, null); + } } diff --git a/android-app-tests/src/test/java/org/solovyev/android/calculator/TextHighlighterTest.java b/android-app-tests/src/test/java/org/solovyev/android/calculator/TextHighlighterTest.java index 98daee5f..5e794935 100644 --- a/android-app-tests/src/test/java/org/solovyev/android/calculator/TextHighlighterTest.java +++ b/android-app-tests/src/test/java/org/solovyev/android/calculator/TextHighlighterTest.java @@ -23,8 +23,6 @@ package org.solovyev.android.calculator; import android.graphics.Color; -import jscl.MathEngine; -import jscl.NumeralBase; import org.junit.Before; import org.junit.Test; @@ -34,6 +32,9 @@ import org.solovyev.android.calculator.view.TextHighlighter; import java.util.Date; import java.util.Random; +import jscl.MathEngine; +import jscl.NumeralBase; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -45,152 +46,152 @@ import static org.junit.Assert.assertTrue; */ public class TextHighlighterTest { - @Before - public void setUp() throws Exception { - CalculatorTestUtils.staticSetUp(); - } + @Before + public void setUp() throws Exception { + CalculatorTestUtils.staticSetUp(); + } - @Test - public void testProcess() throws Exception { - TextProcessor textHighlighter = new TextHighlighter(Color.TRANSPARENT, false); + @Test + public void testProcess() throws Exception { + TextProcessor textHighlighter = new TextHighlighter(Color.TRANSPARENT, false); - final Random random = new Random(new Date().getTime()); - for (int i = 0; i < 1000; i++) { - final StringBuilder sb = new StringBuilder(); - for (int j = 0; j < 1000; j++) { - sb.append(random.nextBoolean() ? "(" : ")"); - } - try { - textHighlighter.process(sb.toString()); - } catch (Exception e) { - System.out.println(sb.toString()); - throw e; - } - } + final Random random = new Random(new Date().getTime()); + for (int i = 0; i < 1000; i++) { + final StringBuilder sb = new StringBuilder(); + for (int j = 0; j < 1000; j++) { + sb.append(random.nextBoolean() ? "(" : ")"); + } + try { + textHighlighter.process(sb.toString()); + } catch (Exception e) { + System.out.println(sb.toString()); + throw e; + } + } - assertEquals(")(((())())", textHighlighter.process(")(((())())").toString()); - assertEquals(")", textHighlighter.process(")").toString()); - assertEquals(")()(", textHighlighter.process(")()(").toString()); + assertEquals(")(((())())", textHighlighter.process(")(((())())").toString()); + assertEquals(")", textHighlighter.process(")").toString()); + assertEquals(")()(", textHighlighter.process(")()(").toString()); - textHighlighter = new TextHighlighter(0, true); - assertEquals("1 000 000", textHighlighter.process("1000000").toString()); - assertEquals("1 000 000", textHighlighter.process("1000000").toString()); - assertEquals("0.1E3", textHighlighter.process("0.1E3").toString()); - assertEquals("1E3", textHighlighter.process("1E3").toString()); - assertEquals("20x:", textHighlighter.process("20x:").toString()); - assertEquals("20g", textHighlighter.process("20g").toString()); - assertEquals("22g", textHighlighter.process("22g").toString()); - assertEquals("20ю", textHighlighter.process("20ю").toString()); - assertEquals("20ъ", textHighlighter.process("20ъ").toString()); - assertEquals("3!!", textHighlighter.process("3!!").toString()); - assertEquals("2", textHighlighter.process("2").toString()); - assertEquals("21", textHighlighter.process("21").toString()); - assertEquals("214", textHighlighter.process("214").toString()); - assertEquals("2 145", textHighlighter.process("2 145").toString()); - assertEquals("1 000 000E3", textHighlighter.process("1000000E3").toString()); - assertEquals("-1 000 000E3", textHighlighter.process("-1000000E3").toString()); - assertEquals("-1 000 000E-3", textHighlighter.process("-1000000E-3").toString()); - assertEquals("-1 000 000E-30000", textHighlighter.process("-1000000E-30000").toString()); - textHighlighter = new TextHighlighter(0, false); + textHighlighter = new TextHighlighter(0, true); + assertEquals("1 000 000", textHighlighter.process("1000000").toString()); + assertEquals("1 000 000", textHighlighter.process("1000000").toString()); + assertEquals("0.1E3", textHighlighter.process("0.1E3").toString()); + assertEquals("1E3", textHighlighter.process("1E3").toString()); + assertEquals("20x:", textHighlighter.process("20x:").toString()); + assertEquals("20g", textHighlighter.process("20g").toString()); + assertEquals("22g", textHighlighter.process("22g").toString()); + assertEquals("20ю", textHighlighter.process("20ю").toString()); + assertEquals("20ъ", textHighlighter.process("20ъ").toString()); + assertEquals("3!!", textHighlighter.process("3!!").toString()); + assertEquals("2", textHighlighter.process("2").toString()); + assertEquals("21", textHighlighter.process("21").toString()); + assertEquals("214", textHighlighter.process("214").toString()); + assertEquals("2 145", textHighlighter.process("2 145").toString()); + assertEquals("1 000 000E3", textHighlighter.process("1000000E3").toString()); + assertEquals("-1 000 000E3", textHighlighter.process("-1000000E3").toString()); + assertEquals("-1 000 000E-3", textHighlighter.process("-1000000E-3").toString()); + assertEquals("-1 000 000E-30000", textHighlighter.process("-1000000E-30000").toString()); + textHighlighter = new TextHighlighter(0, false); - textHighlighter.process("cannot calculate 3^10^10 !!!\n" + - " unable to enter 0. FIXED\n" + - " empty display in Xperia Rayo\n" + - " check привиденная FIXED\n" + - " set display result only if text in editor was not changed FIXED\n" + - " shift M text to the left\n" + - " do not show SYNTAX ERROR always (may be show send clock?q) FIXED\n" + - " ln(8)*log(8) => ln(8)*og(8) FIXED\n" + - " copy/paste ln(8)*log(8)\n" + - " 6!^2 ERROR"); + textHighlighter.process("cannot calculate 3^10^10 !!!\n" + + " unable to enter 0. FIXED\n" + + " empty display in Xperia Rayo\n" + + " check привиденная FIXED\n" + + " set display result only if text in editor was not changed FIXED\n" + + " shift M text to the left\n" + + " do not show SYNTAX ERROR always (may be show send clock?q) FIXED\n" + + " ln(8)*log(8) => ln(8)*og(8) FIXED\n" + + " copy/paste ln(8)*log(8)\n" + + " 6!^2 ERROR"); - assertEquals("sin(2)", textHighlighter.process("sin(2)").toString()); - assertEquals("atanh(2)", textHighlighter.process("atanh(2)").toString()); + assertEquals("sin(2)", textHighlighter.process("sin(2)").toString()); + assertEquals("atanh(2)", textHighlighter.process("atanh(2)").toString()); - assertEquals("0x:E", textHighlighter.process("0x:E").toString()); - assertEquals("0x:6F", textHighlighter.process("0x:6F").toString()); - assertEquals("0x:6F.", textHighlighter.process("0x:6F.").toString()); - assertEquals("0x:6F.2", textHighlighter.process("0x:6F.2").toString()); - assertEquals("0x:6F.B", textHighlighter.process("0x:6F.B").toString()); - assertEquals("0x:006F.B", textHighlighter.process("0x:006F.B").toString()); - assertEquals("0x:0", textHighlighter.process("0x:0").toString()); - assertEquals("0x:FF33233FFE", textHighlighter.process("0x:FF33233FFE").toString()); - assertEquals("0x:FF33 233 FFE", textHighlighter.process("0x:FF33 233 FFE").toString()); + assertEquals("0x:E", textHighlighter.process("0x:E").toString()); + assertEquals("0x:6F", textHighlighter.process("0x:6F").toString()); + assertEquals("0x:6F.", textHighlighter.process("0x:6F.").toString()); + assertEquals("0x:6F.2", textHighlighter.process("0x:6F.2").toString()); + assertEquals("0x:6F.B", textHighlighter.process("0x:6F.B").toString()); + assertEquals("0x:006F.B", textHighlighter.process("0x:006F.B").toString()); + assertEquals("0x:0", textHighlighter.process("0x:0").toString()); + assertEquals("0x:FF33233FFE", textHighlighter.process("0x:FF33233FFE").toString()); + assertEquals("0x:FF33 233 FFE", textHighlighter.process("0x:FF33 233 FFE").toString()); - final MathEngine me = Locator.getInstance().getEngine().getMathEngine0(); - try { - me.setNumeralBase(NumeralBase.hex); - assertEquals("E", textHighlighter.process("E").toString()); - assertEquals(".E", textHighlighter.process(".E").toString()); - assertEquals("E+", textHighlighter.process("E+").toString()); - assertEquals("E.", textHighlighter.process("E.").toString()); - assertEquals(".E.", textHighlighter.process(".E.").toString()); - assertEquals("6F", textHighlighter.process("6F").toString()); - assertEquals("6F", textHighlighter.process("6F").toString()); - assertEquals("6F.", textHighlighter.process("6F.").toString()); - assertEquals("6F.2", textHighlighter.process("6F.2").toString()); - assertEquals("6F.B", textHighlighter.process("6F.B").toString()); - assertEquals("006F.B", textHighlighter.process("006F.B").toString()); - } finally { - me.setNumeralBase(NumeralBase.dec); - } + final MathEngine me = Locator.getInstance().getEngine().getMathEngine0(); + try { + me.setNumeralBase(NumeralBase.hex); + assertEquals("E", textHighlighter.process("E").toString()); + assertEquals(".E", textHighlighter.process(".E").toString()); + assertEquals("E+", textHighlighter.process("E+").toString()); + assertEquals("E.", textHighlighter.process("E.").toString()); + assertEquals(".E.", textHighlighter.process(".E.").toString()); + assertEquals("6F", textHighlighter.process("6F").toString()); + assertEquals("6F", textHighlighter.process("6F").toString()); + assertEquals("6F.", textHighlighter.process("6F.").toString()); + assertEquals("6F.2", textHighlighter.process("6F.2").toString()); + assertEquals("6F.B", textHighlighter.process("6F.B").toString()); + assertEquals("006F.B", textHighlighter.process("006F.B").toString()); + } finally { + me.setNumeralBase(NumeralBase.dec); + } - assertEquals("0b:110101", textHighlighter.process("0b:110101").toString()); - assertEquals("0b:110101.", textHighlighter.process("0b:110101.").toString()); - assertEquals("0b:110101.101", textHighlighter.process("0b:110101.101").toString()); - assertEquals("0b:11010100.1", textHighlighter.process("0b:11010100.1").toString()); - assertEquals("0b:110101.0", textHighlighter.process("0b:110101.0").toString()); - assertEquals("0b:0", textHighlighter.process("0b:0").toString()); - assertEquals("0b:1010100101111010101001", textHighlighter.process("0b:1010100101111010101001").toString()); - assertEquals("0b:101 010 01 0 111 1 0 10101001", textHighlighter.process("0b:101 010 01 0 111 1 0 10101001").toString()); + assertEquals("0b:110101", textHighlighter.process("0b:110101").toString()); + assertEquals("0b:110101.", textHighlighter.process("0b:110101.").toString()); + assertEquals("0b:110101.101", textHighlighter.process("0b:110101.101").toString()); + assertEquals("0b:11010100.1", textHighlighter.process("0b:11010100.1").toString()); + assertEquals("0b:110101.0", textHighlighter.process("0b:110101.0").toString()); + assertEquals("0b:0", textHighlighter.process("0b:0").toString()); + assertEquals("0b:1010100101111010101001", textHighlighter.process("0b:1010100101111010101001").toString()); + assertEquals("0b:101 010 01 0 111 1 0 10101001", textHighlighter.process("0b:101 010 01 0 111 1 0 10101001").toString()); - try { - me.setNumeralBase(NumeralBase.bin); - assertEquals("110101", textHighlighter.process("110101").toString()); - assertEquals("110101.", textHighlighter.process("110101.").toString()); - assertEquals("110101.101", textHighlighter.process("110101.101").toString()); - assertEquals("11010100.1", textHighlighter.process("11010100.1").toString()); - assertEquals("110101.0", textHighlighter.process("110101.0").toString()); - assertEquals("0", textHighlighter.process("0").toString()); - assertEquals("1010100101111010101001", textHighlighter.process("1010100101111010101001").toString()); - assertEquals("101 010 01 0 111 1 0 10101001", textHighlighter.process("101 010 01 0 111 1 0 10101001").toString()); - } finally { - me.setNumeralBase(NumeralBase.dec); - } - } + try { + me.setNumeralBase(NumeralBase.bin); + assertEquals("110101", textHighlighter.process("110101").toString()); + assertEquals("110101.", textHighlighter.process("110101.").toString()); + assertEquals("110101.101", textHighlighter.process("110101.101").toString()); + assertEquals("11010100.1", textHighlighter.process("11010100.1").toString()); + assertEquals("110101.0", textHighlighter.process("110101.0").toString()); + assertEquals("0", textHighlighter.process("0").toString()); + assertEquals("1010100101111010101001", textHighlighter.process("1010100101111010101001").toString()); + assertEquals("101 010 01 0 111 1 0 10101001", textHighlighter.process("101 010 01 0 111 1 0 10101001").toString()); + } finally { + me.setNumeralBase(NumeralBase.dec); + } + } - @Test - public void testTime() throws Exception { - final TextProcessor textHighlighter = new TextHighlighter(Color.WHITE, false); + @Test + public void testTime() throws Exception { + final TextProcessor textHighlighter = new TextHighlighter(Color.WHITE, false); - final int count = 1000; - final String subExpression = "cos(acos(t8ln(t5t85tln(8ln(5t55tln(5))))))+tln(88cos(tln(t)))+t√(ln(t))"; - final StringBuilder expression = new StringBuilder(subExpression.length() * count); - for (int i = 0; i < count; i++) { - expression.append(subExpression); - expression.append("+"); - } - expression.append(subExpression); + final int count = 1000; + final String subExpression = "cos(acos(t8ln(t5t85tln(8ln(5t55tln(5))))))+tln(88cos(tln(t)))+t√(ln(t))"; + final StringBuilder expression = new StringBuilder(subExpression.length() * count); + for (int i = 0; i < count; i++) { + expression.append(subExpression); + expression.append("+"); + } + expression.append(subExpression); - long startTime = System.currentTimeMillis(); - textHighlighter.process(expression.toString()); - long endTime = System.currentTimeMillis(); - System.out.println("Total time, ms: " + (endTime - startTime)); - } + long startTime = System.currentTimeMillis(); + textHighlighter.process(expression.toString()); + long endTime = System.currentTimeMillis(); + System.out.println("Total time, ms: " + (endTime - startTime)); + } - @Test - public void testDarkColor() throws Exception { - final TextProcessor textHighlighter = new TextHighlighter(Color.BLACK, false); - assertEquals("", textHighlighter.process("sin(2cos(3))")); - } + @Test + public void testDarkColor() throws Exception { + final TextProcessor textHighlighter = new TextHighlighter(Color.BLACK, false); + assertEquals("", textHighlighter.process("sin(2cos(3))")); + } - @Test - public void testIsDark() throws Exception { - assertFalse(TextHighlighter.isDark(Color.WHITE)); - assertFalse(TextHighlighter.isDark(Color.LTGRAY)); - assertTrue(TextHighlighter.isDark(Color.DKGRAY)); - assertTrue(TextHighlighter.isDark(Color.BLACK)); + @Test + public void testIsDark() throws Exception { + assertFalse(TextHighlighter.isDark(Color.WHITE)); + assertFalse(TextHighlighter.isDark(Color.LTGRAY)); + assertTrue(TextHighlighter.isDark(Color.DKGRAY)); + assertTrue(TextHighlighter.isDark(Color.BLACK)); - } + } } diff --git a/android-app-tests/src/test/java/org/solovyev/android/calculator/history/HistoryUtilsTest.java b/android-app-tests/src/test/java/org/solovyev/android/calculator/history/HistoryUtilsTest.java index 6cf6ace2..4177c77f 100644 --- a/android-app-tests/src/test/java/org/solovyev/android/calculator/history/HistoryUtilsTest.java +++ b/android-app-tests/src/test/java/org/solovyev/android/calculator/history/HistoryUtilsTest.java @@ -47,163 +47,161 @@ import static org.junit.Assert.assertEquals; */ public class HistoryUtilsTest { - @Test - public void testFromXml() throws Exception { + private static final String emptyHistory = "\n" + + " \n" + + ""; + private static final String toXml1 = "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " 3\n" + + " 1+1\n" + + " \n" + + " \n" + + " \n" + + " 0\n" + + " Error\n" + + " \n" + + " simplify\n" + + " \n" + + " \n" + + " \n" + + ""; + private static final String toXml2 = "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " 3\n" + + " 1+1\n" + + " \n" + + " \n" + + " \n" + + " 0\n" + + " Error\n" + + " \n" + + " simplify\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " 2\n" + + " 5/6\n" + + " \n" + + " \n" + + " \n" + + " 3\n" + + " 5/6\n" + + " \n" + + " numeric\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " 1\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " 0\n" + + " Error\n" + + " \n" + + " elementary\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " 0\n" + + " 4+5/35sin(41)+dfdsfsdfs\n" + + " \n" + + " \n" + + " \n" + + " 1\n" + + " 4+5/35sin(41)+dfdsfsdfs\n" + + " \n" + + " numeric\n" + + " \n" + + " \n" + + " \n" + + ""; - } + @Test + public void testFromXml() throws Exception { - private static final String emptyHistory = "\n" + - " \n" + - ""; + } - private static final String toXml1 = "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " 3\n" + - " 1+1\n" + - " \n" + - " \n" + - " \n" + - " 0\n" + - " Error\n" + - " \n" + - " simplify\n" + - " \n" + - " \n" + - " \n" + - ""; + @Test + public void testToXml() throws Exception { + final Date date = new Date(100000000); - private static final String toXml2 = "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " 3\n" + - " 1+1\n" + - " \n" + - " \n" + - " \n" + - " 0\n" + - " Error\n" + - " \n" + - " simplify\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " 2\n" + - " 5/6\n" + - " \n" + - " \n" + - " \n" + - " 3\n" + - " 5/6\n" + - " \n" + - " numeric\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " 1\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " 0\n" + - " Error\n" + - " \n" + - " elementary\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " 0\n" + - " 4+5/35sin(41)+dfdsfsdfs\n" + - " \n" + - " \n" + - " \n" + - " 1\n" + - " 4+5/35sin(41)+dfdsfsdfs\n" + - " \n" + - " numeric\n" + - " \n" + - " \n" + - " \n" + - ""; + HistoryHelper history = SimpleHistoryHelper.newInstance(); - @Test - public void testToXml() throws Exception { - final Date date = new Date(100000000); + CalculatorDisplayViewState calculatorDisplay = CalculatorDisplayViewStateImpl.newErrorState(JsclOperation.simplify, "Error"); - HistoryHelper history = SimpleHistoryHelper.newInstance(); + CalculatorEditorViewState calculatorEditor = CalculatorEditorViewStateImpl.newInstance("1+1", 3); - CalculatorDisplayViewState calculatorDisplay = CalculatorDisplayViewStateImpl.newErrorState(JsclOperation.simplify, "Error"); + CalculatorHistoryState state = CalculatorHistoryState.newInstance(calculatorEditor, calculatorDisplay); + state.setTime(date.getTime()); + history.addState(state); - CalculatorEditorViewState calculatorEditor = CalculatorEditorViewStateImpl.newInstance("1+1", 3); - - CalculatorHistoryState state = CalculatorHistoryState.newInstance(calculatorEditor, calculatorDisplay); - state.setTime(date.getTime()); - history.addState(state); - - assertEquals(emptyHistory, HistoryUtils.toXml(history.getStates())); + assertEquals(emptyHistory, HistoryUtils.toXml(history.getStates())); - state.setSaved(true); + state.setSaved(true); - assertEquals(toXml1, HistoryUtils.toXml(history.getStates())); + assertEquals(toXml1, HistoryUtils.toXml(history.getStates())); - calculatorDisplay = CalculatorDisplayViewStateImpl.newValidState(JsclOperation.numeric, null, "5/6", 3); + calculatorDisplay = CalculatorDisplayViewStateImpl.newValidState(JsclOperation.numeric, null, "5/6", 3); - calculatorEditor = CalculatorEditorViewStateImpl.newInstance("5/6", 2); + calculatorEditor = CalculatorEditorViewStateImpl.newInstance("5/6", 2); - state = CalculatorHistoryState.newInstance(calculatorEditor, calculatorDisplay); - state.setSaved(true); - state.setTime(date.getTime()); - history.addState(state); + state = CalculatorHistoryState.newInstance(calculatorEditor, calculatorDisplay); + state.setSaved(true); + state.setTime(date.getTime()); + history.addState(state); - calculatorDisplay = CalculatorDisplayViewStateImpl.newErrorState(JsclOperation.elementary, "Error"); + calculatorDisplay = CalculatorDisplayViewStateImpl.newErrorState(JsclOperation.elementary, "Error"); - calculatorEditor = CalculatorEditorViewStateImpl.newInstance("", 1); + calculatorEditor = CalculatorEditorViewStateImpl.newInstance("", 1); - state = CalculatorHistoryState.newInstance(calculatorEditor, calculatorDisplay); - state.setSaved(true); - state.setTime(date.getTime()); - history.addState(state); + state = CalculatorHistoryState.newInstance(calculatorEditor, calculatorDisplay); + state.setSaved(true); + state.setTime(date.getTime()); + history.addState(state); - calculatorDisplay = CalculatorDisplayViewStateImpl.newValidState(JsclOperation.numeric, null, "4+5/35sin(41)+dfdsfsdfs", 1); + calculatorDisplay = CalculatorDisplayViewStateImpl.newValidState(JsclOperation.numeric, null, "4+5/35sin(41)+dfdsfsdfs", 1); - calculatorEditor = CalculatorEditorViewStateImpl.newInstance("4+5/35sin(41)+dfdsfsdfs", 0); + calculatorEditor = CalculatorEditorViewStateImpl.newInstance("4+5/35sin(41)+dfdsfsdfs", 0); - state = CalculatorHistoryState.newInstance(calculatorEditor, calculatorDisplay); - state.setSaved(true); - state.setTime(date.getTime()); - history.addState(state); + state = CalculatorHistoryState.newInstance(calculatorEditor, calculatorDisplay); + state.setSaved(true); + state.setTime(date.getTime()); + history.addState(state); - String xml = HistoryUtils.toXml(history.getStates()); - assertEquals(toXml2, xml); + String xml = HistoryUtils.toXml(history.getStates()); + assertEquals(toXml2, xml); - final List fromXml = new ArrayList(); - final HistoryHelper historyFromXml = SimpleHistoryHelper.newInstance(); - HistoryUtils.fromXml(xml, fromXml); - for (CalculatorHistoryState historyState : fromXml) { - historyFromXml.addState(historyState); - } + final List fromXml = new ArrayList(); + final HistoryHelper historyFromXml = SimpleHistoryHelper.newInstance(); + HistoryUtils.fromXml(xml, fromXml); + for (CalculatorHistoryState historyState : fromXml) { + historyFromXml.addState(historyState); + } - assertEquals(history.getStates().size(), historyFromXml.getStates().size()); + assertEquals(history.getStates().size(), historyFromXml.getStates().size()); - for (CalculatorHistoryState historyState : history.getStates()) { - historyState.setId(0); - historyState.setSaved(true); - } - for (CalculatorHistoryState historyState : historyFromXml.getStates()) { - historyState.setId(0); - historyState.setSaved(true); - } - Assert.assertTrue(Objects.areEqual(history.getStates(), historyFromXml.getStates(), new CollectionEqualizer(null))); - } + for (CalculatorHistoryState historyState : history.getStates()) { + historyState.setId(0); + historyState.setSaved(true); + } + for (CalculatorHistoryState historyState : historyFromXml.getStates()) { + historyState.setId(0); + historyState.setSaved(true); + } + Assert.assertTrue(Objects.areEqual(history.getStates(), historyFromXml.getStates(), new CollectionEqualizer(null))); + } } diff --git a/android-app-tests/src/test/java/org/solovyev/android/calculator/model/VarTest.java b/android-app-tests/src/test/java/org/solovyev/android/calculator/model/VarTest.java index 26bd070c..94b985e4 100644 --- a/android-app-tests/src/test/java/org/solovyev/android/calculator/model/VarTest.java +++ b/android-app-tests/src/test/java/org/solovyev/android/calculator/model/VarTest.java @@ -22,14 +22,14 @@ package org.solovyev.android.calculator.model; -import jscl.math.function.IConstant; - import org.junit.Test; import org.simpleframework.xml.Serializer; import org.simpleframework.xml.core.Persister; import java.io.StringWriter; +import jscl.math.function.IConstant; + import static org.junit.Assert.assertEquals; /** @@ -39,48 +39,48 @@ import static org.junit.Assert.assertEquals; */ public class VarTest { - private static final String xml = "\n" + - " \n" + - " \n" + - " e\n" + - " 2.718281828459045\n" + - " true\n" + - " description\n" + - " \n" + - " \n" + - " ;\n" + - " 3.0\n" + - " true\n" + - " \n" + - " \n" + - ""; + private static final String xml = "\n" + + " \n" + + " \n" + + " e\n" + + " 2.718281828459045\n" + + " true\n" + + " description\n" + + " \n" + + " \n" + + " ;\n" + + " 3.0\n" + + " true\n" + + " \n" + + " \n" + + ""; - @Test - public void testXml() throws Exception { - final Vars vars = new Vars(); - Var first = new Var.Builder("e", Math.E).setDescription("description").setSystem(true).create(); - vars.getEntities().add(first); - Var second = new Var.Builder(";", 3d).setSystem(true).create(); - vars.getEntities().add(second); + @Test + public void testXml() throws Exception { + final Vars vars = new Vars(); + Var first = new Var.Builder("e", Math.E).setDescription("description").setSystem(true).create(); + vars.getEntities().add(first); + Var second = new Var.Builder(";", 3d).setSystem(true).create(); + vars.getEntities().add(second); - final StringWriter sw = new StringWriter(); - final Serializer serializer = new Persister(); - serializer.write(vars, sw); + final StringWriter sw = new StringWriter(); + final Serializer serializer = new Persister(); + serializer.write(vars, sw); - assertEquals(xml, sw.toString()); + assertEquals(xml, sw.toString()); - final Vars result = serializer.read(Vars.class, xml); - final IConstant actualFirst = result.getEntities().get(0); - final IConstant actualSecond = result.getEntities().get(1); + final Vars result = serializer.read(Vars.class, xml); + final IConstant actualFirst = result.getEntities().get(0); + final IConstant actualSecond = result.getEntities().get(1); - areEqual(first, actualFirst); - areEqual(second, actualSecond); + areEqual(first, actualFirst); + areEqual(second, actualSecond); - } + } - private void areEqual(IConstant expected, IConstant actual) { - assertEquals(expected.getName(), actual.getName()); - assertEquals(expected.getDescription(), actual.getDescription()); - assertEquals(expected.getValue(), actual.getValue()); - } + private void areEqual(IConstant expected, IConstant actual) { + assertEquals(expected.getName(), actual.getName()); + assertEquals(expected.getDescription(), actual.getDescription()); + assertEquals(expected.getValue(), actual.getValue()); + } } diff --git a/android-app-tests/src/test/java/org/solovyev/android/calculator/plot/CalculatorGraph2dViewTest.java b/android-app-tests/src/test/java/org/solovyev/android/calculator/plot/CalculatorGraph2dViewTest.java index d09133f5..822d0598 100644 --- a/android-app-tests/src/test/java/org/solovyev/android/calculator/plot/CalculatorGraph2dViewTest.java +++ b/android-app-tests/src/test/java/org/solovyev/android/calculator/plot/CalculatorGraph2dViewTest.java @@ -36,28 +36,28 @@ import static org.junit.Assert.assertEquals; */ public class CalculatorGraph2dViewTest { - @Test - public void testFormatTick() throws Exception { - assertEquals("23324", CalculatorGraph2dView.formatTick(23324.0f, 0)); + @Test + public void testFormatTick() throws Exception { + assertEquals("23324", CalculatorGraph2dView.formatTick(23324.0f, 0)); - final DecimalFormat format = (DecimalFormat) DecimalFormat.getInstance(); - final DecimalFormatSymbols decimalFormatSymbols = format.getDecimalFormatSymbols(); - if (',' == decimalFormatSymbols.getDecimalSeparator()) { - assertEquals("23324,1", CalculatorGraph2dView.formatTick(23324.1f, 1)); - } else if ('.' == decimalFormatSymbols.getDecimalSeparator()) { - assertEquals("23324.1", CalculatorGraph2dView.formatTick(23324.1f, 1)); - } - } + final DecimalFormat format = (DecimalFormat) DecimalFormat.getInstance(); + final DecimalFormatSymbols decimalFormatSymbols = format.getDecimalFormatSymbols(); + if (',' == decimalFormatSymbols.getDecimalSeparator()) { + assertEquals("23324,1", CalculatorGraph2dView.formatTick(23324.1f, 1)); + } else if ('.' == decimalFormatSymbols.getDecimalSeparator()) { + assertEquals("23324.1", CalculatorGraph2dView.formatTick(23324.1f, 1)); + } + } - @Test - public void testCountTickDigits() throws Exception { - assertEquals(0, CalculatorGraph2dView.countTickDigits(1)); - assertEquals(0, CalculatorGraph2dView.countTickDigits(10)); - assertEquals(0, CalculatorGraph2dView.countTickDigits(100)); - assertEquals(1, CalculatorGraph2dView.countTickDigits(0.9f)); - assertEquals(1, CalculatorGraph2dView.countTickDigits(0.2f)); - assertEquals(1, CalculatorGraph2dView.countTickDigits(0.1f)); - assertEquals(2, CalculatorGraph2dView.countTickDigits(0.099f)); - assertEquals(3, CalculatorGraph2dView.countTickDigits(0.009f)); - } + @Test + public void testCountTickDigits() throws Exception { + assertEquals(0, CalculatorGraph2dView.countTickDigits(1)); + assertEquals(0, CalculatorGraph2dView.countTickDigits(10)); + assertEquals(0, CalculatorGraph2dView.countTickDigits(100)); + assertEquals(1, CalculatorGraph2dView.countTickDigits(0.9f)); + assertEquals(1, CalculatorGraph2dView.countTickDigits(0.2f)); + assertEquals(1, CalculatorGraph2dView.countTickDigits(0.1f)); + assertEquals(2, CalculatorGraph2dView.countTickDigits(0.099f)); + assertEquals(3, CalculatorGraph2dView.countTickDigits(0.009f)); + } } diff --git a/android-app-tests/src/test/java/org/solovyev/android/calculator/view/AngleUnitsButtonTest.java b/android-app-tests/src/test/java/org/solovyev/android/calculator/view/AngleUnitsButtonTest.java index fa8a4b23..bdae3a13 100644 --- a/android-app-tests/src/test/java/org/solovyev/android/calculator/view/AngleUnitsButtonTest.java +++ b/android-app-tests/src/test/java/org/solovyev/android/calculator/view/AngleUnitsButtonTest.java @@ -1,6 +1,7 @@ package org.solovyev.android.calculator.view; import android.app.Activity; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -12,8 +13,14 @@ import org.robolectric.shadows.ShadowActivity; import java.util.ArrayList; -import static jscl.AngleUnit.*; -import static org.junit.Assert.*; +import static jscl.AngleUnit.deg; +import static jscl.AngleUnit.grad; +import static jscl.AngleUnit.rad; +import static jscl.AngleUnit.turns; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.solovyev.android.calculator.CalculatorTestUtils.staticSetUp; @@ -21,46 +28,46 @@ import static org.solovyev.android.calculator.CalculatorTestUtils.staticSetUp; @RunWith(RobolectricTestRunner.class) public class AngleUnitsButtonTest { - private AngleUnitsButton button; + private AngleUnitsButton button; - @Before - public void setUp() throws Exception { - staticSetUp(); + @Before + public void setUp() throws Exception { + staticSetUp(); - final Activity context = Robolectric.buildActivity(Activity.class).create().get(); - final ShadowActivity activity = Robolectric.shadowOf(context); - button = new AngleUnitsButton(context, activity.createAttributeSet(new ArrayList(), AngleUnitsButton.class)); - } + final Activity context = Robolectric.buildActivity(Activity.class).create().get(); + final ShadowActivity activity = Robolectric.shadowOf(context); + button = new AngleUnitsButton(context, activity.createAttributeSet(new ArrayList(), AngleUnitsButton.class)); + } - @Test - public void testShouldReturnDifferentColorsForDifferentAngleUnits() throws Exception { - button.setAngleUnit(deg); + @Test + public void testShouldReturnDifferentColorsForDifferentAngleUnits() throws Exception { + button.setAngleUnit(deg); - assertEquals(button.getDirectionTextColor(deg.name()), button.getDirectionTextColor(deg.name())); - assertEquals(button.getDirectionTextColor(grad.name()), button.getDirectionTextColor(rad.name())); - assertNotSame(button.getDirectionTextColor(deg.name()), button.getDirectionTextColor(rad.name())); - assertNotSame(button.getDirectionTextColor(deg.name()), button.getDirectionTextColor(grad.name())); - assertNotSame(button.getDirectionTextColor(deg.name()), button.getDirectionTextColor(turns.name())); - } + assertEquals(button.getDirectionTextColor(deg.name()), button.getDirectionTextColor(deg.name())); + assertEquals(button.getDirectionTextColor(grad.name()), button.getDirectionTextColor(rad.name())); + assertNotSame(button.getDirectionTextColor(deg.name()), button.getDirectionTextColor(rad.name())); + assertNotSame(button.getDirectionTextColor(deg.name()), button.getDirectionTextColor(grad.name())); + assertNotSame(button.getDirectionTextColor(deg.name()), button.getDirectionTextColor(turns.name())); + } - @Test - public void testIsCurrentAngleUnits() throws Exception { - button.setAngleUnit(rad); - assertTrue(button.isCurrentAngleUnits(rad.name())); - assertFalse(button.isCurrentAngleUnits(deg.name())); - assertFalse(button.isCurrentAngleUnits(grad.name())); - } + @Test + public void testIsCurrentAngleUnits() throws Exception { + button.setAngleUnit(rad); + assertTrue(button.isCurrentAngleUnits(rad.name())); + assertFalse(button.isCurrentAngleUnits(deg.name())); + assertFalse(button.isCurrentAngleUnits(grad.name())); + } - @Test - public void testInvalidateShouldBeCalledOnlyWhenChangeIsDone() throws Exception { - button.setAngleUnit(rad); + @Test + public void testInvalidateShouldBeCalledOnlyWhenChangeIsDone() throws Exception { + button.setAngleUnit(rad); - button = Mockito.spy(button); + button = Mockito.spy(button); - button.setAngleUnit(deg); - verify(button, times(1)).invalidate(); + button.setAngleUnit(deg); + verify(button, times(1)).invalidate(); - button.setAngleUnit(deg); - verify(button, times(1)).invalidate(); - } + button.setAngleUnit(deg); + verify(button, times(1)).invalidate(); + } } diff --git a/android-app-tests/src/test/java/org/solovyev/android/calculator/view/NumeralBasesButtonTest.java b/android-app-tests/src/test/java/org/solovyev/android/calculator/view/NumeralBasesButtonTest.java index 23f3f0ff..091cabe6 100644 --- a/android-app-tests/src/test/java/org/solovyev/android/calculator/view/NumeralBasesButtonTest.java +++ b/android-app-tests/src/test/java/org/solovyev/android/calculator/view/NumeralBasesButtonTest.java @@ -1,6 +1,7 @@ package org.solovyev.android.calculator.view; import android.app.Activity; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -12,8 +13,14 @@ import org.robolectric.shadows.ShadowActivity; import java.util.ArrayList; -import static jscl.NumeralBase.*; -import static org.junit.Assert.*; +import static jscl.NumeralBase.bin; +import static jscl.NumeralBase.dec; +import static jscl.NumeralBase.hex; +import static jscl.NumeralBase.oct; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.solovyev.android.calculator.CalculatorTestUtils.staticSetUp; @@ -21,46 +28,46 @@ import static org.solovyev.android.calculator.CalculatorTestUtils.staticSetUp; @RunWith(RobolectricTestRunner.class) public class NumeralBasesButtonTest { - private NumeralBasesButton button; + private NumeralBasesButton button; - @Before - public void setUp() throws Exception { - staticSetUp(); + @Before + public void setUp() throws Exception { + staticSetUp(); - final Activity context = Robolectric.buildActivity(Activity.class).create().get(); - final ShadowActivity activity = Robolectric.shadowOf(context); - button = new NumeralBasesButton(context, activity.createAttributeSet(new ArrayList(), NumeralBasesButton.class)); - } + final Activity context = Robolectric.buildActivity(Activity.class).create().get(); + final ShadowActivity activity = Robolectric.shadowOf(context); + button = new NumeralBasesButton(context, activity.createAttributeSet(new ArrayList(), NumeralBasesButton.class)); + } - @Test - public void testShouldReturnDifferentColorsForDifferentNumeralBase() throws Exception { - button.setNumeralBase(dec); + @Test + public void testShouldReturnDifferentColorsForDifferentNumeralBase() throws Exception { + button.setNumeralBase(dec); - assertEquals(button.getDirectionTextColor(dec.name()), button.getDirectionTextColor(dec.name())); - assertEquals(button.getDirectionTextColor(hex.name()), button.getDirectionTextColor(bin.name())); - assertNotSame(button.getDirectionTextColor(dec.name()), button.getDirectionTextColor(bin.name())); - assertNotSame(button.getDirectionTextColor(dec.name()), button.getDirectionTextColor(hex.name())); - assertNotSame(button.getDirectionTextColor(dec.name()), button.getDirectionTextColor(oct.name())); - } + assertEquals(button.getDirectionTextColor(dec.name()), button.getDirectionTextColor(dec.name())); + assertEquals(button.getDirectionTextColor(hex.name()), button.getDirectionTextColor(bin.name())); + assertNotSame(button.getDirectionTextColor(dec.name()), button.getDirectionTextColor(bin.name())); + assertNotSame(button.getDirectionTextColor(dec.name()), button.getDirectionTextColor(hex.name())); + assertNotSame(button.getDirectionTextColor(dec.name()), button.getDirectionTextColor(oct.name())); + } - @Test - public void testIsCurrentNumeralBase() throws Exception { - button.setNumeralBase(dec); - assertTrue(button.isCurrentNumberBase(dec.name())); - assertFalse(button.isCurrentNumberBase(hex.name())); - assertFalse(button.isCurrentNumberBase(bin.name())); - } + @Test + public void testIsCurrentNumeralBase() throws Exception { + button.setNumeralBase(dec); + assertTrue(button.isCurrentNumberBase(dec.name())); + assertFalse(button.isCurrentNumberBase(hex.name())); + assertFalse(button.isCurrentNumberBase(bin.name())); + } - @Test - public void testInvalidateShouldBeCalledOnlyWhenChangeIsDone() throws Exception { - button.setNumeralBase(dec); + @Test + public void testInvalidateShouldBeCalledOnlyWhenChangeIsDone() throws Exception { + button.setNumeralBase(dec); - button = Mockito.spy(button); + button = Mockito.spy(button); - button.setNumeralBase(hex); - verify(button, times(1)).invalidate(); + button.setNumeralBase(hex); + verify(button, times(1)).invalidate(); - button.setNumeralBase(hex); - verify(button, times(1)).invalidate(); - } + button.setNumeralBase(hex); + verify(button, times(1)).invalidate(); + } } diff --git a/android-app-tests/src/test/java/org/solovyev/android/calculator/wizard/CalculatorWizardActivityTest.java b/android-app-tests/src/test/java/org/solovyev/android/calculator/wizard/CalculatorWizardActivityTest.java index 082ac1b6..7ce7e6cf 100644 --- a/android-app-tests/src/test/java/org/solovyev/android/calculator/wizard/CalculatorWizardActivityTest.java +++ b/android-app-tests/src/test/java/org/solovyev/android/calculator/wizard/CalculatorWizardActivityTest.java @@ -26,6 +26,7 @@ import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -37,161 +38,166 @@ import org.solovyev.android.wizard.Wizard; import org.solovyev.android.wizard.WizardUi; import org.solovyev.android.wizard.Wizards; -import javax.annotation.Nonnull; import java.lang.reflect.Field; -import static org.junit.Assert.*; +import javax.annotation.Nonnull; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; import static org.solovyev.android.calculator.wizard.CalculatorWizardStep.choose_mode; @RunWith(value = CalculatorTestRunner.class) public class CalculatorWizardActivityTest { - private ActivityController controller; - private WizardActivity activity; - private Wizards wizards; - private Field uiField; + private ActivityController controller; + private WizardActivity activity; + private Wizards wizards; + private Field uiField; - @Before - public void setUp() throws Exception { - controller = Robolectric.buildActivity(WizardActivity.class); - activity = controller.get(); - wizards = new CalculatorWizards(Robolectric.application); - activity.setWizards(wizards); - controller.attach(); - controller.create(); + @Before + public void setUp() throws Exception { + controller = Robolectric.buildActivity(WizardActivity.class); + activity = controller.get(); + wizards = new CalculatorWizards(Robolectric.application); + activity.setWizards(wizards); + controller.attach(); + controller.create(); - uiField = WizardActivity.class.getDeclaredField("wizardUi"); - uiField.setAccessible(true); - } + uiField = WizardActivity.class.getDeclaredField("wizardUi"); + uiField.setAccessible(true); + } - @Test - public void testShouldBeFirstTimeWizardByDefault() throws Exception { - assertEquals(CalculatorWizards.FIRST_TIME_WIZARD, getWizardUi().getWizard().getName()); - } + @Test + public void testShouldBeFirstTimeWizardByDefault() throws Exception { + assertEquals(CalculatorWizards.FIRST_TIME_WIZARD, getWizardUi().getWizard().getName()); + } - @Nonnull - private WizardUi getWizardUi() throws IllegalAccessException { - return (WizardUi) uiField.get(activity); - } + @Nonnull + private WizardUi getWizardUi() throws IllegalAccessException { + return (WizardUi) uiField.get(activity); + } - @Test - public void testShouldBeFirstStep() throws Exception { - assertNotNull(getWizardUi().getStep()); - assertEquals(getWizardUi().getFlow().getFirstStep(), getWizardUi().getStep()); - } + @Test + public void testShouldBeFirstStep() throws Exception { + assertNotNull(getWizardUi().getStep()); + assertEquals(getWizardUi().getFlow().getFirstStep(), getWizardUi().getStep()); + } - @Test - public void testShouldSaveState() throws Exception { - getWizardUi().setStep(choose_mode); + @Test + public void testShouldSaveState() throws Exception { + getWizardUi().setStep(choose_mode); - final Bundle outState = new Bundle(); - controller.saveInstanceState(outState); + final Bundle outState = new Bundle(); + controller.saveInstanceState(outState); - controller = Robolectric.buildActivity(WizardActivity.class); - controller.create(outState); + controller = Robolectric.buildActivity(WizardActivity.class); + controller.create(outState); - activity = controller.get(); - assertNotNull(getWizardUi().getFlow()); - assertEquals(CalculatorWizards.FIRST_TIME_WIZARD, getWizardUi().getWizard().getName()); - assertNotNull(getWizardUi().getStep()); - assertEquals(choose_mode, getWizardUi().getStep()); - } + activity = controller.get(); + assertNotNull(getWizardUi().getFlow()); + assertEquals(CalculatorWizards.FIRST_TIME_WIZARD, getWizardUi().getWizard().getName()); + assertNotNull(getWizardUi().getStep()); + assertEquals(choose_mode, getWizardUi().getStep()); + } - @Test - public void testCreate() throws Exception { - final Intent intent = new Intent(); - intent.setClass(activity, WizardActivity.class); - intent.putExtra("flow", CalculatorWizards.DEFAULT_WIZARD_FLOW); - controller = Robolectric.buildActivity(WizardActivity.class).withIntent(intent); - controller.create(); - activity = controller.get(); - assertEquals(CalculatorWizards.DEFAULT_WIZARD_FLOW, getWizardUi().getWizard().getName()); - assertEquals(getWizardUi().getFlow().getFirstStep(), getWizardUi().getStep()); + @Test + public void testCreate() throws Exception { + final Intent intent = new Intent(); + intent.setClass(activity, WizardActivity.class); + intent.putExtra("flow", CalculatorWizards.DEFAULT_WIZARD_FLOW); + controller = Robolectric.buildActivity(WizardActivity.class).withIntent(intent); + controller.create(); + activity = controller.get(); + assertEquals(CalculatorWizards.DEFAULT_WIZARD_FLOW, getWizardUi().getWizard().getName()); + assertEquals(getWizardUi().getFlow().getFirstStep(), getWizardUi().getStep()); - final Bundle outState1 = new Bundle(); - controller.saveInstanceState(outState1); + final Bundle outState1 = new Bundle(); + controller.saveInstanceState(outState1); - controller = Robolectric.buildActivity(WizardActivity.class); - activity = controller.get(); - controller.create(outState1); - assertEquals(CalculatorWizards.DEFAULT_WIZARD_FLOW, getWizardUi().getWizard().getName()); - assertEquals(getWizardUi().getFlow().getFirstStep(), getWizardUi().getStep()); - } + controller = Robolectric.buildActivity(WizardActivity.class); + activity = controller.get(); + controller.create(outState1); + assertEquals(CalculatorWizards.DEFAULT_WIZARD_FLOW, getWizardUi().getWizard().getName()); + assertEquals(getWizardUi().getFlow().getFirstStep(), getWizardUi().getStep()); + } - @Test - public void testShouldAddFirstFragment() throws Exception { - controller.start().resume(); + @Test + public void testShouldAddFirstFragment() throws Exception { + controller.start().resume(); - final FragmentManager fm = activity.getSupportFragmentManager(); - final Fragment f = fm.findFragmentByTag(CalculatorWizardStep.welcome.getFragmentTag()); - assertNotNull(f); - assertTrue(f.isAdded()); - } + final FragmentManager fm = activity.getSupportFragmentManager(); + final Fragment f = fm.findFragmentByTag(CalculatorWizardStep.welcome.getFragmentTag()); + assertNotNull(f); + assertTrue(f.isAdded()); + } - @Test - public void testShouldAddStepFragment() throws Exception { - controller.start().resume(); + @Test + public void testShouldAddStepFragment() throws Exception { + controller.start().resume(); - final FragmentManager fm = activity.getSupportFragmentManager(); + final FragmentManager fm = activity.getSupportFragmentManager(); - getWizardUi().setStep(choose_mode); + getWizardUi().setStep(choose_mode); - final Fragment f = fm.findFragmentByTag(choose_mode.getFragmentTag()); - assertNotNull(f); - assertTrue(f.isAdded()); - } + final Fragment f = fm.findFragmentByTag(choose_mode.getFragmentTag()); + assertNotNull(f); + assertTrue(f.isAdded()); + } - @Test - public void testSetStep() throws Exception { - getWizardUi().setStep(choose_mode); - assertEquals(choose_mode, getWizardUi().getStep()); - } + @Test + public void testSetStep() throws Exception { + getWizardUi().setStep(choose_mode); + assertEquals(choose_mode, getWizardUi().getStep()); + } - @Test - public void testShouldStartWizardActivityAfterStart() throws Exception { - final ShadowActivity shadowActivity = Robolectric.shadowOf(controller.get()); - WizardUi.startWizard(activity.getWizards(), CalculatorWizards.DEFAULT_WIZARD_FLOW, shadowActivity.getApplicationContext()); - assertNotNull(shadowActivity.getNextStartedActivity()); - } + @Test + public void testShouldStartWizardActivityAfterStart() throws Exception { + final ShadowActivity shadowActivity = Robolectric.shadowOf(controller.get()); + WizardUi.startWizard(activity.getWizards(), CalculatorWizards.DEFAULT_WIZARD_FLOW, shadowActivity.getApplicationContext()); + assertNotNull(shadowActivity.getNextStartedActivity()); + } - @Test - public void testTitleShouldBeSet() throws Exception { - getWizardUi().setStep(choose_mode); - assertEquals(activity.getString(choose_mode.getTitleResId()), activity.getTitle().toString()); - } + @Test + public void testTitleShouldBeSet() throws Exception { + getWizardUi().setStep(choose_mode); + assertEquals(activity.getString(choose_mode.getTitleResId()), activity.getTitle().toString()); + } - private void setLastStep() throws IllegalAccessException { - getWizardUi().setStep(CalculatorWizardStep.values()[CalculatorWizardStep.values().length - 1]); - } + private void setLastStep() throws IllegalAccessException { + getWizardUi().setStep(CalculatorWizardStep.values()[CalculatorWizardStep.values().length - 1]); + } - private void setFirstStep() throws IllegalAccessException { - getWizardUi().setStep(CalculatorWizardStep.values()[0]); - } + private void setFirstStep() throws IllegalAccessException { + getWizardUi().setStep(CalculatorWizardStep.values()[0]); + } - @Test - public void testShouldSaveLastWizardStateOnPause() throws Exception { - final Wizard wizard = wizards.getWizard(getWizardUi().getWizard().getName()); - assertNull(wizard.getLastSavedStepName()); - getWizardUi().setStep(CalculatorWizardStep.drag_button); - activity.onPause(); - assertEquals(CalculatorWizardStep.drag_button.getName(), wizard.getLastSavedStepName()); - } + @Test + public void testShouldSaveLastWizardStateOnPause() throws Exception { + final Wizard wizard = wizards.getWizard(getWizardUi().getWizard().getName()); + assertNull(wizard.getLastSavedStepName()); + getWizardUi().setStep(CalculatorWizardStep.drag_button); + activity.onPause(); + assertEquals(CalculatorWizardStep.drag_button.getName(), wizard.getLastSavedStepName()); + } - @Test - public void testShouldSaveFinishedIfLastStep() throws Exception { - final Wizard wizard = wizards.getWizard(getWizardUi().getWizard().getName()); - assertFalse(wizard.isFinished()); - setLastStep(); - getWizardUi().finishWizard(); - assertTrue(wizard.isFinished()); - } + @Test + public void testShouldSaveFinishedIfLastStep() throws Exception { + final Wizard wizard = wizards.getWizard(getWizardUi().getWizard().getName()); + assertFalse(wizard.isFinished()); + setLastStep(); + getWizardUi().finishWizard(); + assertTrue(wizard.isFinished()); + } - @Test - public void testShouldNotSaveFinishedIfNotLastStep() throws Exception { - final Wizard wizard = wizards.getWizard(getWizardUi().getWizard().getName()); - assertFalse(wizard.isFinished()); - setFirstStep(); - getWizardUi().finishWizard(); - assertFalse(wizard.isFinished()); - } + @Test + public void testShouldNotSaveFinishedIfNotLastStep() throws Exception { + final Wizard wizard = wizards.getWizard(getWizardUi().getWizard().getName()); + assertFalse(wizard.isFinished()); + setFirstStep(); + getWizardUi().finishWizard(); + assertFalse(wizard.isFinished()); + } } diff --git a/android-app-tests/src/test/java/org/solovyev/android/calculator/wizard/CalculatorWizardTest.java b/android-app-tests/src/test/java/org/solovyev/android/calculator/wizard/CalculatorWizardTest.java index 272048f7..2a36cc39 100644 --- a/android-app-tests/src/test/java/org/solovyev/android/calculator/wizard/CalculatorWizardTest.java +++ b/android-app-tests/src/test/java/org/solovyev/android/calculator/wizard/CalculatorWizardTest.java @@ -11,89 +11,96 @@ import org.solovyev.android.wizard.Wizards; import javax.annotation.Nonnull; -import static org.junit.Assert.*; -import static org.solovyev.android.calculator.wizard.CalculatorWizardStep.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.solovyev.android.calculator.wizard.CalculatorWizardStep.choose_mode; +import static org.solovyev.android.calculator.wizard.CalculatorWizardStep.last; +import static org.solovyev.android.calculator.wizard.CalculatorWizardStep.welcome; @RunWith(value = CalculatorTestRunner.class) public class CalculatorWizardTest { - @Nonnull - private Wizards wizards; + @Nonnull + private Wizards wizards; - @Nonnull - private Wizard wizard; + @Nonnull + private Wizard wizard; - @Nonnull - private Wizard defaultWizard; + @Nonnull + private Wizard defaultWizard; - @Before - public void setUp() throws Exception { - wizards = new CalculatorWizards(Robolectric.application); - wizard = wizards.getWizard(null); - defaultWizard = wizards.getWizard(CalculatorWizards.DEFAULT_WIZARD_FLOW); - } + @Before + public void setUp() throws Exception { + wizards = new CalculatorWizards(Robolectric.application); + wizard = wizards.getWizard(null); + defaultWizard = wizards.getWizard(CalculatorWizards.DEFAULT_WIZARD_FLOW); + } - @Test - public void testDefaultFlowShouldNotContainWelcomeAndLastSteps() throws Exception { - final WizardFlow flow = defaultWizard.getFlow(); - assertNull(flow.getStepByName(welcome.getName())); - assertNull(flow.getStepByName(last.getName())); - } + @Test + public void testDefaultFlowShouldNotContainWelcomeAndLastSteps() throws Exception { + final WizardFlow flow = defaultWizard.getFlow(); + assertNull(flow.getStepByName(welcome.getName())); + assertNull(flow.getStepByName(last.getName())); + } - @Test - public void testFirstTimeFlowShouldContainWelcomeAndLastSteps() throws Exception { - final WizardFlow flow = wizard.getFlow(); - assertNotNull(flow.getStepByName(welcome.getName())); - assertNotNull(flow.getStepByName(last.getName())); - } + @Test + public void testFirstTimeFlowShouldContainWelcomeAndLastSteps() throws Exception { + final WizardFlow flow = wizard.getFlow(); + assertNotNull(flow.getStepByName(welcome.getName())); + assertNotNull(flow.getStepByName(last.getName())); + } - @Test - public void testShouldThrowExceptionIfUnknownWizard() throws Exception { - try { - wizards.getWizard("testtesttesttesttest"); - fail(); - } catch (IllegalArgumentException e) { - // ok - } - } + @Test + public void testShouldThrowExceptionIfUnknownWizard() throws Exception { + try { + wizards.getWizard("testtesttesttesttest"); + fail(); + } catch (IllegalArgumentException e) { + // ok + } + } - @Test - public void testShouldReturnWizard() throws Exception { - assertNotNull(wizards.getWizard(CalculatorWizards.FIRST_TIME_WIZARD)); - assertNotNull(wizards.getWizard(CalculatorWizards.DEFAULT_WIZARD_FLOW)); - } + @Test + public void testShouldReturnWizard() throws Exception { + assertNotNull(wizards.getWizard(CalculatorWizards.FIRST_TIME_WIZARD)); + assertNotNull(wizards.getWizard(CalculatorWizards.DEFAULT_WIZARD_FLOW)); + } - @Test - public void testShouldSaveWizardIsFinishedWhenNotLastStepAndForce() throws Exception { - assertFalse(wizard.isFinished()); - wizard.saveFinished(CalculatorWizardStep.drag_button, true); + @Test + public void testShouldSaveWizardIsFinishedWhenNotLastStepAndForce() throws Exception { + assertFalse(wizard.isFinished()); + wizard.saveFinished(CalculatorWizardStep.drag_button, true); - assertTrue(wizard.isFinished()); - } + assertTrue(wizard.isFinished()); + } - @Test - public void testShouldNotSaveWizardIsFinishedWhenNotLastStepAndNotForce() throws Exception { - assertFalse(wizard.isFinished()); - wizard.saveFinished(CalculatorWizardStep.drag_button, false); + @Test + public void testShouldNotSaveWizardIsFinishedWhenNotLastStepAndNotForce() throws Exception { + assertFalse(wizard.isFinished()); + wizard.saveFinished(CalculatorWizardStep.drag_button, false); - assertFalse(wizard.isFinished()); - } + assertFalse(wizard.isFinished()); + } - @Test - public void testShouldSaveWizardIsFinishedWhenLastStep() throws Exception { - assertFalse(wizard.isFinished()); - wizard.saveFinished(CalculatorWizardStep.last, false); + @Test + public void testShouldSaveWizardIsFinishedWhenLastStep() throws Exception { + assertFalse(wizard.isFinished()); + wizard.saveFinished(CalculatorWizardStep.last, false); - assertTrue(wizard.isFinished()); - } + assertTrue(wizard.isFinished()); + } - @Test - public void testShouldSaveLastWizardStep() throws Exception { - assertFalse(wizard.isStarted()); - assertNull(wizard.getLastSavedStepName()); + @Test + public void testShouldSaveLastWizardStep() throws Exception { + assertFalse(wizard.isStarted()); + assertNull(wizard.getLastSavedStepName()); - wizard.saveLastStep(choose_mode); - assertTrue(wizard.isStarted()); - assertEquals(choose_mode.name(), wizard.getLastSavedStepName()); - } + wizard.saveLastStep(choose_mode); + assertTrue(wizard.isStarted()); + assertEquals(choose_mode.name(), wizard.getLastSavedStepName()); + } } diff --git a/android-app-tests/src/test/java/org/solovyev/android/calculator/wizard/OnScreenCalculatorWizardStepTest.java b/android-app-tests/src/test/java/org/solovyev/android/calculator/wizard/OnScreenCalculatorWizardStepTest.java index 5735e9a2..2078f413 100644 --- a/android-app-tests/src/test/java/org/solovyev/android/calculator/wizard/OnScreenCalculatorWizardStepTest.java +++ b/android-app-tests/src/test/java/org/solovyev/android/calculator/wizard/OnScreenCalculatorWizardStepTest.java @@ -30,58 +30,59 @@ import org.robolectric.util.ActivityController; import org.solovyev.android.CalculatorTestRunner; import org.solovyev.android.wizard.WizardUi; -import javax.annotation.Nonnull; import java.lang.reflect.Field; +import javax.annotation.Nonnull; + import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @RunWith(CalculatorTestRunner.class) public class OnScreenCalculatorWizardStepTest { - @Nonnull - private OnScreenCalculatorWizardStep fragment; + @Nonnull + private OnScreenCalculatorWizardStep fragment; - @Nonnull - private WizardActivity activity; + @Nonnull + private WizardActivity activity; - @Nonnull - private ActivityController controller; - private Field uiField; + @Nonnull + private ActivityController controller; + private Field uiField; - @Before - public void setUp() throws Exception { - uiField = WizardActivity.class.getDeclaredField("wizardUi"); - uiField.setAccessible(true); + @Before + public void setUp() throws Exception { + uiField = WizardActivity.class.getDeclaredField("wizardUi"); + uiField.setAccessible(true); - createActivity(); - setFragment(); - } + createActivity(); + setFragment(); + } - @Nonnull - private WizardUi getWizardUi() throws IllegalAccessException { - return (WizardUi) uiField.get(activity); - } + @Nonnull + private WizardUi getWizardUi() throws IllegalAccessException { + return (WizardUi) uiField.get(activity); + } - private void createActivity() { - controller = Robolectric.buildActivity(WizardActivity.class).create().start().resume(); - activity = controller.get(); - } + private void createActivity() { + controller = Robolectric.buildActivity(WizardActivity.class).create().start().resume(); + activity = controller.get(); + } - private void setFragment() throws IllegalAccessException { - getWizardUi().setStep(CalculatorWizardStep.on_screen_calculator); - activity.getSupportFragmentManager().executePendingTransactions(); - fragment = (OnScreenCalculatorWizardStep) activity.getSupportFragmentManager().findFragmentByTag(CalculatorWizardStep.on_screen_calculator.getFragmentTag()); - } + private void setFragment() throws IllegalAccessException { + getWizardUi().setStep(CalculatorWizardStep.on_screen_calculator); + activity.getSupportFragmentManager().executePendingTransactions(); + fragment = (OnScreenCalculatorWizardStep) activity.getSupportFragmentManager().findFragmentByTag(CalculatorWizardStep.on_screen_calculator.getFragmentTag()); + } - @Test - public void testShouldRestoreStateOnRestart() throws Exception { - fragment.getCheckbox().setChecked(true); - controller.restart(); - assertTrue(fragment.getCheckbox().isChecked()); + @Test + public void testShouldRestoreStateOnRestart() throws Exception { + fragment.getCheckbox().setChecked(true); + controller.restart(); + assertTrue(fragment.getCheckbox().isChecked()); - fragment.getCheckbox().setChecked(false); - controller.restart(); - assertFalse(fragment.getCheckbox().isChecked()); - } + fragment.getCheckbox().setChecked(false); + controller.restart(); + assertFalse(fragment.getCheckbox().isChecked()); + } } diff --git a/android-app/build.gradle b/android-app/build.gradle index 55a84ed5..2685f6b7 100644 --- a/android-app/build.gradle +++ b/android-app/build.gradle @@ -55,7 +55,7 @@ android { } repositories { - flatDir{ + flatDir { dirs 'misc/libs' } } @@ -86,7 +86,7 @@ dependencies { compile 'com.google.android.gms:play-services-base:8.4.0' compile 'com.google.android.gms:play-services-analytics:8.4.0' compile 'com.melnykov:floatingactionbutton:1.1.0' - compile(name:'plotter', ext:'aar') + compile(name: 'plotter', ext: 'aar') debugCompile 'com.squareup.leakcanary:leakcanary-android:1.3.1' releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.3.1' diff --git a/android-app/src/main/AndroidManifest.xml b/android-app/src/main/AndroidManifest.xml index 08d06286..9dbff231 100644 --- a/android-app/src/main/AndroidManifest.xml +++ b/android-app/src/main/AndroidManifest.xml @@ -1,210 +1,310 @@ - + - - - - - + + + + + - - + + - - - + + + - - - - - + + + + + - + - + - + - - - - + + + + - + - - - - - + + + + + - + - + - + - + - + - + - + - - - - - - + + + + + + - - - - + + + + - + - + - - - - - - + + + + + + - - - - - + + + + + - + - + - - - - + + + + - + - - - - - - + + + + + + - - - - - - - + + + + + + + - + - + - - - - - - - - + + + + + + + + - - + + - + - - - - - - - - + + + + + + + + - - + + - + - - - - - - - - + + + + + + + + - - + + - + - - - - - - - - + + + + + + + + - - + + - + - - - - - - - - + + + + + + + + - - + + - + - + - + - + - - - - - - - + + + + + + + - + \ No newline at end of file diff --git a/android-app/src/main/java/com/viewpagerindicator/CirclePageIndicator.java b/android-app/src/main/java/com/viewpagerindicator/CirclePageIndicator.java index c5666391..d9711b2a 100644 --- a/android-app/src/main/java/com/viewpagerindicator/CirclePageIndicator.java +++ b/android-app/src/main/java/com/viewpagerindicator/CirclePageIndicator.java @@ -32,6 +32,7 @@ import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; + import org.solovyev.android.calculator.R; import static android.graphics.Paint.ANTI_ALIAS_FLAG; @@ -44,11 +45,10 @@ import static android.widget.LinearLayout.VERTICAL; */ public class CirclePageIndicator extends View implements PageIndicator { private static final int INVALID_POINTER = -1; - - private float mRadius; private final Paint mPaintPageFill = new Paint(ANTI_ALIAS_FLAG); private final Paint mPaintStroke = new Paint(ANTI_ALIAS_FLAG); private final Paint mPaintFill = new Paint(ANTI_ALIAS_FLAG); + private float mRadius; private ViewPager mViewPager; private ViewPager.OnPageChangeListener mListener; private int mCurrentPage; @@ -105,7 +105,7 @@ public class CirclePageIndicator extends View implements PageIndicator { Drawable background = a.getDrawable(R.styleable.CirclePageIndicator_android_background); if (background != null) { - setBackgroundDrawable(background); + setBackgroundDrawable(background); } a.recycle(); @@ -114,18 +114,12 @@ public class CirclePageIndicator extends View implements PageIndicator { mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration); } - - public void setCentered(boolean centered) { - mCentered = centered; - invalidate(); - } - public boolean isCentered() { return mCentered; } - public void setPageColor(int pageColor) { - mPaintPageFill.setColor(pageColor); + public void setCentered(boolean centered) { + mCentered = centered; invalidate(); } @@ -133,8 +127,8 @@ public class CirclePageIndicator extends View implements PageIndicator { return mPaintPageFill.getColor(); } - public void setFillColor(int fillColor) { - mPaintFill.setColor(fillColor); + public void setPageColor(int pageColor) { + mPaintPageFill.setColor(pageColor); invalidate(); } @@ -142,6 +136,15 @@ public class CirclePageIndicator extends View implements PageIndicator { return mPaintFill.getColor(); } + public void setFillColor(int fillColor) { + mPaintFill.setColor(fillColor); + invalidate(); + } + + public int getOrientation() { + return mOrientation; + } + public void setOrientation(int orientation) { switch (orientation) { case HORIZONTAL: @@ -155,8 +158,8 @@ public class CirclePageIndicator extends View implements PageIndicator { } } - public int getOrientation() { - return mOrientation; + public int getStrokeColor() { + return mPaintStroke.getColor(); } public void setStrokeColor(int strokeColor) { @@ -164,8 +167,8 @@ public class CirclePageIndicator extends View implements PageIndicator { invalidate(); } - public int getStrokeColor() { - return mPaintStroke.getColor(); + public float getStrokeWidth() { + return mPaintStroke.getStrokeWidth(); } public void setStrokeWidth(float strokeWidth) { @@ -173,8 +176,8 @@ public class CirclePageIndicator extends View implements PageIndicator { invalidate(); } - public float getStrokeWidth() { - return mPaintStroke.getStrokeWidth(); + public float getRadius() { + return mRadius; } public void setRadius(float radius) { @@ -182,8 +185,8 @@ public class CirclePageIndicator extends View implements PageIndicator { invalidate(); } - public float getRadius() { - return mRadius; + public boolean isSnap() { + return mSnap; } public void setSnap(boolean snap) { @@ -191,10 +194,6 @@ public class CirclePageIndicator extends View implements PageIndicator { invalidate(); } - public boolean isSnap() { - return mSnap; - } - @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); @@ -454,8 +453,7 @@ public class CirclePageIndicator extends View implements PageIndicator { /** * Determines the width of this view * - * @param measureSpec - * A measureSpec packed into an int + * @param measureSpec A measureSpec packed into an int * @return The width of the view, honoring constraints from measureSpec */ private int measureLong(int measureSpec) { @@ -469,7 +467,7 @@ public class CirclePageIndicator extends View implements PageIndicator { } else { //Calculate the width according the views count final int count = mViewPager.getAdapter().getCount(); - result = (int)(getPaddingLeft() + getPaddingRight() + result = (int) (getPaddingLeft() + getPaddingRight() + (count * 2 * mRadius) + (count - 1) * mRadius + 1); //Respect AT_MOST value if that was what is called for by measureSpec if (specMode == MeasureSpec.AT_MOST) { @@ -482,8 +480,7 @@ public class CirclePageIndicator extends View implements PageIndicator { /** * Determines the height of this view * - * @param measureSpec - * A measureSpec packed into an int + * @param measureSpec A measureSpec packed into an int * @return The height of the view, honoring constraints from measureSpec */ private int measureShort(int measureSpec) { @@ -496,7 +493,7 @@ public class CirclePageIndicator extends View implements PageIndicator { result = specSize; } else { //Measure the height - result = (int)(2 * mRadius + getPaddingTop() + getPaddingBottom() + 1); + result = (int) (2 * mRadius + getPaddingTop() + getPaddingBottom() + 1); //Respect AT_MOST value if that was what is called for by measureSpec if (specMode == MeasureSpec.AT_MOST) { result = Math.min(result, specSize); @@ -507,7 +504,7 @@ public class CirclePageIndicator extends View implements PageIndicator { @Override public void onRestoreInstanceState(Parcelable state) { - SavedState savedState = (SavedState)state; + SavedState savedState = (SavedState) state; super.onRestoreInstanceState(savedState.getSuperState()); mCurrentPage = savedState.currentPage; mSnapPage = savedState.currentPage; @@ -523,6 +520,18 @@ public class CirclePageIndicator extends View implements PageIndicator { } static class SavedState extends BaseSavedState { + @SuppressWarnings("UnusedDeclaration") + public static final Creator CREATOR = new Creator() { + @Override + public SavedState createFromParcel(Parcel in) { + return new SavedState(in); + } + + @Override + public SavedState[] newArray(int size) { + return new SavedState[size]; + } + }; int currentPage; public SavedState(Parcelable superState) { @@ -539,18 +548,5 @@ public class CirclePageIndicator extends View implements PageIndicator { super.writeToParcel(dest, flags); dest.writeInt(currentPage); } - - @SuppressWarnings("UnusedDeclaration") - public static final Creator CREATOR = new Creator() { - @Override - public SavedState createFromParcel(Parcel in) { - return new SavedState(in); - } - - @Override - public SavedState[] newArray(int size) { - return new SavedState[size]; - } - }; } } diff --git a/android-app/src/main/java/com/viewpagerindicator/PageIndicator.java b/android-app/src/main/java/com/viewpagerindicator/PageIndicator.java index c08c00ae..929c91a4 100644 --- a/android-app/src/main/java/com/viewpagerindicator/PageIndicator.java +++ b/android-app/src/main/java/com/viewpagerindicator/PageIndicator.java @@ -41,7 +41,7 @@ public interface PageIndicator extends ViewPager.OnPageChangeListener { /** *

Set the current page of both the ViewPager and indicator.

- * + *

*

This must be used if you need to set the page before * the views are drawn on screen (e.g., default start page).

* diff --git a/android-app/src/main/java/org/solovyev/android/Check.java b/android-app/src/main/java/org/solovyev/android/Check.java index db1877d5..0bab0fe8 100644 --- a/android-app/src/main/java/org/solovyev/android/Check.java +++ b/android-app/src/main/java/org/solovyev/android/Check.java @@ -34,139 +34,139 @@ import static java.lang.Thread.currentThread; public final class Check { - private static final boolean junit = isJunit(); + private static final boolean junit = isJunit(); - private static boolean isJunit() { - final StackTraceElement[] stackTrace = currentThread().getStackTrace(); - for (StackTraceElement element : stackTrace) { - if (element.getClassName().startsWith("org.junit.")) { - return true; - } - } - return false; - } + private Check() { + throw new AssertionError(); + } - private Check() { - throw new AssertionError(); - } + private static boolean isJunit() { + final StackTraceElement[] stackTrace = currentThread().getStackTrace(); + for (StackTraceElement element : stackTrace) { + if (element.getClassName().startsWith("org.junit.")) { + return true; + } + } + return false; + } - public static void isMainThread() { - if (!junit && Looper.getMainLooper() != Looper.myLooper()) { - throw new AssertionException("Should be called on the main thread"); - } - } + public static void isMainThread() { + if (!junit && Looper.getMainLooper() != Looper.myLooper()) { + throw new AssertionException("Should be called on the main thread"); + } + } - public static void isNotNull(@Nullable Object o) { - isNotNull(o, "Object should not be null"); - } + public static void isNotNull(@Nullable Object o) { + isNotNull(o, "Object should not be null"); + } - public static void isNotNull(@Nullable Object o, @Nonnull String message) { - if (o == null) { - throw new AssertionException(message); - } - } + public static void isNotNull(@Nullable Object o, @Nonnull String message) { + if (o == null) { + throw new AssertionException(message); + } + } - public static void notEquals(int expected, int actual) { - if (expected == actual) { - throw new AssertionException("Should not be equal"); - } - } + public static void notEquals(int expected, int actual) { + if (expected == actual) { + throw new AssertionException("Should not be equal"); + } + } - public static void equals(int expected, int actual) { - if (expected != actual) { - throw new AssertionException("Should be equal"); - } - } + public static void equals(int expected, int actual) { + if (expected != actual) { + throw new AssertionException("Should be equal"); + } + } - public static void equals(@Nullable Object expected, @Nullable Object actual) { - equals(expected, actual, "Should be equal"); - } + public static void equals(@Nullable Object expected, @Nullable Object actual) { + equals(expected, actual, "Should be equal"); + } - public static void equals(@Nullable Object expected, @Nullable Object actual, @Nonnull String message) { - if (expected == actual) { - // both nulls or same - return; - } + public static void equals(@Nullable Object expected, @Nullable Object actual, @Nonnull String message) { + if (expected == actual) { + // both nulls or same + return; + } - if (expected != null && actual != null && expected.equals(actual)) { - // equals - return; - } + if (expected != null && actual != null && expected.equals(actual)) { + // equals + return; + } - throw new AssertionException(message); - } + throw new AssertionException(message); + } - public static void isTrue(boolean expression) { - if (!expression) { - throw new AssertionException(""); - } - } + public static void isTrue(boolean expression) { + if (!expression) { + throw new AssertionException(""); + } + } - public static void isTrue(boolean expression, @Nonnull String message) { - if (!expression) { - throw new AssertionException(message); - } - } + public static void isTrue(boolean expression, @Nonnull String message) { + if (!expression) { + throw new AssertionException(message); + } + } - public static void isFalse(boolean expression, @Nonnull String message) { - if (expression) { - throw new AssertionException(message); - } - } + public static void isFalse(boolean expression, @Nonnull String message) { + if (expression) { + throw new AssertionException(message); + } + } - public static void isNull(@Nullable Object o) { - isNull(o, "Object should be null"); - } + public static void isNull(@Nullable Object o) { + isNull(o, "Object should be null"); + } - public static void isNull(@Nullable Object o, @Nonnull String message) { - if (o != null) { - throw new AssertionException(message); - } - } + public static void isNull(@Nullable Object o, @Nonnull String message) { + if (o != null) { + throw new AssertionException(message); + } + } - public static void isNotEmpty(@Nullable String s) { - if (s == null || s.length() == 0) { - throw new AssertionException("String should not be empty"); - } - } + public static void isNotEmpty(@Nullable String s) { + if (s == null || s.length() == 0) { + throw new AssertionException("String should not be empty"); + } + } - public static void isNotEmpty(@Nullable String[] array) { - if (array == null || array.length == 0) { - throw new AssertionException("Array should not be empty"); - } - } + public static void isNotEmpty(@Nullable String[] array) { + if (array == null || array.length == 0) { + throw new AssertionException("Array should not be empty"); + } + } - public static void isNotEmpty(@Nullable Collection c) { - if (c == null || c.size() == 0) { - throw new AssertionException("Collection should not be empty"); - } - } + public static void isNotEmpty(@Nullable Collection c) { + if (c == null || c.size() == 0) { + throw new AssertionException("Collection should not be empty"); + } + } - public static void isNotEmpty(@Nullable Map c) { - if (c == null || c.size() == 0) { - throw new AssertionException("Map should not be empty"); - } - } + public static void isNotEmpty(@Nullable Map c) { + if (c == null || c.size() == 0) { + throw new AssertionException("Map should not be empty"); + } + } - public static void same(Object expected, Object actual) { - if (expected != actual) { - throw new AssertionException("Objects should be the same"); - } - } + public static void same(Object expected, Object actual) { + if (expected != actual) { + throw new AssertionException("Objects should be the same"); + } + } - public static void isEmpty(@Nullable Collection c) { - if (c != null && !c.isEmpty()) { - throw new AssertionException("Collection should be empty"); - } - } + public static void isEmpty(@Nullable Collection c) { + if (c != null && !c.isEmpty()) { + throw new AssertionException("Collection should be empty"); + } + } - public static void shouldNotHappen() { - throw new AssertionException("Should not happen"); - } + public static void shouldNotHappen() { + throw new AssertionException("Should not happen"); + } - private static final class AssertionException extends RuntimeException { - private AssertionException(@Nonnull String message) { - super(message); - } - } + private static final class AssertionException extends RuntimeException { + private AssertionException(@Nonnull String message) { + super(message); + } + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/ActivityUi.java b/android-app/src/main/java/org/solovyev/android/calculator/ActivityUi.java index 778a2d7c..bf8920c4 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/ActivityUi.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/ActivityUi.java @@ -50,319 +50,319 @@ import javax.annotation.Nullable; public class ActivityUi extends BaseUi { - private int layoutId; + private int layoutId; - @Nonnull - private Preferences.Gui.Theme theme = Preferences.Gui.Theme.material_theme; + @Nonnull + private Preferences.Gui.Theme theme = Preferences.Gui.Theme.material_theme; - @Nonnull - private Preferences.Gui.Layout layout = Preferences.Gui.Layout.main_calculator; + @Nonnull + private Preferences.Gui.Layout layout = Preferences.Gui.Layout.main_calculator; - @Nonnull - private Language language = Languages.SYSTEM_LANGUAGE; + @Nonnull + private Language language = Languages.SYSTEM_LANGUAGE; - private int selectedNavigationIndex = 0; + private int selectedNavigationIndex = 0; - public ActivityUi(@LayoutRes int layoutId, @Nonnull String logTag) { - super(logTag); - this.layoutId = layoutId; - } + public ActivityUi(@LayoutRes int layoutId, @Nonnull String logTag) { + super(logTag); + this.layoutId = layoutId; + } - public void setLayoutId(int layoutId) { - this.layoutId = layoutId; - } + public static boolean restartIfThemeChanged(@Nonnull Activity activity, @Nonnull Preferences.Gui.Theme oldTheme) { + final Preferences.Gui.Theme newTheme = Preferences.Gui.theme.getPreference(App.getPreferences()); + final int themeId = oldTheme.getThemeId(activity); + final int newThemeId = newTheme.getThemeId(activity); + if (themeId != newThemeId) { + Activities.restartActivity(activity); + return true; + } + return false; + } - public void onPreCreate(@Nonnull Activity activity) { - final SharedPreferences preferences = App.getPreferences(); + public static boolean restartIfLanguageChanged(@Nonnull Activity activity, @Nonnull Language oldLanguage) { + final Language current = App.getLanguages().getCurrent(); + if (!current.equals(oldLanguage)) { + Activities.restartActivity(activity); + return true; + } + return false; + } - theme = Preferences.Gui.getTheme(preferences); - activity.setTheme(theme.getThemeId(activity)); + public static void reportActivityStop(@Nonnull Activity activity) { + App.getGa().getAnalytics().reportActivityStop(activity); + } - layout = Preferences.Gui.getLayout(preferences); - language = App.getLanguages().getCurrent(); - } + public static void reportActivityStart(@Nonnull Activity activity) { + App.getGa().getAnalytics().reportActivityStart(activity); + } - @Override - public void onCreate(@Nonnull Activity activity) { - super.onCreate(activity); - App.getLanguages().updateLanguage(activity, false); + public void onPreCreate(@Nonnull Activity activity) { + final SharedPreferences preferences = App.getPreferences(); - if (activity instanceof CalculatorEventListener) { - Locator.getInstance().getCalculator().addCalculatorEventListener((CalculatorEventListener) activity); - } + theme = Preferences.Gui.getTheme(preferences); + activity.setTheme(theme.getThemeId(activity)); - activity.setContentView(layoutId); + layout = Preferences.Gui.getLayout(preferences); + language = App.getLanguages().getCurrent(); + } - final View root = activity.findViewById(R.id.main_layout); - if (root != null) { - processButtons(activity, root); - fixFonts(root); - addHelpInfo(activity, root); - } - } + @Override + public void onCreate(@Nonnull Activity activity) { + super.onCreate(activity); + App.getLanguages().updateLanguage(activity, false); - public void onCreate(@Nonnull final ActionBarActivity activity) { - onCreate((Activity) activity); - final ActionBar actionBar = activity.getSupportActionBar(); - if (actionBar != null) { - initActionBar(activity, actionBar); - } - } + if (activity instanceof CalculatorEventListener) { + Locator.getInstance().getCalculator().addCalculatorEventListener((CalculatorEventListener) activity); + } - private void initActionBar(@Nonnull Activity activity, @Nonnull ActionBar actionBar) { - actionBar.setDisplayUseLogoEnabled(false); - final boolean homeAsUp = !(activity instanceof CalculatorActivity); - actionBar.setDisplayHomeAsUpEnabled(homeAsUp); - actionBar.setHomeButtonEnabled(false); - actionBar.setDisplayShowHomeEnabled(true); - actionBar.setElevation(0); + activity.setContentView(layoutId); - toggleTitle(activity, actionBar, true); + final View root = activity.findViewById(R.id.main_layout); + if (root != null) { + processButtons(activity, root); + fixFonts(root); + addHelpInfo(activity, root); + } + } - if (!homeAsUp) { - actionBar.setIcon(R.drawable.ab_logo); - } - actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); - } + public void onCreate(@Nonnull final ActionBarActivity activity) { + onCreate((Activity) activity); + final ActionBar actionBar = activity.getSupportActionBar(); + if (actionBar != null) { + initActionBar(activity, actionBar); + } + } - private void toggleTitle(@Nonnull Activity activity, @Nonnull ActionBar actionBar, boolean showTitle) { - if (activity instanceof CalculatorActivity) { - if (Views.getScreenOrientation(activity) == Configuration.ORIENTATION_PORTRAIT) { - actionBar.setDisplayShowTitleEnabled(true); - } else { - actionBar.setDisplayShowTitleEnabled(false); - } - } else { - actionBar.setDisplayShowTitleEnabled(showTitle); - } - } + private void initActionBar(@Nonnull Activity activity, @Nonnull ActionBar actionBar) { + actionBar.setDisplayUseLogoEnabled(false); + final boolean homeAsUp = !(activity instanceof CalculatorActivity); + actionBar.setDisplayHomeAsUpEnabled(homeAsUp); + actionBar.setHomeButtonEnabled(false); + actionBar.setDisplayShowHomeEnabled(true); + actionBar.setElevation(0); - public void restoreSavedTab(@Nonnull ActionBarActivity activity) { - final ActionBar actionBar = activity.getSupportActionBar(); - if (actionBar != null) { - if (selectedNavigationIndex >= 0 && selectedNavigationIndex < actionBar.getTabCount()) { - actionBar.setSelectedNavigationItem(selectedNavigationIndex); - } - } - } + toggleTitle(activity, actionBar, true); - public void onSaveInstanceState(@Nonnull ActionBarActivity activity, @Nonnull Bundle outState) { - onSaveInstanceState((Activity) activity, outState); - } + if (!homeAsUp) { + actionBar.setIcon(R.drawable.ab_logo); + } + actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); + } - public void onSaveInstanceState(@Nonnull Activity activity, @Nonnull Bundle outState) { - } + private void toggleTitle(@Nonnull Activity activity, @Nonnull ActionBar actionBar, boolean 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 onResume(@Nonnull Activity activity) { - if (!restartIfThemeChanged(activity, theme)) { - restartIfLanguageChanged(activity, language); - } - } + public void restoreSavedTab(@Nonnull ActionBarActivity activity) { + final ActionBar actionBar = activity.getSupportActionBar(); + if (actionBar != null) { + if (selectedNavigationIndex >= 0 && selectedNavigationIndex < actionBar.getTabCount()) { + actionBar.setSelectedNavigationItem(selectedNavigationIndex); + } + } + } - public static boolean restartIfThemeChanged(@Nonnull Activity activity, @Nonnull Preferences.Gui.Theme oldTheme) { - final Preferences.Gui.Theme newTheme = Preferences.Gui.theme.getPreference(App.getPreferences()); - final int themeId = oldTheme.getThemeId(activity); - final int newThemeId = newTheme.getThemeId(activity); - if (themeId != newThemeId) { - Activities.restartActivity(activity); - return true; - } - return false; - } + public void onSaveInstanceState(@Nonnull ActionBarActivity activity, @Nonnull Bundle outState) { + onSaveInstanceState((Activity) activity, outState); + } - public static boolean restartIfLanguageChanged(@Nonnull Activity activity, @Nonnull Language oldLanguage) { - final Language current = App.getLanguages().getCurrent(); - if (!current.equals(oldLanguage)) { - Activities.restartActivity(activity); - return true; - } - return false; - } + public void onSaveInstanceState(@Nonnull Activity activity, @Nonnull Bundle outState) { + } - public void onPause(@Nonnull Activity activity) { - } + public void onResume(@Nonnull Activity activity) { + if (!restartIfThemeChanged(activity, theme)) { + restartIfLanguageChanged(activity, language); + } + } - public void onPause(@Nonnull ActionBarActivity activity) { - onPause((Activity) activity); + public void onPause(@Nonnull Activity activity) { + } - final ActionBar actionBar = activity.getSupportActionBar(); - if (actionBar != null) { - final int selectedNavigationIndex = actionBar.getSelectedNavigationIndex(); - if (selectedNavigationIndex >= 0) { - final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity); - final SharedPreferences.Editor editor = preferences.edit(); - editor.putInt(getSavedTabPreferenceName(activity), selectedNavigationIndex); - editor.apply(); - } - } - } + public void onPause(@Nonnull ActionBarActivity activity) { + onPause((Activity) activity); - @Nonnull - private String getSavedTabPreferenceName(@Nonnull Activity activity) { - return "tab_" + activity.getClass().getSimpleName(); - } + final ActionBar actionBar = activity.getSupportActionBar(); + if (actionBar != null) { + final int selectedNavigationIndex = actionBar.getSelectedNavigationIndex(); + if (selectedNavigationIndex >= 0) { + final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity); + final SharedPreferences.Editor editor = preferences.edit(); + editor.putInt(getSavedTabPreferenceName(activity), selectedNavigationIndex); + editor.apply(); + } + } + } - @Override - public void onDestroy(@Nonnull Activity activity) { - super.onDestroy(activity); + @Nonnull + private String getSavedTabPreferenceName(@Nonnull Activity activity) { + return "tab_" + activity.getClass().getSimpleName(); + } - if (activity instanceof CalculatorEventListener) { - Locator.getInstance().getCalculator().removeCalculatorEventListener((CalculatorEventListener) activity); - } - } + @Override + public void onDestroy(@Nonnull Activity activity) { + super.onDestroy(activity); - public void onDestroy(@Nonnull ActionBarActivity activity) { - this.onDestroy((Activity) activity); - } + if (activity instanceof CalculatorEventListener) { + Locator.getInstance().getCalculator().removeCalculatorEventListener((CalculatorEventListener) activity); + } + } - public void addTab(@Nonnull ActionBarActivity activity, - @Nonnull String tag, - @Nonnull Class fragmentClass, - @Nullable Bundle fragmentArgs, - int captionResId, - int parentViewId) { - final ActionBar actionBar = activity.getSupportActionBar(); + public void onDestroy(@Nonnull ActionBarActivity activity) { + this.onDestroy((Activity) activity); + } - final ActionBar.Tab tab = actionBar.newTab(); - tab.setTag(tag); - tab.setText(captionResId); + public void addTab(@Nonnull ActionBarActivity activity, + @Nonnull String tag, + @Nonnull Class fragmentClass, + @Nullable Bundle fragmentArgs, + int captionResId, + int parentViewId) { + final ActionBar actionBar = activity.getSupportActionBar(); - final ActionBarFragmentTabListener listener = new ActionBarFragmentTabListener(activity, tag, fragmentClass, fragmentArgs, parentViewId); - tab.setTabListener(listener); - actionBar.addTab(tab); - } + final ActionBar.Tab tab = actionBar.newTab(); + tab.setTag(tag); + tab.setText(captionResId); - public void addTab(@Nonnull ActionBarActivity activity, @Nonnull CalculatorFragmentType fragmentType, @Nullable Bundle fragmentArgs, int parentViewId) { - addTab(activity, fragmentType.getFragmentTag(), fragmentType.getFragmentClass(), fragmentArgs, fragmentType.getDefaultTitleResId(), parentViewId); - } + final ActionBarFragmentTabListener listener = new ActionBarFragmentTabListener(activity, tag, fragmentClass, fragmentArgs, parentViewId); + tab.setTabListener(listener); + actionBar.addTab(tab); + } - public void setFragment(@Nonnull ActionBarActivity activity, @Nonnull CalculatorFragmentType fragmentType, @Nullable Bundle fragmentArgs, int parentViewId) { - final FragmentManager fm = activity.getSupportFragmentManager(); + public void addTab(@Nonnull ActionBarActivity activity, @Nonnull CalculatorFragmentType fragmentType, @Nullable Bundle fragmentArgs, int parentViewId) { + addTab(activity, fragmentType.getFragmentTag(), fragmentType.getFragmentClass(), fragmentArgs, fragmentType.getDefaultTitleResId(), parentViewId); + } - 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(); - } + public void setFragment(@Nonnull ActionBarActivity activity, @Nonnull 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(); + } - public void selectTab(@Nonnull ActionBarActivity activity, @Nonnull 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 && fragmentType.getFragmentTag().equals(tab.getTag())) { - actionBar.setSelectedNavigationItem(i); - break; - } - } - } + } + } - public int getLayoutId() { - return layoutId; - } + public void selectTab(@Nonnull ActionBarActivity activity, @Nonnull 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 && fragmentType.getFragmentTag().equals(tab.getTag())) { + actionBar.setSelectedNavigationItem(i); + break; + } + } + } - @Nonnull - public Preferences.Gui.Theme getTheme() { - return theme; - } + public int getLayoutId() { + return layoutId; + } - @Nonnull - public Language getLanguage() { - return language; - } + public void setLayoutId(int layoutId) { + this.layoutId = layoutId; + } - @Nonnull - public Preferences.Gui.Layout getLayout() { - return layout; - } + @Nonnull + public Preferences.Gui.Theme getTheme() { + return theme; + } - public void onResume(@Nonnull ActionBarActivity activity) { - onResume((Activity) activity); + @Nonnull + public Language getLanguage() { + return language; + } - final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity); - selectedNavigationIndex = preferences.getInt(getSavedTabPreferenceName(activity), -1); - restoreSavedTab(activity); - } + @Nonnull + public Preferences.Gui.Layout getLayout() { + return layout; + } - private void addHelpInfo(@Nonnull Activity activity, @Nonnull View root) { - if (CalculatorApplication.isMonkeyRunner(activity)) { - if (root instanceof ViewGroup) { - final TextView helperTextView = new TextView(activity); + public void onResume(@Nonnull ActionBarActivity activity) { + onResume((Activity) activity); - final DisplayMetrics dm = new DisplayMetrics(); - activity.getWindowManager().getDefaultDisplay().getMetrics(dm); + final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity); + selectedNavigationIndex = preferences.getInt(getSavedTabPreferenceName(activity), -1); + restoreSavedTab(activity); + } - helperTextView.setTextSize(15); - helperTextView.setTextColor(Color.WHITE); + private void addHelpInfo(@Nonnull Activity activity, @Nonnull View root) { + if (CalculatorApplication.isMonkeyRunner(activity)) { + if (root instanceof ViewGroup) { + final TextView helperTextView = new TextView(activity); - final Configuration c = activity.getResources().getConfiguration(); + final DisplayMetrics dm = new DisplayMetrics(); + activity.getWindowManager().getDefaultDisplay().getMetrics(dm); - 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"); - } + helperTextView.setTextSize(15); + helperTextView.setTextColor(Color.WHITE); - helpText.append(" (").append(dm.widthPixels).append("x").append(dm.heightPixels).append(")"); + final Configuration c = activity.getResources().getConfiguration(); - 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; - } + 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.densityDpi).append(")"); + helpText.append(" (").append(dm.widthPixels).append("x").append(dm.heightPixels).append(")"); - helperTextView.setText(helpText); + 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; + } - ((ViewGroup) root).addView(helperTextView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); - } - } - } + helpText.append(" (").append(dm.densityDpi).append(")"); - public void onStop(@Nonnull Activity activity) { - reportActivityStop(activity); - } + helperTextView.setText(helpText); - public static void reportActivityStop(@Nonnull Activity activity) { - App.getGa().getAnalytics().reportActivityStop(activity); - } + ((ViewGroup) root).addView(helperTextView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)); + } + } + } - public void onStart(@Nonnull Activity activity) { - reportActivityStart(activity); - } + public void onStop(@Nonnull Activity activity) { + reportActivityStop(activity); + } - public static void reportActivityStart(@Nonnull Activity activity) { - App.getGa().getAnalytics().reportActivityStart(activity); - } + public void onStart(@Nonnull Activity activity) { + reportActivityStart(activity); + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/AdView.java b/android-app/src/main/java/org/solovyev/android/calculator/AdView.java index 4b7732d5..82d6a893 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/AdView.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/AdView.java @@ -16,118 +16,118 @@ import javax.annotation.Nullable; public class AdView extends FrameLayout { - @Nullable - private com.google.android.gms.ads.AdView admobView; - @Nullable - private AdView.AdViewListener admobListener; + @Nullable + private com.google.android.gms.ads.AdView admobView; + @Nullable + private AdView.AdViewListener admobListener; - public AdView(Context context) { - super(context); - } + public AdView(Context context) { + super(context); + } - public AdView(Context context, AttributeSet attrs) { - super(context, attrs); - } + public AdView(Context context, AttributeSet attrs) { + super(context, attrs); + } - public AdView(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - } + public AdView(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + } - public void destroy() { - destroyAdmobView(); - } + public void destroy() { + destroyAdmobView(); + } - private void destroyAdmobView() { - if (admobView != null) { - admobView.destroy(); - admobView.setAdListener(null); - admobView = null; - } - if(admobListener != null) { - admobListener.destroy(); - admobListener = null; - } - } + private void destroyAdmobView() { + if (admobView != null) { + admobView.destroy(); + admobView.setAdListener(null); + admobView = null; + } + if (admobListener != null) { + admobListener.destroy(); + admobListener = null; + } + } - public void pause() { - if (admobView != null) { - admobView.pause(); - } - } + public void pause() { + if (admobView != null) { + admobView.pause(); + } + } - public void resume() { - if (admobView != null) { - admobView.resume(); - } - } + public void resume() { + if (admobView != null) { + admobView.resume(); + } + } - public void show() { - if (admobView != null) { - return; - } + public void show() { + if (admobView != null) { + return; + } - LayoutInflater.from(getContext()).inflate(R.layout.admob, this); - admobView = (com.google.android.gms.ads.AdView) findViewById(R.id.admob); - Check.isNotNull(admobView); - if (admobView == null) { - return; - } + LayoutInflater.from(getContext()).inflate(R.layout.admob, this); + admobView = (com.google.android.gms.ads.AdView) findViewById(R.id.admob); + Check.isNotNull(admobView); + if (admobView == null) { + return; + } - admobListener = new AdView.AdViewListener(this); - admobView.setAdListener(admobListener); + admobListener = new AdView.AdViewListener(this); + admobView.setAdListener(admobListener); - final AdRequest.Builder b = new AdRequest.Builder(); - b.addTestDevice(AdRequest.DEVICE_ID_EMULATOR); - if (BuildConfig.DEBUG) { - // LG Nexus 5 - b.addTestDevice("B80E676D60CE6FDBE1B84A55464E3FE1"); - } - admobView.loadAd(b.build()); - } + final AdRequest.Builder b = new AdRequest.Builder(); + b.addTestDevice(AdRequest.DEVICE_ID_EMULATOR); + if (BuildConfig.DEBUG) { + // LG Nexus 5 + b.addTestDevice("B80E676D60CE6FDBE1B84A55464E3FE1"); + } + admobView.loadAd(b.build()); + } - public void hide() { - if(admobView == null) { - return; - } + public void hide() { + if (admobView == null) { + return; + } - setVisibility(GONE); + setVisibility(GONE); - admobView.setVisibility(View.GONE); - admobView.pause(); - destroyAdmobView(); - } + admobView.setVisibility(View.GONE); + admobView.pause(); + destroyAdmobView(); + } - private static class AdViewListener extends AdListener { + private static class AdViewListener extends AdListener { - @Nullable - private AdView adView; + @Nullable + private AdView adView; - public AdViewListener(@Nonnull AdView adView) { - this.adView = adView; - } + public AdViewListener(@Nonnull AdView adView) { + this.adView = adView; + } - void destroy() { - adView = null; - } + void destroy() { + adView = null; + } - @Override - public void onAdFailedToLoad(int errorCode) { - if (adView != null) { - adView.hide(); - adView = null; - } - } + @Override + public void onAdFailedToLoad(int errorCode) { + if (adView != null) { + adView.hide(); + adView = null; + } + } - @Override - public void onAdLoaded() { - if (adView != null) { - final com.google.android.gms.ads.AdView admobView = adView.admobView; - if (admobView != null) { - admobView.setVisibility(View.VISIBLE); - } - adView.setVisibility(VISIBLE); - adView = null; - } - } - } + @Override + public void onAdLoaded() { + if (adView != null) { + final com.google.android.gms.ads.AdView admobView = adView.admobView; + if (admobView != null) { + admobView.setVisibility(View.VISIBLE); + } + adView.setVisibility(VISIBLE); + adView = null; + } + } + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/AndroidCalculator.java b/android-app/src/main/java/org/solovyev/android/calculator/AndroidCalculator.java index b5a0ecba..d293e0f0 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/AndroidCalculator.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/AndroidCalculator.java @@ -46,192 +46,192 @@ import jscl.math.Generic; */ public class AndroidCalculator implements Calculator, CalculatorEventListener, SharedPreferences.OnSharedPreferenceChangeListener { - @Nonnull - private final CalculatorImpl calculator = new CalculatorImpl(); + @Nonnull + private final CalculatorImpl calculator = new CalculatorImpl(); - @Nonnull - private final Application context; + @Nonnull + private final Application context; - public AndroidCalculator(@Nonnull Application application) { - this.context = application; - this.calculator.addCalculatorEventListener(this); + public AndroidCalculator(@Nonnull Application application) { + this.context = application; + this.calculator.addCalculatorEventListener(this); - PreferenceManager.getDefaultSharedPreferences(application).registerOnSharedPreferenceChangeListener(this); - } + PreferenceManager.getDefaultSharedPreferences(application).registerOnSharedPreferenceChangeListener(this); + } /* - ********************************************************************** + ********************************************************************** * * DELEGATED TO CALCULATOR * ********************************************************************** */ - @Override - @Nonnull - public CalculatorEventData evaluate(@Nonnull JsclOperation operation, @Nonnull String expression) { - return calculator.evaluate(operation, expression); - } + @Override + @Nonnull + public CalculatorEventData evaluate(@Nonnull JsclOperation operation, @Nonnull String expression) { + return calculator.evaluate(operation, expression); + } - @Override - @Nonnull - public CalculatorEventData evaluate(@Nonnull JsclOperation operation, @Nonnull String expression, @Nonnull Long sequenceId) { - return calculator.evaluate(operation, expression, sequenceId); - } + @Override + @Nonnull + public CalculatorEventData evaluate(@Nonnull JsclOperation operation, @Nonnull String expression, @Nonnull Long sequenceId) { + return calculator.evaluate(operation, expression, sequenceId); + } - @Override - public void setCalculateOnFly(boolean calculateOnFly) { - calculator.setCalculateOnFly(calculateOnFly); - } + @Override + public boolean isCalculateOnFly() { + return calculator.isCalculateOnFly(); + } - @Override - public boolean isCalculateOnFly() { - return calculator.isCalculateOnFly(); - } + @Override + public void setCalculateOnFly(boolean calculateOnFly) { + calculator.setCalculateOnFly(calculateOnFly); + } - @Override - public boolean isConversionPossible(@Nonnull Generic generic, @Nonnull NumeralBase from, @Nonnull NumeralBase to) { - return calculator.isConversionPossible(generic, from, to); - } + @Override + public boolean isConversionPossible(@Nonnull Generic generic, @Nonnull NumeralBase from, @Nonnull NumeralBase to) { + return calculator.isConversionPossible(generic, from, to); + } - @Override - @Nonnull - public CalculatorEventData convert(@Nonnull Generic generic, @Nonnull NumeralBase to) { - return calculator.convert(generic, to); - } + @Override + @Nonnull + public CalculatorEventData convert(@Nonnull Generic generic, @Nonnull NumeralBase to) { + return calculator.convert(generic, to); + } - @Override - @Nonnull - public CalculatorEventData fireCalculatorEvent(@Nonnull CalculatorEventType calculatorEventType, @Nullable Object data) { - return calculator.fireCalculatorEvent(calculatorEventType, data); - } + @Override + @Nonnull + public CalculatorEventData fireCalculatorEvent(@Nonnull CalculatorEventType calculatorEventType, @Nullable Object data) { + return calculator.fireCalculatorEvent(calculatorEventType, data); + } - @Nonnull - @Override - public CalculatorEventData fireCalculatorEvent(@Nonnull CalculatorEventType calculatorEventType, @Nullable Object data, @Nonnull Object source) { - return calculator.fireCalculatorEvent(calculatorEventType, data, source); - } + @Nonnull + @Override + public CalculatorEventData fireCalculatorEvent(@Nonnull CalculatorEventType calculatorEventType, @Nullable Object data, @Nonnull Object source) { + return calculator.fireCalculatorEvent(calculatorEventType, data, source); + } - @Override - @Nonnull - public CalculatorEventData fireCalculatorEvent(@Nonnull CalculatorEventType calculatorEventType, @Nullable Object data, @Nonnull Long sequenceId) { - return calculator.fireCalculatorEvent(calculatorEventType, data, sequenceId); - } + @Override + @Nonnull + public CalculatorEventData fireCalculatorEvent(@Nonnull CalculatorEventType calculatorEventType, @Nullable Object data, @Nonnull Long sequenceId) { + return calculator.fireCalculatorEvent(calculatorEventType, data, sequenceId); + } - @Nonnull - @Override - public PreparedExpression prepareExpression(@Nonnull String expression) throws CalculatorParseException { - return calculator.prepareExpression(expression); - } + @Nonnull + @Override + public PreparedExpression prepareExpression(@Nonnull String expression) throws CalculatorParseException { + return calculator.prepareExpression(expression); + } - @Override - public void init() { - this.calculator.init(); + @Override + public void init() { + this.calculator.init(); - final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); - this.calculator.setCalculateOnFly(Preferences.Calculations.calculateOnFly.getPreference(prefs)); - } + final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); + this.calculator.setCalculateOnFly(Preferences.Calculations.calculateOnFly.getPreference(prefs)); + } - @Override - public void addCalculatorEventListener(@Nonnull CalculatorEventListener calculatorEventListener) { - calculator.addCalculatorEventListener(calculatorEventListener); - } + @Override + public void addCalculatorEventListener(@Nonnull CalculatorEventListener calculatorEventListener) { + calculator.addCalculatorEventListener(calculatorEventListener); + } - @Override - public void removeCalculatorEventListener(@Nonnull CalculatorEventListener calculatorEventListener) { - calculator.removeCalculatorEventListener(calculatorEventListener); - } + @Override + public void removeCalculatorEventListener(@Nonnull CalculatorEventListener calculatorEventListener) { + calculator.removeCalculatorEventListener(calculatorEventListener); + } - @Override - public void fireCalculatorEvent(@Nonnull CalculatorEventData calculatorEventData, @Nonnull CalculatorEventType calculatorEventType, @Nullable Object data) { - calculator.fireCalculatorEvent(calculatorEventData, calculatorEventType, data); - } + @Override + public void fireCalculatorEvent(@Nonnull CalculatorEventData calculatorEventData, @Nonnull CalculatorEventType calculatorEventType, @Nullable Object data) { + calculator.fireCalculatorEvent(calculatorEventData, calculatorEventType, data); + } - @Override - public void fireCalculatorEvents(@Nonnull List calculatorEvents) { - calculator.fireCalculatorEvents(calculatorEvents); - } + @Override + public void fireCalculatorEvents(@Nonnull List calculatorEvents) { + calculator.fireCalculatorEvents(calculatorEvents); + } - @Override - public void doHistoryAction(@Nonnull HistoryAction historyAction) { - calculator.doHistoryAction(historyAction); - } + @Override + public void doHistoryAction(@Nonnull HistoryAction historyAction) { + calculator.doHistoryAction(historyAction); + } - @Override - public void setCurrentHistoryState(@Nonnull CalculatorHistoryState editorHistoryState) { - calculator.setCurrentHistoryState(editorHistoryState); - } + @Override + @Nonnull + public CalculatorHistoryState getCurrentHistoryState() { + return calculator.getCurrentHistoryState(); + } - @Override - @Nonnull - public CalculatorHistoryState getCurrentHistoryState() { - return calculator.getCurrentHistoryState(); - } + @Override + public void setCurrentHistoryState(@Nonnull CalculatorHistoryState editorHistoryState) { + calculator.setCurrentHistoryState(editorHistoryState); + } - @Override - public void evaluate() { - calculator.evaluate(); - } + @Override + public void evaluate() { + calculator.evaluate(); + } - @Override - public void evaluate(@Nonnull Long sequenceId) { - calculator.evaluate(sequenceId); - } + @Override + public void evaluate(@Nonnull Long sequenceId) { + calculator.evaluate(sequenceId); + } - @Override - public void simplify() { - calculator.simplify(); - } + @Override + public void simplify() { + calculator.simplify(); + } - @Override - public void onCalculatorEvent(@Nonnull CalculatorEventData calculatorEventData, @Nonnull CalculatorEventType calculatorEventType, @Nullable Object data) { - switch (calculatorEventType) { - case calculation_messages: - CalculatorActivityLauncher.showCalculationMessagesDialog(CalculatorApplication.getInstance(), (List) 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(@Nonnull CalculatorEventData calculatorEventData, @Nonnull CalculatorEventType calculatorEventType, @Nullable Object data) { + switch (calculatorEventType) { + case calculation_messages: + CalculatorActivityLauncher.showCalculationMessagesDialog(CalculatorApplication.getInstance(), (List) 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(@Nonnull SharedPreferences prefs, @Nonnull String key) { - if (Preferences.Calculations.calculateOnFly.getKey().equals(key)) { - this.calculator.setCalculateOnFly(Preferences.Calculations.calculateOnFly.getPreference(prefs)); - } - } + @Override + public void onSharedPreferenceChanged(@Nonnull SharedPreferences prefs, @Nonnull String key) { + if (Preferences.Calculations.calculateOnFly.getKey().equals(key)) { + this.calculator.setCalculateOnFly(Preferences.Calculations.calculateOnFly.getPreference(prefs)); + } + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/AndroidCalculatorClipboard.java b/android-app/src/main/java/org/solovyev/android/calculator/AndroidCalculatorClipboard.java index e32ef9ae..dce12137 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/AndroidCalculatorClipboard.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/AndroidCalculatorClipboard.java @@ -35,32 +35,32 @@ import javax.annotation.Nonnull; */ public class AndroidCalculatorClipboard implements CalculatorClipboard { - @Nonnull - private final Context context; + @Nonnull + private final Context context; - public AndroidCalculatorClipboard(@Nonnull Application application) { - this.context = application; - } + public AndroidCalculatorClipboard(@Nonnull 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(@Nonnull String text) { - final ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); - clipboard.setText(text); - } + @Override + public void setText(@Nonnull CharSequence text) { + final ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); + clipboard.setText(text); + } - @Override - public void setText(@Nonnull CharSequence text) { - final ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); - clipboard.setText(text); - } + @Override + public void setText(@Nonnull String text) { + final ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); + clipboard.setText(text); + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/AndroidCalculatorDisplayView.java b/android-app/src/main/java/org/solovyev/android/calculator/AndroidCalculatorDisplayView.java index 9ea187e1..1418783b 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/AndroidCalculatorDisplayView.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/AndroidCalculatorDisplayView.java @@ -47,15 +47,15 @@ import javax.annotation.Nullable; public class AndroidCalculatorDisplayView extends AutoResizeTextView implements CalculatorDisplayView { /* - ********************************************************************** + ********************************************************************** * * STATIC FIELDS * ********************************************************************** */ - @Nonnull - private final TextProcessor textHighlighter; + @Nonnull + private final TextProcessor textHighlighter; /* ********************************************************************** @@ -64,17 +64,13 @@ public class AndroidCalculatorDisplayView extends AutoResizeTextView implements * ********************************************************************** */ - - @Nonnull - private volatile CalculatorDisplayViewState state = CalculatorDisplayViewStateImpl.newDefaultInstance(); - - @Nonnull - private final Object lock = new Object(); - - @Nonnull - private final Handler uiHandler = new Handler(); - - private volatile boolean initialized = false; + @Nonnull + private final Object lock = new Object(); + @Nonnull + private final Handler uiHandler = new Handler(); + @Nonnull + private volatile CalculatorDisplayViewState state = CalculatorDisplayViewStateImpl.newDefaultInstance(); + private volatile boolean initialized = false; /* ********************************************************************** @@ -84,20 +80,20 @@ public class AndroidCalculatorDisplayView extends AutoResizeTextView implements ********************************************************************** */ - public AndroidCalculatorDisplayView(Context context) { - super(context); - textHighlighter = new TextHighlighter(getTextColors().getDefaultColor(), false); - } + public AndroidCalculatorDisplayView(Context context) { + super(context); + textHighlighter = new TextHighlighter(getTextColors().getDefaultColor(), false); + } - public AndroidCalculatorDisplayView(Context context, AttributeSet attrs) { - super(context, attrs); - textHighlighter = new TextHighlighter(getTextColors().getDefaultColor(), false); - } + public AndroidCalculatorDisplayView(Context context, AttributeSet attrs) { + super(context, attrs); + textHighlighter = new TextHighlighter(getTextColors().getDefaultColor(), false); + } - public AndroidCalculatorDisplayView(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - textHighlighter = new TextHighlighter(getTextColors().getDefaultColor(), false); - } + public AndroidCalculatorDisplayView(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + textHighlighter = new TextHighlighter(getTextColors().getDefaultColor(), false); + } /* ********************************************************************** @@ -107,100 +103,99 @@ public class AndroidCalculatorDisplayView extends AutoResizeTextView implements ********************************************************************** */ + private Preferences.Gui.TextColor getTextColor() { + final Context context = getContext(); + return App.getThemeIn(context).getTextColor(context); + } - @Override - public void setState(@Nonnull final CalculatorDisplayViewState state) { + @Nonnull + @Override + public CalculatorDisplayViewState getState() { + synchronized (lock) { + return this.state; + } + } - uiHandler.post(new Runnable() { - @Override - public void run() { + @Override + public void setState(@Nonnull final CalculatorDisplayViewState state) { - synchronized (lock) { + uiHandler.post(new Runnable() { + @Override + public void run() { - final CharSequence text = prepareText(state.getStringResult(), state.isValid()); + synchronized (lock) { - AndroidCalculatorDisplayView.this.state = state; - if (state.isValid()) { - setTextColor(getTextColor().normal); - setText(text); + final CharSequence text = prepareText(state.getStringResult(), state.isValid()); - adjustTextSize(); + AndroidCalculatorDisplayView.this.state = state; + if (state.isValid()) { + setTextColor(getTextColor().normal); + setText(text); - } else { - // update text in order to get rid of HTML tags - setText(getText().toString()); - setTextColor(getTextColor().error); + adjustTextSize(); - // error messages are never shown -> just greyed out text (error message will be shown on click) - //setText(state.getErrorMessage()); - //redraw(); - } - } - } - }); - } + } else { + // update text in order to get rid of HTML tags + setText(getText().toString()); + setTextColor(getTextColor().error); - private Preferences.Gui.TextColor getTextColor() { - final Context context = getContext(); - return App.getThemeIn(context).getTextColor(context); - } + // error messages are never shown -> just greyed out text (error message will be shown on click) + //setText(state.getErrorMessage()); + //redraw(); + } + } + } + }); + } - @Nonnull - @Override - public CalculatorDisplayViewState getState() { - synchronized (lock) { - return this.state; - } - } + @Nullable + private CharSequence prepareText(@Nullable String text, boolean valid) { + CharSequence result; - @Nullable - private CharSequence prepareText(@Nullable String text, boolean valid) { - CharSequence result; + if (valid && text != null) { + try { + final TextProcessorEditorResult processedText = textHighlighter.process(text); + text = processedText.toString(); + result = Html.fromHtml(text); + } catch (CalculatorParseException e) { + result = text; + } + } else { + result = text; + } - if (valid && text != null) { - try { - final TextProcessorEditorResult processedText = textHighlighter.process(text); - text = processedText.toString(); - result = Html.fromHtml(text); - } catch (CalculatorParseException e) { - result = text; - } - } else { - result = text; - } + return result; + } - return result; - } + private void adjustTextSize() { + // todo serso: think where to move it (keep in mind org.solovyev.android.view.AutoResizeTextView.resetTextSize()) + setAddEllipsis(false); + setMinTextSize(10); + resizeText(); + } - private void adjustTextSize() { - // todo serso: think where to move it (keep in mind org.solovyev.android.view.AutoResizeTextView.resetTextSize()) - setAddEllipsis(false); - setMinTextSize(10); - resizeText(); - } + public synchronized void init(@Nonnull Context context) { + this.init(context, true); + } - public synchronized void init(@Nonnull Context context) { - this.init(context, true); - } + public synchronized void init(@Nonnull Context context, boolean fromApp) { + if (!initialized) { + if (fromApp) { + final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); + final Preferences.Gui.Layout layout = Preferences.Gui.getLayout(preferences); - public synchronized void init(@Nonnull Context context, boolean fromApp) { - if (!initialized) { - if (fromApp) { - final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); - final Preferences.Gui.Layout layout = Preferences.Gui.getLayout(preferences); + if (!layout.isOptimized()) { + setTextSize(TypedValue.COMPLEX_UNIT_SP, getResources().getDimension(R.dimen.cpp_display_text_size_mobile)); + } - if (!layout.isOptimized()) { - setTextSize(TypedValue.COMPLEX_UNIT_SP, getResources().getDimension(R.dimen.cpp_display_text_size_mobile)); - } + if (context instanceof FragmentActivity) { + this.setOnClickListener(new CalculatorDisplayOnClickListener((FragmentActivity) context)); + } else { + throw new IllegalArgumentException("Must be fragment activity, got " + context.getClass()); + } + } - if (context instanceof FragmentActivity) { - this.setOnClickListener(new CalculatorDisplayOnClickListener((FragmentActivity) context)); - } else { - throw new IllegalArgumentException("Must be fragment activity, got " + context.getClass()); - } - } - - this.initialized = true; - } - } + this.initialized = true; + } + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/AndroidCalculatorEditorView.java b/android-app/src/main/java/org/solovyev/android/calculator/AndroidCalculatorEditorView.java index da773462..ad5c345d 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/AndroidCalculatorEditorView.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/AndroidCalculatorEditorView.java @@ -43,140 +43,137 @@ import javax.annotation.Nonnull; */ public class AndroidCalculatorEditorView extends EditText implements CalculatorEditorView { - private volatile boolean initialized = false; + @Nonnull + private final Handler uiHandler = new Handler(); + private volatile boolean initialized = false; + @SuppressWarnings("UnusedDeclaration") + @Nonnull + private volatile CalculatorEditorViewState viewState = CalculatorEditorViewStateImpl.newDefaultInstance(); + private volatile boolean viewStateChange = false; - @SuppressWarnings("UnusedDeclaration") - @Nonnull - private volatile CalculatorEditorViewState viewState = CalculatorEditorViewStateImpl.newDefaultInstance(); + public AndroidCalculatorEditorView(Context context) { + super(context); + } - private volatile boolean viewStateChange = false; + public AndroidCalculatorEditorView(Context context, AttributeSet attrs) { + super(context, attrs); + } - @Nonnull - private final Handler uiHandler = new Handler(); + public AndroidCalculatorEditorView(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + } - public AndroidCalculatorEditorView(Context context) { - super(context); - } + @Override + public boolean onCheckIsTextEditor() { + // NOTE: code below can be used carefully and should not be copied without special intention + // The main purpose of code is to disable soft input (virtual keyboard) but leave all the TextEdit functionality, like cursor, scrolling, copy/paste menu etc - public AndroidCalculatorEditorView(Context context, AttributeSet attrs) { - super(context, attrs); - } + if (Build.VERSION.SDK_INT >= 11) { + // fix for missing cursor in android 3 and higher + try { + // IDEA: return false always except if method was called from TextView.isCursorVisible() method + for (StackTraceElement stackTraceElement : Collections.asList(Thread.currentThread().getStackTrace())) { + if ("isCursorVisible".equals(stackTraceElement.getMethodName())) { + return true; + } + } + } catch (RuntimeException e) { + // just in case... + } - public AndroidCalculatorEditorView(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - } + return false; + } else { + return false; + } + } - @Override - public boolean onCheckIsTextEditor() { - // NOTE: code below can be used carefully and should not be copied without special intention - // The main purpose of code is to disable soft input (virtual keyboard) but leave all the TextEdit functionality, like cursor, scrolling, copy/paste menu etc + @Override + protected void onCreateContextMenu(ContextMenu menu) { + super.onCreateContextMenu(menu); - if (Build.VERSION.SDK_INT >= 11) { - // fix for missing cursor in android 3 and higher - try { - // IDEA: return false always except if method was called from TextView.isCursorVisible() method - for (StackTraceElement stackTraceElement : Collections.asList(Thread.currentThread().getStackTrace())) { - if ("isCursorVisible".equals(stackTraceElement.getMethodName())) { - return true; - } - } - } catch (RuntimeException e) { - // just in case... - } + menu.removeItem(android.R.id.selectAll); + } - return false; - } else { - return false; - } - } + public void setHighlightText(boolean highlightText) { + //this.highlightText = highlightText; + Locator.getInstance().getEditor().updateViewState(); + } - @Override - protected void onCreateContextMenu(ContextMenu menu) { - super.onCreateContextMenu(menu); + public synchronized void init() { + if (!initialized) { + this.addTextChangedListener(new TextWatcherImpl()); - menu.removeItem(android.R.id.selectAll); - } + initialized = true; + } + } - public void setHighlightText(boolean highlightText) { - //this.highlightText = highlightText; - Locator.getInstance().getEditor().updateViewState(); - } + @Override + public void setState(@Nonnull final CalculatorEditorViewState viewState) { + synchronized (this) { - public synchronized void init() { - if (!initialized) { - this.addTextChangedListener(new TextWatcherImpl()); + uiHandler.post(new Runnable() { + @Override + public void run() { + final AndroidCalculatorEditorView editorView = AndroidCalculatorEditorView.this; + synchronized (AndroidCalculatorEditorView.this) { + try { + editorView.viewStateChange = true; + editorView.viewState = viewState; + if (App.getTheme().isLight() && getContext() instanceof CalculatorOnscreenService) { + // don't need formatting + editorView.setText(viewState.getText()); + } else { + editorView.setText(viewState.getTextAsCharSequence(), BufferType.EDITABLE); + } + final int selection = CalculatorEditorImpl.correctSelection(viewState.getSelection(), editorView.getText()); + editorView.setSelection(selection); + } finally { + editorView.viewStateChange = false; + } + } + } + }); + } + } - initialized = true; - } - } + @Override + protected void onSelectionChanged(int selStart, int selEnd) { + synchronized (this) { + if (initialized && !viewStateChange) { + // external text change => need to notify editor + super.onSelectionChanged(selStart, selEnd); - @Override - public void setState(@Nonnull final CalculatorEditorViewState viewState) { - synchronized (this) { + if (selStart == selEnd) { + // only if cursor moving, if selection do nothing + Locator.getInstance().getEditor().setSelection(selStart); + } + } + } + } - uiHandler.post(new Runnable() { - @Override - public void run() { - final AndroidCalculatorEditorView editorView = AndroidCalculatorEditorView.this; - synchronized (AndroidCalculatorEditorView.this) { - try { - editorView.viewStateChange = true; - editorView.viewState = viewState; - if (App.getTheme().isLight() && getContext() instanceof CalculatorOnscreenService) { - // don't need formatting - editorView.setText(viewState.getText()); - } else { - editorView.setText(viewState.getTextAsCharSequence(), BufferType.EDITABLE); - } - final int selection = CalculatorEditorImpl.correctSelection(viewState.getSelection(), editorView.getText()); - editorView.setSelection(selection); - } finally { - editorView.viewStateChange = false; - } - } - } - }); - } - } + public void handleTextChange(Editable s) { + synchronized (this) { + if (initialized && !viewStateChange) { + // external text change => need to notify editor + Locator.getInstance().getEditor().setText(String.valueOf(s)); + } + } + } - @Override - protected void onSelectionChanged(int selStart, int selEnd) { - synchronized (this) { - if (initialized && !viewStateChange) { - // external text change => need to notify editor - super.onSelectionChanged(selStart, selEnd); + private final class TextWatcherImpl implements TextWatcher { - if (selStart == selEnd) { - // only if cursor moving, if selection do nothing - Locator.getInstance().getEditor().setSelection(selStart); - } - } - } - } + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { - public void handleTextChange(Editable s) { - synchronized (this) { - if (initialized && !viewStateChange) { - // external text change => need to notify editor - Locator.getInstance().getEditor().setText(String.valueOf(s)); - } - } - } + } - private final class TextWatcherImpl implements TextWatcher { + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + } - @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - - } - - @Override - public void onTextChanged(CharSequence s, int start, int before, int count) { - } - - @Override - public void afterTextChanged(Editable s) { - handleTextChange(s); - } - } + @Override + public void afterTextChanged(Editable s) { + handleTextChange(s); + } + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/AndroidCalculatorKeyboard.java b/android-app/src/main/java/org/solovyev/android/calculator/AndroidCalculatorKeyboard.java index 7493ec63..943a6712 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/AndroidCalculatorKeyboard.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/AndroidCalculatorKeyboard.java @@ -22,13 +22,8 @@ package org.solovyev.android.calculator; -import android.app.Activity; import android.app.Application; import android.content.Context; -import android.content.SharedPreferences; -import android.os.Vibrator; -import android.preference.PreferenceManager; -import org.solovyev.android.view.VibratorContainer; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -40,71 +35,71 @@ import javax.annotation.Nullable; */ public class AndroidCalculatorKeyboard implements CalculatorKeyboard { - @Nonnull - private final CalculatorKeyboard calculatorKeyboard; + @Nonnull + private final CalculatorKeyboard calculatorKeyboard; - @Nonnull - private final Context context; + @Nonnull + private final Context context; - @android.support.annotation.Nullable - private org.solovyev.android.calculator.Vibrator vibrator; + @android.support.annotation.Nullable + private org.solovyev.android.calculator.Vibrator vibrator; - public AndroidCalculatorKeyboard(@Nonnull Application application, - @Nonnull CalculatorKeyboard calculatorKeyboard) { - this.context = application; - this.calculatorKeyboard = calculatorKeyboard; - } + public AndroidCalculatorKeyboard(@Nonnull Application application, + @Nonnull CalculatorKeyboard calculatorKeyboard) { + this.context = application; + this.calculatorKeyboard = calculatorKeyboard; + } - @Override - public boolean buttonPressed(@Nullable String text) { - App.getGa().onButtonPressed(text); - final boolean processed = calculatorKeyboard.buttonPressed(text); - if (processed) { - vibrate(); - } - return processed; - } + @Override + public boolean buttonPressed(@Nullable String text) { + App.getGa().onButtonPressed(text); + final boolean processed = calculatorKeyboard.buttonPressed(text); + if (processed) { + vibrate(); + } + return processed; + } - private void vibrate() { - if (vibrator == null) { - vibrator = App.getVibrator(); - } - vibrator.vibrate(); - } + private void vibrate() { + if (vibrator == null) { + vibrator = App.getVibrator(); + } + 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(); + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/AndroidCalculatorLogger.java b/android-app/src/main/java/org/solovyev/android/calculator/AndroidCalculatorLogger.java index 594e471a..22675a5b 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/AndroidCalculatorLogger.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/AndroidCalculatorLogger.java @@ -34,31 +34,31 @@ import javax.annotation.Nullable; */ public class AndroidCalculatorLogger implements CalculatorLogger { - @Nonnull - private static final String TAG = "Calculatorpp"; + @Nonnull + private static final String TAG = "Calculatorpp"; - @Override - public void debug(@Nullable String tag, @Nonnull String message) { - Log.d(getTag(tag), message); - } + @Override + public void debug(@Nullable String tag, @Nonnull String message) { + Log.d(getTag(tag), message); + } - @Nonnull - private String getTag(@Nullable String tag) { - return tag != null ? TAG + "/" + tag : TAG; - } + @Nonnull + private String getTag(@Nullable String tag) { + return tag != null ? TAG + "/" + tag : TAG; + } - @Override - public void debug(@Nullable String tag, @Nullable String message, @Nonnull Throwable e) { - Log.d(getTag(tag), message, e); - } + @Override + public void debug(@Nullable String tag, @Nullable String message, @Nonnull Throwable e) { + Log.d(getTag(tag), message, e); + } - @Override - public void error(@Nullable String tag, @Nullable String message, @Nonnull Throwable e) { - Log.e(getTag(tag), message, e); - } + @Override + public void error(@Nullable String tag, @Nullable String message, @Nonnull 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); + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/AndroidCalculatorNotifier.java b/android-app/src/main/java/org/solovyev/android/calculator/AndroidCalculatorNotifier.java index ba83fecb..c4a8b132 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/AndroidCalculatorNotifier.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/AndroidCalculatorNotifier.java @@ -25,14 +25,16 @@ package org.solovyev.android.calculator; import android.app.Application; import android.os.Handler; import android.widget.Toast; + import org.solovyev.android.Threads; import org.solovyev.android.msg.AndroidMessage; import org.solovyev.common.msg.Message; import org.solovyev.common.msg.MessageType; +import java.util.List; + import javax.annotation.Nonnull; import javax.annotation.Nullable; -import java.util.List; /** * User: serso @@ -41,58 +43,58 @@ import java.util.List; */ public class AndroidCalculatorNotifier implements CalculatorNotifier { - @Nonnull - private final Application application; + @Nonnull + private final Application application; - @Nonnull - private final Handler uiHandler = new Handler(); + @Nonnull + private final Handler uiHandler = new Handler(); - private final boolean showDebugMessages; + private final boolean showDebugMessages; - public AndroidCalculatorNotifier(@Nonnull Application application) { - this(application, false); - } + public AndroidCalculatorNotifier(@Nonnull Application application) { + this(application, false); + } - public AndroidCalculatorNotifier(@Nonnull Application application, boolean showDebugMessages) { - if (!Threads.isUiThread()) throw new AssertionError(); + public AndroidCalculatorNotifier(@Nonnull Application application, boolean showDebugMessages) { + if (!Threads.isUiThread()) throw new AssertionError(); - this.application = application; - this.showDebugMessages = showDebugMessages; - } + this.application = application; + this.showDebugMessages = showDebugMessages; + } - @Override - public void showMessage(@Nonnull Message message) { - showMessageInUiThread(message.getLocalizedMessage()); - } + @Override + public void showMessage(@Nonnull Message message) { + showMessageInUiThread(message.getLocalizedMessage()); + } - @Override - public void showMessage(@Nonnull Integer messageCode, @Nonnull MessageType messageType, @Nonnull List parameters) { - showMessage(new AndroidMessage(messageCode, messageType, application, parameters)); - } + @Override + public void showMessage(@Nonnull Integer messageCode, @Nonnull MessageType messageType, @Nonnull List parameters) { + showMessage(new AndroidMessage(messageCode, messageType, application, parameters)); + } - @Override - public void showMessage(@Nonnull Integer messageCode, @Nonnull MessageType messageType, @Nullable Object... parameters) { - showMessage(new AndroidMessage(messageCode, messageType, application, parameters)); - } + @Override + public void showMessage(@Nonnull Integer messageCode, @Nonnull MessageType messageType, @Nullable Object... parameters) { + showMessage(new AndroidMessage(messageCode, messageType, application, parameters)); + } - @Override - public void showDebugMessage(@Nullable final String tag, @Nonnull final String message) { - if (showDebugMessages) { - showMessageInUiThread(tag == null ? message : tag + ": " + message); - } - } + @Override + public void showDebugMessage(@Nullable final String tag, @Nonnull final String message) { + if (showDebugMessages) { + showMessageInUiThread(tag == null ? message : tag + ": " + message); + } + } - private void showMessageInUiThread(@Nonnull 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(@Nonnull 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(); + } + }); + } + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/AndroidCalculatorPreferenceService.java b/android-app/src/main/java/org/solovyev/android/calculator/AndroidCalculatorPreferenceService.java index 57482c5b..62784211 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/AndroidCalculatorPreferenceService.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/AndroidCalculatorPreferenceService.java @@ -25,10 +25,6 @@ package org.solovyev.android.calculator; import android.app.Application; import android.content.SharedPreferences; import android.preference.PreferenceManager; -import jscl.AngleUnit; -import jscl.NumeralBase; - -import javax.annotation.Nonnull; import org.solovyev.android.calculator.model.AndroidCalculatorEngine; import org.solovyev.android.msg.AndroidMessage; @@ -37,6 +33,11 @@ import org.solovyev.common.msg.MessageType; import java.util.ArrayList; import java.util.List; +import javax.annotation.Nonnull; + +import jscl.AngleUnit; +import jscl.NumeralBase; + /** * User: serso * Date: 11/17/12 @@ -44,75 +45,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; - @Nonnull - private final Application application; + @Nonnull + private final Application application; - public AndroidCalculatorPreferenceService(@Nonnull Application application) { - this.application = application; - } + public AndroidCalculatorPreferenceService(@Nonnull 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 || (Preferences.Calculations.showCalculationMessagesDialog.getPreference(prefs) && isTimeForCheck(currentTime, prefs))) { - final NumeralBase preferredNumeralBase = Preferences.Calculations.preferredNumeralBase.getPreference(prefs); - final NumeralBase numeralBase = AndroidCalculatorEngine.Preferences.numeralBase.getPreference(prefs); + if (force || (Preferences.Calculations.showCalculationMessagesDialog.getPreference(prefs) && isTimeForCheck(currentTime, prefs))) { + final NumeralBase preferredNumeralBase = Preferences.Calculations.preferredNumeralBase.getPreference(prefs); + final NumeralBase numeralBase = AndroidCalculatorEngine.Preferences.numeralBase.getPreference(prefs); - final AngleUnit preferredAngleUnits = Preferences.Calculations.preferredAngleUnits.getPreference(prefs); - final AngleUnit angleUnits = AndroidCalculatorEngine.Preferences.angleUnit.getPreference(prefs); + final AngleUnit preferredAngleUnits = Preferences.Calculations.preferredAngleUnits.getPreference(prefs); + final AngleUnit angleUnits = AndroidCalculatorEngine.Preferences.angleUnit.getPreference(prefs); - final List messages = new ArrayList(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 messages = new ArrayList(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); - Preferences.Calculations.lastPreferredPreferencesCheck.putPreference(prefs, currentTime); - } - } + Preferences.Calculations.lastPreferredPreferencesCheck.putPreference(prefs, currentTime); + } + } - private boolean isTimeForCheck(@Nonnull Long currentTime, @Nonnull SharedPreferences preferences) { - final Long lastPreferredPreferencesCheckTime = Preferences.Calculations.lastPreferredPreferencesCheck.getPreference(preferences); + private boolean isTimeForCheck(@Nonnull Long currentTime, @Nonnull SharedPreferences preferences) { + final Long lastPreferredPreferencesCheckTime = Preferences.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(Preferences.Calculations.preferredAngleUnits.getPreference(preferences)); - } + @Override + public void setPreferredAngleUnits() { + final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(application); + setAngleUnits(Preferences.Calculations.preferredAngleUnits.getPreference(preferences)); + } - @Override - public void setAngleUnits(@Nonnull AngleUnit angleUnit) { - final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(application); - AndroidCalculatorEngine.Preferences.angleUnit.putPreference(preferences, angleUnit); + @Override + public void setAngleUnits(@Nonnull 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(Preferences.Calculations.preferredNumeralBase.getPreference(preferences)); - } + @Override + public void setPreferredNumeralBase() { + final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(application); + setNumeralBase(Preferences.Calculations.preferredNumeralBase.getPreference(preferences)); + } - @Override - public void setNumeralBase(@Nonnull NumeralBase numeralBase) { - final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(application); - AndroidCalculatorEngine.Preferences.numeralBase.putPreference(preferences, numeralBase); + @Override + public void setNumeralBase(@Nonnull 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())); + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/AndroidFunctionCategory.java b/android-app/src/main/java/org/solovyev/android/calculator/AndroidFunctionCategory.java index 8bf13ae2..7c32e597 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/AndroidFunctionCategory.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/AndroidFunctionCategory.java @@ -32,30 +32,30 @@ import javax.annotation.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; - } + @Nullable + public static AndroidFunctionCategory valueOf(@Nonnull FunctionCategory functionCategory) { + for (AndroidFunctionCategory androidFunctionCategory : values()) { + if (androidFunctionCategory.name().equals(functionCategory.name())) { + return androidFunctionCategory; + } + } - @Nullable - public static AndroidFunctionCategory valueOf(@Nonnull FunctionCategory functionCategory) { - for (AndroidFunctionCategory androidFunctionCategory : values()) { - if (androidFunctionCategory.name().equals(functionCategory.name())) { - return androidFunctionCategory; - } - } + return null; + } - return null; - } + public int getCaptionId() { + return captionId; + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/AndroidNumeralBase.java b/android-app/src/main/java/org/solovyev/android/calculator/AndroidNumeralBase.java index bc030e35..d78a1318 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/AndroidNumeralBase.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/AndroidNumeralBase.java @@ -23,18 +23,19 @@ package org.solovyev.android.calculator; import android.app.Activity; -import jscl.NumeralBase; -import javax.annotation.Nonnull; - -import org.solovyev.android.calculator.units.CalculatorNumeralBase; import org.solovyev.android.calculator.drag.DirectionDragButton; import org.solovyev.android.calculator.drag.DragDirection; +import org.solovyev.android.calculator.units.CalculatorNumeralBase; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import javax.annotation.Nonnull; + +import jscl.NumeralBase; + /** * User: serso * Date: 4/21/12 @@ -42,92 +43,92 @@ import java.util.List; */ public enum AndroidNumeralBase { - bin(CalculatorNumeralBase.bin) { - @Nonnull - @Override - public List getButtonIds() { - return Arrays.asList(R.id.cpp_button_0, R.id.cpp_button_1); - } - }, + bin(CalculatorNumeralBase.bin) { + @Nonnull + @Override + public List getButtonIds() { + return Arrays.asList(R.id.cpp_button_0, R.id.cpp_button_1); + } + }, - oct(CalculatorNumeralBase.oct) { - @Nonnull - @Override - public List getButtonIds() { - final List result = new ArrayList(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) { + @Nonnull + @Override + public List getButtonIds() { + final List result = new ArrayList(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) { - @Nonnull - @Override - public List getButtonIds() { - final List result = new ArrayList(oct.getButtonIds()); - result.addAll(Arrays.asList(R.id.cpp_button_8, R.id.cpp_button_9)); - return result; - } - }, + dec(CalculatorNumeralBase.dec) { + @Nonnull + @Override + public List getButtonIds() { + final List result = new ArrayList(oct.getButtonIds()); + result.addAll(Arrays.asList(R.id.cpp_button_8, R.id.cpp_button_9)); + return result; + } + }, - hex(CalculatorNumeralBase.hex) { + hex(CalculatorNumeralBase.hex) { - @Nonnull - private List 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); + @Nonnull + private List 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); - @Nonnull - @Override - public List getButtonIds() { - return dec.getButtonIds(); - } + @Nonnull + @Override + public List getButtonIds() { + return dec.getButtonIds(); + } - @Override - protected void toggleButton(boolean show, @Nonnull DirectionDragButton button) { - super.toggleButton(show, button); - if (specialHexButtonIds.contains(button.getId())) { - button.showDirectionText(show, DragDirection.left); - button.invalidate(); - } - } - }; + @Override + protected void toggleButton(boolean show, @Nonnull DirectionDragButton button) { + super.toggleButton(show, button); + if (specialHexButtonIds.contains(button.getId())) { + button.showDirectionText(show, DragDirection.left); + button.invalidate(); + } + } + }; - @Nonnull - private final CalculatorNumeralBase calculatorNumeralBase; + @Nonnull + private final CalculatorNumeralBase calculatorNumeralBase; - private AndroidNumeralBase(@Nonnull CalculatorNumeralBase calculatorNumeralBase) { - this.calculatorNumeralBase = calculatorNumeralBase; - } + private AndroidNumeralBase(@Nonnull CalculatorNumeralBase calculatorNumeralBase) { + this.calculatorNumeralBase = calculatorNumeralBase; + } - @Nonnull - public abstract List getButtonIds(); + @Nonnull + public static AndroidNumeralBase valueOf(@Nonnull NumeralBase nb) { + for (AndroidNumeralBase androidNumeralBase : values()) { + if (androidNumeralBase.calculatorNumeralBase.getNumeralBase() == nb) { + return androidNumeralBase; + } + } - public void toggleButtons(boolean show, @Nonnull Activity activity) { - for (Integer buttonId : getButtonIds()) { - final DirectionDragButton button = (DirectionDragButton) activity.findViewById(buttonId); - if (button != null) { - toggleButton(show, button); - } - } - } + throw new IllegalArgumentException(nb + " is not supported numeral base!"); + } - protected void toggleButton(boolean show, @Nonnull DirectionDragButton button) { - button.setShowText(show); - button.invalidate(); - } + @Nonnull + public abstract List getButtonIds(); - @Nonnull - public NumeralBase getNumeralBase() { - return calculatorNumeralBase.getNumeralBase(); - } + public void toggleButtons(boolean show, @Nonnull Activity activity) { + for (Integer buttonId : getButtonIds()) { + final DirectionDragButton button = (DirectionDragButton) activity.findViewById(buttonId); + if (button != null) { + toggleButton(show, button); + } + } + } - @Nonnull - public static AndroidNumeralBase valueOf(@Nonnull NumeralBase nb) { - for (AndroidNumeralBase androidNumeralBase : values()) { - if (androidNumeralBase.calculatorNumeralBase.getNumeralBase() == nb) { - return androidNumeralBase; - } - } + protected void toggleButton(boolean show, @Nonnull DirectionDragButton button) { + button.setShowText(show); + button.invalidate(); + } - throw new IllegalArgumentException(nb + " is not supported numeral base!"); - } + @Nonnull + public NumeralBase getNumeralBase() { + return calculatorNumeralBase.getNumeralBase(); + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/AndroidOperatorCategory.java b/android-app/src/main/java/org/solovyev/android/calculator/AndroidOperatorCategory.java index ff218bc8..bb96cd2d 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/AndroidOperatorCategory.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/AndroidOperatorCategory.java @@ -32,29 +32,29 @@ import javax.annotation.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; - } + @Nullable + public static AndroidOperatorCategory valueOf(@Nonnull OperatorCategory operatorCategory) { + for (AndroidOperatorCategory androidOperatorCategory : values()) { + if (androidOperatorCategory.name().equals(operatorCategory.name())) { + return androidOperatorCategory; + } + } - @Nullable - public static AndroidOperatorCategory valueOf(@Nonnull OperatorCategory operatorCategory) { - for (AndroidOperatorCategory androidOperatorCategory : values()) { - if (androidOperatorCategory.name().equals(operatorCategory.name())) { - return androidOperatorCategory; - } - } + return null; + } - return null; - } + public int getCaptionId() { + return captionId; + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/AndroidVarCategory.java b/android-app/src/main/java/org/solovyev/android/calculator/AndroidVarCategory.java index 939c8c25..1cab9df3 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/AndroidVarCategory.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/AndroidVarCategory.java @@ -32,27 +32,27 @@ import javax.annotation.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; - } + @Nullable + public static AndroidVarCategory valueOf(@Nonnull VarCategory varCategory) { + for (AndroidVarCategory androidVarCategory : values()) { + if (androidVarCategory.name().equals(varCategory.name())) { + return androidVarCategory; + } + } - @Nullable - public static AndroidVarCategory valueOf(@Nonnull VarCategory varCategory) { - for (AndroidVarCategory androidVarCategory : values()) { - if (androidVarCategory.name().equals(varCategory.name())) { - return androidVarCategory; - } - } + return null; + } - return null; - } + public int getCaptionId() { + return captionId; + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/App.java b/android-app/src/main/java/org/solovyev/android/calculator/App.java index db562b17..214935a3 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/App.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/App.java @@ -84,273 +84,259 @@ import javax.annotation.Nullable; * Before first usage this class must be initialized by calling {@link App#init(android.app.Application)} method (for example, from {@link android.app.Application#onCreate()}) */ public final class App { - @Nonnull - private static final List> OLD_WIDGETS = Arrays.asList(CalculatorWidgetProvider.class, CalculatorWidgetProvider3x4.class, CalculatorWidgetProvider4x4.class, CalculatorWidgetProvider4x5.class); + @Nonnull + private static final List> OLD_WIDGETS = Arrays.asList(CalculatorWidgetProvider.class, CalculatorWidgetProvider3x4.class, CalculatorWidgetProvider4x4.class, CalculatorWidgetProvider4x5.class); + @Nonnull + private static final Products products = Products.create().add(ProductTypes.IN_APP, Arrays.asList("ad_free")); + @Nonnull + private static final Languages languages = new Languages(); + @Nonnull + private static volatile Application application; + @Nonnull + private static volatile DelayedExecutor uiThreadExecutor; + @Nonnull + private static volatile JEventListeners, JEvent> eventBus; + private static volatile boolean initialized; + @Nonnull + private static CalculatorBroadcaster broadcaster; + @Nonnull + private static SharedPreferences preferences; + @Nonnull + private static volatile Ga ga; + @Nonnull + private static volatile Billing billing; + @Nullable + private static Boolean lg = null; + @Nonnull + private static volatile Vibrator vibrator; + @Nonnull + private static volatile ScreenMetrics screenMetrics; + @Nonnull + private static volatile Plotter plotter; - @Nonnull - private static volatile Application application; - - @Nonnull - private static volatile DelayedExecutor uiThreadExecutor; - - @Nonnull - private static volatile JEventListeners, JEvent> eventBus; - - private static volatile boolean initialized; - - @Nonnull - private static CalculatorBroadcaster broadcaster; - - @Nonnull - private static SharedPreferences preferences; - - @Nonnull - private static volatile Ga ga; - - @Nonnull - private static volatile Billing billing; - - @Nonnull - private static final Products products = Products.create().add(ProductTypes.IN_APP, Arrays.asList("ad_free")); - - @Nullable - private static Boolean lg = null; - - @Nonnull - private static volatile Vibrator vibrator; - - @Nonnull - private static volatile ScreenMetrics screenMetrics; - - @Nonnull - private static volatile Plotter plotter; - - @Nonnull - private static final Languages languages = new Languages(); - - private App() { - throw new AssertionError(); - } + private App() { + throw new AssertionError(); + } /* - ********************************************************************** + ********************************************************************** * * METHODS * ********************************************************************** */ - public static void init(@Nonnull Application application) { - init(application, new UiThreadExecutor(), Listeners.newEventBus()); - } + public static void init(@Nonnull Application application) { + init(application, new UiThreadExecutor(), Listeners.newEventBus()); + } - public static void init(@Nonnull Application application, - @Nonnull UiThreadExecutor uiThreadExecutor, - @Nonnull JEventListeners, JEvent> eventBus) { - if (!initialized) { - App.application = application; - App.preferences = PreferenceManager.getDefaultSharedPreferences(application); - App.uiThreadExecutor = uiThreadExecutor; - App.eventBus = eventBus; - App.ga = new Ga(application, preferences, eventBus); - App.billing = new Billing(application, new Billing.DefaultConfiguration() { - @Nonnull - @Override - public String getPublicKey() { - return CalculatorSecurity.getPK(); - } + public static void init(@Nonnull Application application, + @Nonnull UiThreadExecutor uiThreadExecutor, + @Nonnull JEventListeners, JEvent> eventBus) { + if (!initialized) { + App.application = application; + App.preferences = PreferenceManager.getDefaultSharedPreferences(application); + App.uiThreadExecutor = uiThreadExecutor; + App.eventBus = eventBus; + App.ga = new Ga(application, preferences, eventBus); + App.billing = new Billing(application, new Billing.DefaultConfiguration() { + @Nonnull + @Override + public String getPublicKey() { + return CalculatorSecurity.getPK(); + } - @Nullable - @Override - public Inventory getFallbackInventory(@Nonnull Checkout checkout, @Nonnull Executor onLoadExecutor) { - if (RobotmediaDatabase.exists(billing.getContext())) { - return new RobotmediaInventory(checkout, onLoadExecutor); - } else { - return null; - } - } - }); - App.broadcaster = new CalculatorBroadcaster(application, preferences); - App.vibrator = new Vibrator(application, preferences); - App.screenMetrics = new ScreenMetrics(application); + @Nullable + @Override + public Inventory getFallbackInventory(@Nonnull Checkout checkout, @Nonnull Executor onLoadExecutor) { + if (RobotmediaDatabase.exists(billing.getContext())) { + return new RobotmediaInventory(checkout, onLoadExecutor); + } else { + return null; + } + } + }); + App.broadcaster = new CalculatorBroadcaster(application, preferences); + App.vibrator = new Vibrator(application, preferences); + App.screenMetrics = new ScreenMetrics(application); - final List> oldNotUsedWidgetClasses = findNotUsedWidgets(application); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) { - for (Class oldNotUsedWidgetClass : oldNotUsedWidgetClasses) { - Android.enableComponent(application, oldNotUsedWidgetClass, false); - } - } else { - // smaller widgets should be still used for smaller screens - if (oldNotUsedWidgetClasses.contains(CalculatorWidgetProvider4x5.class)) { - Android.enableComponent(application, CalculatorWidgetProvider4x5.class, false); - } - if (oldNotUsedWidgetClasses.contains(CalculatorWidgetProvider4x4.class)) { - Android.enableComponent(application, CalculatorWidgetProvider4x4.class, false); - } - } - App.languages.init(App.preferences); - App.plotter = Plot.newPlotter(application); + final List> oldNotUsedWidgetClasses = findNotUsedWidgets(application); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) { + for (Class oldNotUsedWidgetClass : oldNotUsedWidgetClasses) { + Android.enableComponent(application, oldNotUsedWidgetClass, false); + } + } else { + // smaller widgets should be still used for smaller screens + if (oldNotUsedWidgetClasses.contains(CalculatorWidgetProvider4x5.class)) { + Android.enableComponent(application, CalculatorWidgetProvider4x5.class, false); + } + if (oldNotUsedWidgetClasses.contains(CalculatorWidgetProvider4x4.class)) { + Android.enableComponent(application, CalculatorWidgetProvider4x4.class, false); + } + } + App.languages.init(App.preferences); + App.plotter = Plot.newPlotter(application); - App.initialized = true; - } else { - throw new IllegalStateException("Already initialized!"); - } - } + App.initialized = true; + } else { + throw new IllegalStateException("Already initialized!"); + } + } - @Nonnull - private static List> findNotUsedWidgets(@Nonnull Application application) { - final List> result = new ArrayList<>(); + @Nonnull + private static List> findNotUsedWidgets(@Nonnull Application application) { + final List> result = new ArrayList<>(); - final AppWidgetManager widgetManager = AppWidgetManager.getInstance(application); - for (Class widgetClass : OLD_WIDGETS) { - final int ids[] = widgetManager.getAppWidgetIds(new ComponentName(application, widgetClass)); - if (ids == null || ids.length == 0) { - result.add(widgetClass); - } - } + final AppWidgetManager widgetManager = AppWidgetManager.getInstance(application); + for (Class widgetClass : OLD_WIDGETS) { + final int ids[] = widgetManager.getAppWidgetIds(new ComponentName(application, widgetClass)); + if (ids == null || ids.length == 0) { + result.add(widgetClass); + } + } - return result; - } + return result; + } - private static void checkInit() { - if (!initialized) { - throw new IllegalStateException("App should be initialized!"); - } - } + private static void checkInit() { + if (!initialized) { + throw new IllegalStateException("App should be initialized!"); + } + } - /** - * @return if App has already been initialized, false otherwise - */ - public static boolean isInitialized() { - return initialized; - } + /** + * @return if App has already been initialized, false otherwise + */ + public static boolean isInitialized() { + return initialized; + } - /** - * @param real type of application - * @return application instance which was provided in {@link App#init(android.app.Application)} method - */ - @SuppressWarnings("unchecked") - @Nonnull - public static A getApplication() { - checkInit(); - return (A) application; - } + /** + * @param real type of application + * @return application instance which was provided in {@link App#init(android.app.Application)} method + */ + @SuppressWarnings("unchecked") + @Nonnull + public static A getApplication() { + checkInit(); + return (A) application; + } - /** - * Method returns executor which runs on Main Application's thread. It's safe to do all UI work on this executor - * - * @return UI thread executor - */ - @Nonnull - public static DelayedExecutor getUiThreadExecutor() { - checkInit(); - return uiThreadExecutor; - } + /** + * Method returns executor which runs on Main Application's thread. It's safe to do all UI work on this executor + * + * @return UI thread executor + */ + @Nonnull + public static DelayedExecutor getUiThreadExecutor() { + checkInit(); + return uiThreadExecutor; + } - /** - * @return application's event bus - */ - @Nonnull - public static JEventListeners, JEvent> getEventBus() { - checkInit(); - return eventBus; - } + /** + * @return application's event bus + */ + @Nonnull + public static JEventListeners, JEvent> getEventBus() { + checkInit(); + return eventBus; + } - @Nonnull - public static CalculatorBroadcaster getBroadcaster() { - return broadcaster; - } + @Nonnull + public static CalculatorBroadcaster getBroadcaster() { + return broadcaster; + } - @Nonnull - public static Ga getGa() { - return ga; - } + @Nonnull + public static Ga getGa() { + return ga; + } - @Nonnull - public static Billing getBilling() { - return billing; - } + @Nonnull + public static Billing getBilling() { + return billing; + } - @Nonnull - public static Products getProducts() { - return products; - } + @Nonnull + public static Products getProducts() { + return products; + } - public static boolean isLargeScreen() { - return Views.isLayoutSizeAtLeast(Configuration.SCREENLAYOUT_SIZE_LARGE, App.getApplication().getResources().getConfiguration()); - } + public static boolean isLargeScreen() { + return Views.isLayoutSizeAtLeast(Configuration.SCREENLAYOUT_SIZE_LARGE, App.getApplication().getResources().getConfiguration()); + } - @Nonnull - public static SharedPreferences getPreferences() { - return preferences; - } + @Nonnull + public static SharedPreferences getPreferences() { + return preferences; + } - @Nonnull - public static Preferences.Gui.Theme getTheme() { - return Preferences.Gui.getTheme(getPreferences()); - } + @Nonnull + public static Preferences.Gui.Theme getTheme() { + return Preferences.Gui.getTheme(getPreferences()); + } - @Nonnull - public static Preferences.SimpleTheme getWidgetTheme() { - return Preferences.Widget.getTheme(getPreferences()); - } + @Nonnull + public static Preferences.SimpleTheme getWidgetTheme() { + return Preferences.Widget.getTheme(getPreferences()); + } - @Nonnull - public static Preferences.Gui.Theme getThemeIn(@Nonnull Context context) { - if (context instanceof CalculatorOnscreenService) { - final SharedPreferences p = getPreferences(); - final Preferences.SimpleTheme onscreenTheme = Preferences.Onscreen.getTheme(p); - final Preferences.Gui.Theme appTheme = Preferences.Gui.getTheme(p); - return onscreenTheme.resolveThemeFor(appTheme).getAppTheme(); - } else { - return App.getTheme(); - } - } + @Nonnull + public static Preferences.Gui.Theme getThemeIn(@Nonnull Context context) { + if (context instanceof CalculatorOnscreenService) { + final SharedPreferences p = getPreferences(); + final Preferences.SimpleTheme onscreenTheme = Preferences.Onscreen.getTheme(p); + final Preferences.Gui.Theme appTheme = Preferences.Gui.getTheme(p); + return onscreenTheme.resolveThemeFor(appTheme).getAppTheme(); + } else { + return App.getTheme(); + } + } - @Nonnull - public static Languages getLanguages() { - return languages; - } + @Nonnull + public static Languages getLanguages() { + return languages; + } - public static boolean isLg() { - if (lg == null) { - lg = "lge".equalsIgnoreCase(Build.BRAND) || "lge".equalsIgnoreCase(Build.MANUFACTURER); - } - return lg; - } + public static boolean isLg() { + if (lg == null) { + lg = "lge".equalsIgnoreCase(Build.BRAND) || "lge".equalsIgnoreCase(Build.MANUFACTURER); + } + return lg; + } - // see https://code.google.com/p/android/issues/detail?id=78154 - // and http://developer.lge.com/community/forums/RetrieveForumContent.dev?detailContsId=FC29190703 - public static boolean shouldOpenMenuManually() { - return isLg() && Build.VERSION.SDK_INT == Build.VERSION_CODES.JELLY_BEAN; - } + // see https://code.google.com/p/android/issues/detail?id=78154 + // and http://developer.lge.com/community/forums/RetrieveForumContent.dev?detailContsId=FC29190703 + public static boolean shouldOpenMenuManually() { + return isLg() && Build.VERSION.SDK_INT == Build.VERSION_CODES.JELLY_BEAN; + } - @Nonnull - public static Vibrator getVibrator() { - return vibrator; - } + @Nonnull + public static Vibrator getVibrator() { + return vibrator; + } - @Nonnull - public static ScreenMetrics getScreenMetrics() { - return screenMetrics; - } + @Nonnull + public static ScreenMetrics getScreenMetrics() { + return screenMetrics; + } - public static void showDialog(@Nonnull DialogFragment dialogFragment, - @Nonnull String fragmentTag, - @Nonnull FragmentManager fm) { - final FragmentTransaction ft = fm.beginTransaction(); + public static void showDialog(@Nonnull DialogFragment dialogFragment, + @Nonnull String fragmentTag, + @Nonnull FragmentManager fm) { + final FragmentTransaction ft = fm.beginTransaction(); - Fragment prev = fm.findFragmentByTag(fragmentTag); - if (prev != null) { - ft.remove(prev); - } + Fragment prev = fm.findFragmentByTag(fragmentTag); + if (prev != null) { + ft.remove(prev); + } - // Create and show the dialog. - dialogFragment.show(ft, fragmentTag); - } + // Create and show the dialog. + dialogFragment.show(ft, fragmentTag); + } - @Nonnull - public static Plotter getPlotter() { - return plotter; - } + @Nonnull + public static Plotter getPlotter() { + return plotter; + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/BaseActivity.java b/android-app/src/main/java/org/solovyev/android/calculator/BaseActivity.java index 4d4c858f..f8e91f7c 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/BaseActivity.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/BaseActivity.java @@ -10,86 +10,86 @@ import javax.annotation.Nonnull; public class BaseActivity extends ActionBarActivity { - @Nonnull - protected final ActivityUi ui; + @Nonnull + protected final ActivityUi ui; - public BaseActivity(@Nonnull ActivityUi ui) { - this.ui = ui; - } + public BaseActivity(@Nonnull ActivityUi ui) { + this.ui = ui; + } - public BaseActivity(@LayoutRes int layout) { - this(layout, "Activity"); - } + public BaseActivity(@LayoutRes int layout) { + this(layout, "Activity"); + } - public BaseActivity(@LayoutRes int layout, @Nonnull String logTag) { - this.ui = new ActivityUi(layout, logTag); - } + public BaseActivity(@LayoutRes int layout, @Nonnull String logTag) { + this.ui = new ActivityUi(layout, logTag); + } - @Nonnull - public ActivityUi getUi() { - return ui; - } + @Nonnull + public ActivityUi getUi() { + return ui; + } - @Override - protected void onCreate(Bundle savedInstanceState) { - ui.onPreCreate(this); - super.onCreate(savedInstanceState); - ui.onCreate(this); - } + @Override + protected void onCreate(Bundle savedInstanceState) { + ui.onPreCreate(this); + super.onCreate(savedInstanceState); + ui.onCreate(this); + } - @Override - protected void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); - ui.onSaveInstanceState(this, outState); - } + @Override + protected void onSaveInstanceState(Bundle outState) { + super.onSaveInstanceState(outState); + ui.onSaveInstanceState(this, outState); + } - @Override - protected void onStart() { - super.onStart(); - ui.onStart(this); - } + @Override + protected void onStart() { + super.onStart(); + ui.onStart(this); + } - @Override - protected void onStop() { - ui.onStop(this); - super.onStop(); - } + @Override + protected void onStop() { + ui.onStop(this); + super.onStop(); + } - @Override - public boolean onKeyDown(int keyCode, KeyEvent event) { - if (App.shouldOpenMenuManually() && keyCode == KeyEvent.KEYCODE_MENU) { - openOptionsMenu(); - return true; - } - return super.onKeyDown(keyCode, event); - } + @Override + public boolean onKeyDown(int keyCode, KeyEvent event) { + if (App.shouldOpenMenuManually() && keyCode == KeyEvent.KEYCODE_MENU) { + openOptionsMenu(); + return true; + } + return super.onKeyDown(keyCode, event); + } - @Override - protected void onResume() { - super.onResume(); - ui.onResume(this); - } + @Override + protected void onResume() { + super.onResume(); + ui.onResume(this); + } - @Override - protected void onPause() { - this.ui.onPause(this); - super.onPause(); - } + @Override + protected void onPause() { + this.ui.onPause(this); + super.onPause(); + } - @Override - protected void onDestroy() { - super.onDestroy(); - ui.onDestroy(this); - } + @Override + protected void onDestroy() { + super.onDestroy(); + ui.onDestroy(this); + } - @Override - public boolean onOptionsItemSelected(MenuItem item) { - switch (item.getItemId()) { - case android.R.id.home: - finish(); - return true; - } - return super.onOptionsItemSelected(item); - } + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + finish(); + return true; + } + return super.onOptionsItemSelected(item); + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/BaseUi.java b/android-app/src/main/java/org/solovyev/android/calculator/BaseUi.java index 72943256..2380aebf 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/BaseUi.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/BaseUi.java @@ -32,8 +32,13 @@ import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.widget.TextView; + import org.solovyev.android.Views; -import org.solovyev.android.calculator.drag.*; +import org.solovyev.android.calculator.drag.DirectionDragButton; +import org.solovyev.android.calculator.drag.DragButton; +import org.solovyev.android.calculator.drag.DragDirection; +import org.solovyev.android.calculator.drag.DragListener; +import org.solovyev.android.calculator.drag.SimpleDragListener; import org.solovyev.android.calculator.history.CalculatorHistoryState; import org.solovyev.android.calculator.history.HistoryDragProcessor; import org.solovyev.android.calculator.view.AngleUnitsButton; @@ -42,11 +47,12 @@ import org.solovyev.android.calculator.view.NumeralBasesButton; import org.solovyev.android.calculator.view.ViewsCache; import org.solovyev.common.math.Point2d; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + import static org.solovyev.android.calculator.Preferences.Gui.Layout.simple; import static org.solovyev.android.calculator.Preferences.Gui.Layout.simple_mobile; import static org.solovyev.android.calculator.model.AndroidCalculatorEngine.Preferences.angleUnit; @@ -54,263 +60,263 @@ import static org.solovyev.android.calculator.model.AndroidCalculatorEngine.Pref public abstract class BaseUi implements SharedPreferences.OnSharedPreferenceChangeListener { - @Nonnull - private static final List viewIds = new ArrayList<>(200); + @Nonnull + private static final List viewIds = new ArrayList<>(200); - @Nonnull - protected Preferences.Gui.Layout layout; + @Nonnull + protected Preferences.Gui.Layout layout; - @Nonnull - protected Preferences.Gui.Theme theme; + @Nonnull + protected Preferences.Gui.Theme theme; - @Nonnull - private String logTag = "CalculatorActivity"; + @Nonnull + private String logTag = "CalculatorActivity"; - @Nullable - private AngleUnitsButton angleUnitsButton; + @Nullable + private AngleUnitsButton angleUnitsButton; - @Nullable - private NumeralBasesButton clearButton; + @Nullable + private NumeralBasesButton clearButton; - protected BaseUi() { - } + protected BaseUi() { + } - protected BaseUi(@Nonnull String logTag) { - this.logTag = logTag; - } + protected BaseUi(@Nonnull String logTag) { + this.logTag = logTag; + } - protected void onCreate(@Nonnull Activity activity) { - final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity); + @Nonnull + private static List getViewIds() { + if (viewIds.isEmpty()) { + viewIds.add(R.id.wizard_dragbutton); + viewIds.add(R.id.cpp_button_vars); + viewIds.add(R.id.cpp_button_round_brackets); + viewIds.add(R.id.cpp_button_right); + viewIds.add(R.id.cpp_button_plus); + viewIds.add(R.id.cpp_button_operators); + viewIds.add(R.id.cpp_button_multiplication); + viewIds.add(R.id.cpp_button_subtraction); + viewIds.add(R.id.cpp_button_left); + viewIds.add(R.id.cpp_button_history); + viewIds.add(R.id.cpp_button_functions); + viewIds.add(R.id.cpp_button_equals); + viewIds.add(R.id.cpp_button_period); + viewIds.add(R.id.cpp_button_division); + viewIds.add(R.id.cpp_button_9); + viewIds.add(R.id.cpp_button_8); + viewIds.add(R.id.cpp_button_7); + viewIds.add(R.id.cpp_button_6); + viewIds.add(R.id.cpp_button_5); + viewIds.add(R.id.cpp_button_4); + viewIds.add(R.id.cpp_button_3); + viewIds.add(R.id.cpp_button_2); + viewIds.add(R.id.cpp_button_1); + viewIds.add(R.id.cpp_button_0); + viewIds.add(R.id.cpp_button_clear); + } + return viewIds; + } - layout = Preferences.Gui.layout.getPreferenceNoError(preferences); - theme = Preferences.Gui.theme.getPreferenceNoError(preferences); + protected void onCreate(@Nonnull Activity activity) { + final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity); - preferences.registerOnSharedPreferenceChangeListener(this); + layout = Preferences.Gui.layout.getPreferenceNoError(preferences); + theme = Preferences.Gui.theme.getPreferenceNoError(preferences); - // let's disable locking of screen for monkeyrunner - if (CalculatorApplication.isMonkeyRunner(activity)) { - final KeyguardManager km = (KeyguardManager) activity.getSystemService(Context.KEYGUARD_SERVICE); - //noinspection deprecation - km.newKeyguardLock(activity.getClass().getName()).disableKeyguard(); - } - } + preferences.registerOnSharedPreferenceChangeListener(this); - public void logError(@Nonnull String message) { - Log.e(logTag, message); - } + // let's disable locking of screen for monkeyrunner + if (CalculatorApplication.isMonkeyRunner(activity)) { + final KeyguardManager km = (KeyguardManager) activity.getSystemService(Context.KEYGUARD_SERVICE); + //noinspection deprecation + km.newKeyguardLock(activity.getClass().getName()).disableKeyguard(); + } + } - public void onDestroy(@Nonnull Activity activity) { - final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity); + public void logError(@Nonnull String message) { + Log.e(logTag, message); + } - preferences.unregisterOnSharedPreferenceChangeListener(this); - } + public void onDestroy(@Nonnull Activity activity) { + final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity); - protected void fixFonts(@Nonnull View root) { - // some devices ship own fonts which causes issues with rendering. Let's use our own font for all text views - final Typeface typeFace = CalculatorApplication.getInstance().getTypeFace(); - Views.processViewsOfType(root, TextView.class, new Views.ViewProcessor() { - @Override - public void process(@Nonnull TextView view) { - int style = Typeface.NORMAL; - final Typeface oldTypeface = view.getTypeface(); - if (oldTypeface != null) { - style = oldTypeface.getStyle(); - } - view.setTypeface(typeFace, style); - } - }); - } + preferences.unregisterOnSharedPreferenceChangeListener(this); + } - public void processButtons(@Nonnull final Activity activity, @Nonnull View root) { - final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity); + protected void fixFonts(@Nonnull View root) { + // some devices ship own fonts which causes issues with rendering. Let's use our own font for all text views + final Typeface typeFace = CalculatorApplication.getInstance().getTypeFace(); + Views.processViewsOfType(root, TextView.class, new Views.ViewProcessor() { + @Override + public void process(@Nonnull TextView view) { + int style = Typeface.NORMAL; + final Typeface oldTypeface = view.getTypeface(); + if (oldTypeface != null) { + style = oldTypeface.getStyle(); + } + view.setTypeface(typeFace, style); + } + }); + } - final ViewsCache views = ViewsCache.forView(root); - setOnDragListeners(views, activity); + public void processButtons(@Nonnull final Activity activity, @Nonnull View root) { + final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity); - HistoryDragProcessor historyDragProcessor = new HistoryDragProcessor<>(getCalculator()); - final DragListener historyDragListener = newDragListener(historyDragProcessor, activity); - final DragButton historyButton = getButton(views, R.id.cpp_button_history); - if (historyButton != null) { - historyButton.setOnDragListener(historyDragListener); - } + final ViewsCache views = ViewsCache.forView(root); + setOnDragListeners(views, activity); - final DragButton minusButton = getButton(views, R.id.cpp_button_subtraction); - if (minusButton != null) { - minusButton.setOnDragListener(newDragListener(new OperatorsDragProcessor(), activity)); - } + HistoryDragProcessor historyDragProcessor = new HistoryDragProcessor<>(getCalculator()); + final DragListener historyDragListener = newDragListener(historyDragProcessor, activity); + final DragButton historyButton = getButton(views, R.id.cpp_button_history); + if (historyButton != null) { + historyButton.setOnDragListener(historyDragListener); + } - final DragListener toPositionDragListener = new SimpleDragListener(new CursorDragProcessor(), activity); + final DragButton minusButton = getButton(views, R.id.cpp_button_subtraction); + if (minusButton != null) { + minusButton.setOnDragListener(newDragListener(new OperatorsDragProcessor(), activity)); + } - final DragButton rightButton = getButton(views, R.id.cpp_button_right); - if (rightButton != null) { - rightButton.setOnDragListener(toPositionDragListener); - } + final DragListener toPositionDragListener = new SimpleDragListener(new CursorDragProcessor(), activity); - final DragButton leftButton = getButton(views, R.id.cpp_button_left); - if (leftButton != null) { - leftButton.setOnDragListener(toPositionDragListener); - } + final DragButton rightButton = getButton(views, R.id.cpp_button_right); + if (rightButton != null) { + rightButton.setOnDragListener(toPositionDragListener); + } - final DragButton equalsButton = getButton(views, R.id.cpp_button_equals); - if (equalsButton != null) { - equalsButton.setOnDragListener(newDragListener(new EqualsDragProcessor(), activity)); - } + final DragButton leftButton = getButton(views, R.id.cpp_button_left); + if (leftButton != null) { + leftButton.setOnDragListener(toPositionDragListener); + } - angleUnitsButton = getButton(views, R.id.cpp_button_6); - if (angleUnitsButton != null) { - angleUnitsButton.setOnDragListener(newDragListener(new CalculatorButtons.AngleUnitsChanger(activity), activity)); - } + final DragButton equalsButton = getButton(views, R.id.cpp_button_equals); + if (equalsButton != null) { + equalsButton.setOnDragListener(newDragListener(new EqualsDragProcessor(), activity)); + } - final View eraseButton = getButton(views, R.id.cpp_button_erase); - if (eraseButton != null) { - LongClickEraser.createAndAttach(eraseButton); - } + angleUnitsButton = getButton(views, R.id.cpp_button_6); + if (angleUnitsButton != null) { + angleUnitsButton.setOnDragListener(newDragListener(new CalculatorButtons.AngleUnitsChanger(activity), activity)); + } - clearButton = getButton(views, R.id.cpp_button_clear); - if (clearButton != null) { - clearButton.setOnDragListener(newDragListener(new CalculatorButtons.NumeralBasesChanger(activity), activity)); - } + final View eraseButton = getButton(views, R.id.cpp_button_erase); + if (eraseButton != null) { + LongClickEraser.createAndAttach(eraseButton); + } - final DragButton varsButton = getButton(views, R.id.cpp_button_vars); - if (varsButton != null) { - varsButton.setOnDragListener(newDragListener(new CalculatorButtons.VarsDragProcessor(activity), activity)); - } + clearButton = getButton(views, R.id.cpp_button_clear); + if (clearButton != null) { + clearButton.setOnDragListener(newDragListener(new CalculatorButtons.NumeralBasesChanger(activity), activity)); + } - final DragButton functionsButton = getButton(views, R.id.cpp_button_functions); - if (functionsButton != null) { - functionsButton.setOnDragListener(newDragListener(new CalculatorButtons.FunctionsDragProcessor(activity), activity)); - } + final DragButton varsButton = getButton(views, R.id.cpp_button_vars); + if (varsButton != null) { + varsButton.setOnDragListener(newDragListener(new CalculatorButtons.VarsDragProcessor(activity), activity)); + } - final DragButton roundBracketsButton = getButton(views, R.id.cpp_button_round_brackets); - if (roundBracketsButton != null) { - roundBracketsButton.setOnDragListener(newDragListener(new CalculatorButtons.RoundBracketsDragProcessor(), activity)); - } + final DragButton functionsButton = getButton(views, R.id.cpp_button_functions); + if (functionsButton != null) { + functionsButton.setOnDragListener(newDragListener(new CalculatorButtons.FunctionsDragProcessor(activity), activity)); + } - if (layout == simple || layout == simple_mobile) { - toggleButtonDirectionText(views, R.id.cpp_button_1, false, DragDirection.up, DragDirection.down); - toggleButtonDirectionText(views, R.id.cpp_button_2, false, DragDirection.up, DragDirection.down); - toggleButtonDirectionText(views, R.id.cpp_button_3, false, DragDirection.up, DragDirection.down); + final DragButton roundBracketsButton = getButton(views, R.id.cpp_button_round_brackets); + if (roundBracketsButton != null) { + roundBracketsButton.setOnDragListener(newDragListener(new CalculatorButtons.RoundBracketsDragProcessor(), activity)); + } - toggleButtonDirectionText(views, R.id.cpp_button_6, false, DragDirection.up, DragDirection.down); - toggleButtonDirectionText(views, R.id.cpp_button_7, false, DragDirection.left, DragDirection.up, DragDirection.down); - toggleButtonDirectionText(views, R.id.cpp_button_8, false, DragDirection.left, DragDirection.up, DragDirection.down); + if (layout == simple || layout == simple_mobile) { + toggleButtonDirectionText(views, R.id.cpp_button_1, false, DragDirection.up, DragDirection.down); + toggleButtonDirectionText(views, R.id.cpp_button_2, false, DragDirection.up, DragDirection.down); + toggleButtonDirectionText(views, R.id.cpp_button_3, false, DragDirection.up, DragDirection.down); - toggleButtonDirectionText(views, R.id.cpp_button_clear, false, DragDirection.left, DragDirection.up, DragDirection.down); + toggleButtonDirectionText(views, R.id.cpp_button_6, false, DragDirection.up, DragDirection.down); + toggleButtonDirectionText(views, R.id.cpp_button_7, false, DragDirection.left, DragDirection.up, DragDirection.down); + toggleButtonDirectionText(views, R.id.cpp_button_8, false, DragDirection.left, DragDirection.up, DragDirection.down); - toggleButtonDirectionText(views, R.id.cpp_button_4, false, DragDirection.down); - toggleButtonDirectionText(views, R.id.cpp_button_5, false, DragDirection.down); + toggleButtonDirectionText(views, R.id.cpp_button_clear, false, DragDirection.left, DragDirection.up, DragDirection.down); - toggleButtonDirectionText(views, R.id.cpp_button_9, false, DragDirection.left); + toggleButtonDirectionText(views, R.id.cpp_button_4, false, DragDirection.down); + toggleButtonDirectionText(views, R.id.cpp_button_5, false, DragDirection.down); - toggleButtonDirectionText(views, R.id.cpp_button_multiplication, false, DragDirection.left); - toggleButtonDirectionText(views, R.id.cpp_button_plus, false, DragDirection.down, DragDirection.up); - } + toggleButtonDirectionText(views, R.id.cpp_button_9, false, DragDirection.left); - CalculatorButtons.fixButtonsTextSize(theme, layout, root); - CalculatorButtons.toggleEqualsButton(preferences, activity); - CalculatorButtons.initMultiplicationButton(root); - NumeralBaseButtons.toggleNumericDigits(activity, preferences); + toggleButtonDirectionText(views, R.id.cpp_button_multiplication, false, DragDirection.left); + toggleButtonDirectionText(views, R.id.cpp_button_plus, false, DragDirection.down, DragDirection.up); + } - new ButtonOnClickListener().attachToViews(views); - } + CalculatorButtons.fixButtonsTextSize(theme, layout, root); + CalculatorButtons.toggleEqualsButton(preferences, activity); + CalculatorButtons.initMultiplicationButton(root); + NumeralBaseButtons.toggleNumericDigits(activity, preferences); - private void setOnDragListeners(@Nonnull ViewsCache views, @Nonnull Context context) { - final DragListener dragListener = newDragListener(new DigitButtonDragProcessor(getKeyboard()), context); + new ButtonOnClickListener().attachToViews(views); + } - final List viewIds = getViewIds(); - for (Integer viewId : viewIds) { - final View view = views.findViewById(viewId); - if (view instanceof DragButton) { - ((DragButton) view).setOnDragListener(dragListener); - } - } - } + private void setOnDragListeners(@Nonnull ViewsCache views, @Nonnull Context context) { + final DragListener dragListener = newDragListener(new DigitButtonDragProcessor(getKeyboard()), context); - @Nonnull - private SimpleDragListener newDragListener(@Nonnull SimpleDragListener.DragProcessor dragProcessor, @Nonnull Context context) { - return new SimpleDragListener(dragProcessor, context); - } + final List viewIds = getViewIds(); + for (Integer viewId : viewIds) { + final View view = views.findViewById(viewId); + if (view instanceof DragButton) { + ((DragButton) view).setOnDragListener(dragListener); + } + } + } - private void toggleButtonDirectionText(@Nonnull ViewsCache views, int id, boolean showDirectionText, @Nonnull DragDirection... dragDirections) { - final View v = getButton(views, id); - if (v instanceof DirectionDragButton) { - final DirectionDragButton button = (DirectionDragButton) v; - for (DragDirection dragDirection : dragDirections) { - button.showDirectionText(showDirectionText, dragDirection); - } - } - } + @Nonnull + private SimpleDragListener newDragListener(@Nonnull SimpleDragListener.DragProcessor dragProcessor, @Nonnull Context context) { + return new SimpleDragListener(dragProcessor, context); + } - @Nonnull - private Calculator getCalculator() { - return Locator.getInstance().getCalculator(); - } + private void toggleButtonDirectionText(@Nonnull ViewsCache views, int id, boolean showDirectionText, @Nonnull DragDirection... dragDirections) { + final View v = getButton(views, id); + if (v instanceof DirectionDragButton) { + final DirectionDragButton button = (DirectionDragButton) v; + for (DragDirection dragDirection : dragDirections) { + button.showDirectionText(showDirectionText, dragDirection); + } + } + } - @Nonnull - private static List getViewIds() { - if (viewIds.isEmpty()) { - viewIds.add(R.id.wizard_dragbutton); - viewIds.add(R.id.cpp_button_vars); - viewIds.add(R.id.cpp_button_round_brackets); - viewIds.add(R.id.cpp_button_right); - viewIds.add(R.id.cpp_button_plus); - viewIds.add(R.id.cpp_button_operators); - viewIds.add(R.id.cpp_button_multiplication); - viewIds.add(R.id.cpp_button_subtraction); - viewIds.add(R.id.cpp_button_left); - viewIds.add(R.id.cpp_button_history); - viewIds.add(R.id.cpp_button_functions); - viewIds.add(R.id.cpp_button_equals); - viewIds.add(R.id.cpp_button_period); - viewIds.add(R.id.cpp_button_division); - viewIds.add(R.id.cpp_button_9); - viewIds.add(R.id.cpp_button_8); - viewIds.add(R.id.cpp_button_7); - viewIds.add(R.id.cpp_button_6); - viewIds.add(R.id.cpp_button_5); - viewIds.add(R.id.cpp_button_4); - viewIds.add(R.id.cpp_button_3); - viewIds.add(R.id.cpp_button_2); - viewIds.add(R.id.cpp_button_1); - viewIds.add(R.id.cpp_button_0); - viewIds.add(R.id.cpp_button_clear); - } - return viewIds; - } + @Nonnull + private Calculator getCalculator() { + return Locator.getInstance().getCalculator(); + } - @Nonnull - private CalculatorKeyboard getKeyboard() { - return Locator.getInstance().getKeyboard(); - } + @Nonnull + private CalculatorKeyboard getKeyboard() { + return Locator.getInstance().getKeyboard(); + } - @Nullable - private V getButton(@Nonnull ViewsCache views, int buttonId) { - //noinspection unchecked - return (V) views.findViewById(buttonId); - } + @Nullable + private V getButton(@Nonnull ViewsCache views, int buttonId) { + //noinspection unchecked + return (V) views.findViewById(buttonId); + } - @Override - public void onSharedPreferenceChanged(SharedPreferences preferences, String key) { - if (angleUnit.isSameKey(key) || numeralBase.isSameKey(key)) { - if (angleUnitsButton != null) { - angleUnitsButton.setAngleUnit(angleUnit.getPreference(preferences)); - } + @Override + public void onSharedPreferenceChanged(SharedPreferences preferences, String key) { + if (angleUnit.isSameKey(key) || numeralBase.isSameKey(key)) { + if (angleUnitsButton != null) { + angleUnitsButton.setAngleUnit(angleUnit.getPreference(preferences)); + } - if (clearButton != null) { - clearButton.setNumeralBase(numeralBase.getPreference(preferences)); - } - } - } + if (clearButton != null) { + clearButton.setNumeralBase(numeralBase.getPreference(preferences)); + } + } + } - private static class OperatorsDragProcessor implements SimpleDragListener.DragProcessor { - @Override - public boolean processDragEvent(@Nonnull DragDirection dragDirection, @Nonnull DragButton dragButton, @Nonnull Point2d startPoint2d, @Nonnull MotionEvent motionEvent) { - if (dragDirection == DragDirection.down) { - App.getVibrator().vibrate(); - Locator.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.show_operators, null); - return true; - } - return false; - } - } + private static class OperatorsDragProcessor implements SimpleDragListener.DragProcessor { + @Override + public boolean processDragEvent(@Nonnull DragDirection dragDirection, @Nonnull DragButton dragButton, @Nonnull Point2d startPoint2d, @Nonnull MotionEvent motionEvent) { + if (dragDirection == DragDirection.down) { + App.getVibrator().vibrate(); + Locator.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.show_operators, null); + return true; + } + return false; + } + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/ButtonOnClickListener.java b/android-app/src/main/java/org/solovyev/android/calculator/ButtonOnClickListener.java index c8ae9c65..727f567b 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/ButtonOnClickListener.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/ButtonOnClickListener.java @@ -3,111 +3,112 @@ package org.solovyev.android.calculator; import android.support.annotation.IdRes; import android.view.View; import android.widget.Button; + import org.solovyev.android.calculator.view.ViewsCache; import javax.annotation.Nonnull; final class ButtonOnClickListener implements View.OnClickListener { - @Override - public void onClick(View v) { - switch (v.getId()) { - case R.id.cpp_button_0: - case R.id.cpp_button_1: - case R.id.cpp_button_2: - case R.id.cpp_button_3: - case R.id.cpp_button_4: - case R.id.cpp_button_5: - case R.id.cpp_button_6: - case R.id.cpp_button_7: - case R.id.cpp_button_8: - case R.id.cpp_button_9: - case R.id.cpp_button_division: - case R.id.cpp_button_period: - case R.id.cpp_button_left: - case R.id.cpp_button_subtraction: - case R.id.cpp_button_multiplication: - case R.id.cpp_button_plus: - case R.id.cpp_button_right: - case R.id.cpp_button_round_brackets: - onClick(((Button) v).getText().toString()); - break; - case R.id.cpp_button_clear: - onClick(CalculatorSpecialButton.clear); - break; - case R.id.cpp_button_functions: - onClick(CalculatorSpecialButton.functions); - break; - case R.id.cpp_button_history: - onClick(CalculatorSpecialButton.history); - break; - case R.id.cpp_button_erase: - onClick(CalculatorSpecialButton.erase); - break; - case R.id.cpp_button_paste: - onClick(CalculatorSpecialButton.paste); - break; - case R.id.cpp_button_copy: - onClick(CalculatorSpecialButton.copy); - break; - case R.id.cpp_button_like: - onClick(CalculatorSpecialButton.like); - break; - case R.id.cpp_button_operators: - onClick(CalculatorSpecialButton.operators); - break; - case R.id.cpp_button_vars: - onClick(CalculatorSpecialButton.vars); - break; - case R.id.cpp_button_equals: - onClick(CalculatorSpecialButton.equals); - break; - } - } + @Override + public void onClick(View v) { + switch (v.getId()) { + case R.id.cpp_button_0: + case R.id.cpp_button_1: + case R.id.cpp_button_2: + case R.id.cpp_button_3: + case R.id.cpp_button_4: + case R.id.cpp_button_5: + case R.id.cpp_button_6: + case R.id.cpp_button_7: + case R.id.cpp_button_8: + case R.id.cpp_button_9: + case R.id.cpp_button_division: + case R.id.cpp_button_period: + case R.id.cpp_button_left: + case R.id.cpp_button_subtraction: + case R.id.cpp_button_multiplication: + case R.id.cpp_button_plus: + case R.id.cpp_button_right: + case R.id.cpp_button_round_brackets: + onClick(((Button) v).getText().toString()); + break; + case R.id.cpp_button_clear: + onClick(CalculatorSpecialButton.clear); + break; + case R.id.cpp_button_functions: + onClick(CalculatorSpecialButton.functions); + break; + case R.id.cpp_button_history: + onClick(CalculatorSpecialButton.history); + break; + case R.id.cpp_button_erase: + onClick(CalculatorSpecialButton.erase); + break; + case R.id.cpp_button_paste: + onClick(CalculatorSpecialButton.paste); + break; + case R.id.cpp_button_copy: + onClick(CalculatorSpecialButton.copy); + break; + case R.id.cpp_button_like: + onClick(CalculatorSpecialButton.like); + break; + case R.id.cpp_button_operators: + onClick(CalculatorSpecialButton.operators); + break; + case R.id.cpp_button_vars: + onClick(CalculatorSpecialButton.vars); + break; + case R.id.cpp_button_equals: + onClick(CalculatorSpecialButton.equals); + break; + } + } - private void onClick(@Nonnull CalculatorSpecialButton b) { - onClick(b.getActionCode()); - } + private void onClick(@Nonnull CalculatorSpecialButton b) { + onClick(b.getActionCode()); + } - private void onClick(@Nonnull String s) { - Locator.getInstance().getKeyboard().buttonPressed(s); - } + private void onClick(@Nonnull String s) { + Locator.getInstance().getKeyboard().buttonPressed(s); + } - public void attachToViews(@Nonnull ViewsCache views) { - attachToView(views, R.id.cpp_button_0); - attachToView(views, R.id.cpp_button_1); - attachToView(views, R.id.cpp_button_2); - attachToView(views, R.id.cpp_button_3); - attachToView(views, R.id.cpp_button_4); - attachToView(views, R.id.cpp_button_5); - attachToView(views, R.id.cpp_button_6); - attachToView(views, R.id.cpp_button_7); - attachToView(views, R.id.cpp_button_8); - attachToView(views, R.id.cpp_button_9); - attachToView(views, R.id.cpp_button_division); - attachToView(views, R.id.cpp_button_period); - attachToView(views, R.id.cpp_button_left); - attachToView(views, R.id.cpp_button_subtraction); - attachToView(views, R.id.cpp_button_multiplication); - attachToView(views, R.id.cpp_button_plus); - attachToView(views, R.id.cpp_button_right); - attachToView(views, R.id.cpp_button_round_brackets); - attachToView(views, R.id.cpp_button_clear); - attachToView(views, R.id.cpp_button_functions); - attachToView(views, R.id.cpp_button_history); - attachToView(views, R.id.cpp_button_erase); - attachToView(views, R.id.cpp_button_paste); - attachToView(views, R.id.cpp_button_copy); - attachToView(views, R.id.cpp_button_like); - attachToView(views, R.id.cpp_button_operators); - attachToView(views, R.id.cpp_button_vars); - attachToView(views, R.id.cpp_button_equals); - } + public void attachToViews(@Nonnull ViewsCache views) { + attachToView(views, R.id.cpp_button_0); + attachToView(views, R.id.cpp_button_1); + attachToView(views, R.id.cpp_button_2); + attachToView(views, R.id.cpp_button_3); + attachToView(views, R.id.cpp_button_4); + attachToView(views, R.id.cpp_button_5); + attachToView(views, R.id.cpp_button_6); + attachToView(views, R.id.cpp_button_7); + attachToView(views, R.id.cpp_button_8); + attachToView(views, R.id.cpp_button_9); + attachToView(views, R.id.cpp_button_division); + attachToView(views, R.id.cpp_button_period); + attachToView(views, R.id.cpp_button_left); + attachToView(views, R.id.cpp_button_subtraction); + attachToView(views, R.id.cpp_button_multiplication); + attachToView(views, R.id.cpp_button_plus); + attachToView(views, R.id.cpp_button_right); + attachToView(views, R.id.cpp_button_round_brackets); + attachToView(views, R.id.cpp_button_clear); + attachToView(views, R.id.cpp_button_functions); + attachToView(views, R.id.cpp_button_history); + attachToView(views, R.id.cpp_button_erase); + attachToView(views, R.id.cpp_button_paste); + attachToView(views, R.id.cpp_button_copy); + attachToView(views, R.id.cpp_button_like); + attachToView(views, R.id.cpp_button_operators); + attachToView(views, R.id.cpp_button_vars); + attachToView(views, R.id.cpp_button_equals); + } - private void attachToView(@Nonnull ViewsCache views, @IdRes int viewId) { - final View view = views.findViewById(viewId); - if (view != null) { - view.setOnClickListener(this); - } - } + private void attachToView(@Nonnull ViewsCache views, @IdRes int viewId) { + final View view = views.findViewById(viewId); + if (view != null) { + view.setOnClickListener(this); + } + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/CalculatorActivity.java b/android-app/src/main/java/org/solovyev/android/calculator/CalculatorActivity.java index 17a34ef7..0f166dc7 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/CalculatorActivity.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/CalculatorActivity.java @@ -32,8 +32,13 @@ import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v7.app.ActionBar; import android.text.method.LinkMovementMethod; -import android.view.*; +import android.view.KeyEvent; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewConfiguration; +import android.view.Window; import android.widget.TextView; + import org.solovyev.android.Activities; import org.solovyev.android.Android; import org.solovyev.android.Threads; @@ -54,230 +59,232 @@ import static android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH; import static android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON; import static org.solovyev.android.calculator.Preferences.Gui.preventScreenFromFading; import static org.solovyev.android.calculator.release.ReleaseNotes.hasReleaseNotes; -import static org.solovyev.android.wizard.WizardUi.*; +import static org.solovyev.android.wizard.WizardUi.continueWizard; +import static org.solovyev.android.wizard.WizardUi.createLaunchIntent; +import static org.solovyev.android.wizard.WizardUi.startWizard; public class CalculatorActivity extends BaseActivity implements SharedPreferences.OnSharedPreferenceChangeListener, CalculatorEventListener { - @Nonnull - public static final String TAG = CalculatorActivity.class.getSimpleName(); + @Nonnull + public static final String TAG = CalculatorActivity.class.getSimpleName(); - private boolean useBackAsPrev; + private boolean useBackAsPrev; - public CalculatorActivity() { - super(0, TAG); - } + public CalculatorActivity() { + super(0, TAG); + } - /** - * Called when the activity is first created. - */ - @Override - public void onCreate(@Nullable Bundle savedInstanceState) { - final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); - final Preferences.Gui.Layout layout = Preferences.Gui.layout.getPreferenceNoError(preferences); - ui.setLayoutId(layout.getLayoutId()); + private static void firstTimeInit(@Nonnull SharedPreferences preferences, @Nonnull Context context) { + final Integer appOpenedCounter = Preferences.appOpenedCounter.getPreference(preferences); + if (appOpenedCounter != null) { + Preferences.appOpenedCounter.putPreference(preferences, appOpenedCounter + 1); + } - super.onCreate(savedInstanceState); + final Integer savedVersion = Preferences.appVersion.getPreference(preferences); - if (isMultiPane()) { - ui.addTab(this, CalculatorFragmentType.history, null, R.id.main_second_pane); - ui.addTab(this, CalculatorFragmentType.saved_history, null, R.id.main_second_pane); - ui.addTab(this, CalculatorFragmentType.variables, null, R.id.main_second_pane); - ui.addTab(this, CalculatorFragmentType.functions, null, R.id.main_second_pane); - ui.addTab(this, CalculatorFragmentType.operators, null, R.id.main_second_pane); - ui.addTab(this, CalculatorPlotActivity.getPlotterFragmentType(), null, R.id.main_second_pane); - } else { - final ActionBar actionBar = getSupportActionBar(); - if (Build.VERSION.SDK_INT <= GINGERBREAD_MR1 || (Build.VERSION.SDK_INT >= ICE_CREAM_SANDWICH && hasPermanentMenuKey())) { - actionBar.hide(); - } else { - actionBar.setDisplayShowTitleEnabled(false); - actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); - } - } + final int appVersion = Android.getAppVersionCode(context); - 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"); + Preferences.appVersion.putPreference(preferences, appVersion); - this.useBackAsPrev = Preferences.Gui.usePrevAsBack.getPreference(preferences); - if (savedInstanceState == null) { - firstTimeInit(preferences, this); - } + if (!CalculatorApplication.isMonkeyRunner(context)) { - toggleOrientationChange(preferences); + boolean dialogShown = false; + final Wizards wizards = CalculatorApplication.getInstance().getWizards(); + final Wizard wizard = wizards.getWizard(CalculatorWizards.FIRST_TIME_WIZARD); + if (wizard.isStarted() && !wizard.isFinished()) { + continueWizard(wizards, wizard.getName(), context); + dialogShown = true; + } else { + if (Objects.areEqual(savedVersion, Preferences.appVersion.getDefaultValue())) { + // new start + startWizard(wizards, context); + dialogShown = true; + } else { + if (savedVersion < appVersion) { + final boolean showReleaseNotes = Preferences.Gui.showReleaseNotes.getPreference(preferences); + if (showReleaseNotes && hasReleaseNotes(context, savedVersion + 1)) { + final Bundle bundle = new Bundle(); + bundle.putInt(CalculatorWizards.RELEASE_NOTES_VERSION, savedVersion); + context.startActivity(createLaunchIntent(wizards, CalculatorWizards.RELEASE_NOTES, context, bundle)); + dialogShown = true; + } + } + } + } - preferences.registerOnSharedPreferenceChangeListener(this); + //Log.d(this.getClass().getName(), "Application was opened " + appOpenedCounter + " time!"); + if (!dialogShown) { + if (appOpenedCounter != null && appOpenedCounter > 30) { + dialogShown = showSpecialWindow(preferences, Preferences.Gui.feedbackWindowShown, R.layout.feedback, R.id.feedbackText, context); + } + } + } + } - Locator.getInstance().getPreferenceService().checkPreferredPreferences(false); + private static boolean showSpecialWindow(@Nonnull SharedPreferences preferences, @Nonnull Preference specialWindowShownPref, int layoutId, int textViewId, @Nonnull Context context) { + boolean result = false; - if (CalculatorApplication.isMonkeyRunner(this)) { - Locator.getInstance().getKeyboard().buttonPressed("123"); - Locator.getInstance().getKeyboard().buttonPressed("+"); - Locator.getInstance().getKeyboard().buttonPressed("321"); - } - } + 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); - @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) - private boolean hasPermanentMenuKey() { - return ViewConfiguration.get(this).hasPermanentMenuKey(); - } + final TextView feedbackTextView = (TextView) view.findViewById(textViewId); + feedbackTextView.setMovementMethod(LinkMovementMethod.getInstance()); - private boolean isMultiPane() { - return findViewById(R.id.main_second_pane) != null; - } + final AlertDialog.Builder builder = new AlertDialog.Builder(context).setView(view); + builder.setPositiveButton(android.R.string.ok, null); + builder.create().show(); - @Nonnull - private AndroidCalculator getCalculator() { - return ((AndroidCalculator) Locator.getInstance().getCalculator()); - } + result = true; + specialWindowShownPref.putPreference(preferences, true); + } - private static void firstTimeInit(@Nonnull SharedPreferences preferences, @Nonnull Context context) { - final Integer appOpenedCounter = Preferences.appOpenedCounter.getPreference(preferences); - if (appOpenedCounter != null) { - Preferences.appOpenedCounter.putPreference(preferences, appOpenedCounter + 1); - } + return result; + } - final Integer savedVersion = Preferences.appVersion.getPreference(preferences); + /** + * Called when the activity is first created. + */ + @Override + public void onCreate(@Nullable Bundle savedInstanceState) { + final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); + final Preferences.Gui.Layout layout = Preferences.Gui.layout.getPreferenceNoError(preferences); + ui.setLayoutId(layout.getLayoutId()); - final int appVersion = Android.getAppVersionCode(context); + super.onCreate(savedInstanceState); - Preferences.appVersion.putPreference(preferences, appVersion); + if (isMultiPane()) { + ui.addTab(this, CalculatorFragmentType.history, null, R.id.main_second_pane); + ui.addTab(this, CalculatorFragmentType.saved_history, null, R.id.main_second_pane); + ui.addTab(this, CalculatorFragmentType.variables, null, R.id.main_second_pane); + ui.addTab(this, CalculatorFragmentType.functions, null, R.id.main_second_pane); + ui.addTab(this, CalculatorFragmentType.operators, null, R.id.main_second_pane); + ui.addTab(this, CalculatorPlotActivity.getPlotterFragmentType(), null, R.id.main_second_pane); + } else { + final ActionBar actionBar = getSupportActionBar(); + if (Build.VERSION.SDK_INT <= GINGERBREAD_MR1 || (Build.VERSION.SDK_INT >= ICE_CREAM_SANDWICH && hasPermanentMenuKey())) { + actionBar.hide(); + } else { + actionBar.setDisplayShowTitleEnabled(false); + actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); + } + } - if (!CalculatorApplication.isMonkeyRunner(context)) { + 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"); - boolean dialogShown = false; - final Wizards wizards = CalculatorApplication.getInstance().getWizards(); - final Wizard wizard = wizards.getWizard(CalculatorWizards.FIRST_TIME_WIZARD); - if (wizard.isStarted() && !wizard.isFinished()) { - continueWizard(wizards, wizard.getName(), context); - dialogShown = true; - } else { - if (Objects.areEqual(savedVersion, Preferences.appVersion.getDefaultValue())) { - // new start - startWizard(wizards, context); - dialogShown = true; - } else { - if (savedVersion < appVersion) { - final boolean showReleaseNotes = Preferences.Gui.showReleaseNotes.getPreference(preferences); - if (showReleaseNotes && hasReleaseNotes(context, savedVersion + 1)) { - final Bundle bundle = new Bundle(); - bundle.putInt(CalculatorWizards.RELEASE_NOTES_VERSION, savedVersion); - context.startActivity(createLaunchIntent(wizards, CalculatorWizards.RELEASE_NOTES, context, bundle)); - dialogShown = true; - } - } - } - } + this.useBackAsPrev = Preferences.Gui.usePrevAsBack.getPreference(preferences); + if (savedInstanceState == null) { + firstTimeInit(preferences, this); + } - //Log.d(this.getClass().getName(), "Application was opened " + appOpenedCounter + " time!"); - if (!dialogShown) { - if (appOpenedCounter != null && appOpenedCounter > 30) { - dialogShown = showSpecialWindow(preferences, Preferences.Gui.feedbackWindowShown, R.layout.feedback, R.id.feedbackText, context); - } - } - } - } + toggleOrientationChange(preferences); - private static boolean showSpecialWindow(@Nonnull SharedPreferences preferences, @Nonnull Preference specialWindowShownPref, int layoutId, int textViewId, @Nonnull Context context) { - boolean result = false; + preferences.registerOnSharedPreferenceChangeListener(this); - 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); + Locator.getInstance().getPreferenceService().checkPreferredPreferences(false); - final TextView feedbackTextView = (TextView) view.findViewById(textViewId); - feedbackTextView.setMovementMethod(LinkMovementMethod.getInstance()); + if (CalculatorApplication.isMonkeyRunner(this)) { + Locator.getInstance().getKeyboard().buttonPressed("123"); + Locator.getInstance().getKeyboard().buttonPressed("+"); + Locator.getInstance().getKeyboard().buttonPressed("321"); + } + } - final AlertDialog.Builder builder = new AlertDialog.Builder(context).setView(view); - builder.setPositiveButton(android.R.string.ok, null); - builder.create().show(); + @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) + private boolean hasPermanentMenuKey() { + return ViewConfiguration.get(this).hasPermanentMenuKey(); + } - result = true; - specialWindowShownPref.putPreference(preferences, true); - } + private boolean isMultiPane() { + return findViewById(R.id.main_second_pane) != null; + } - return result; - } + @Nonnull + private AndroidCalculator getCalculator() { + return ((AndroidCalculator) Locator.getInstance().getCalculator()); + } - @Override - public boolean onKeyDown(int keyCode, KeyEvent event) { - if (keyCode == KeyEvent.KEYCODE_BACK) { - if (useBackAsPrev) { - getCalculator().doHistoryAction(HistoryAction.undo); - return true; - } - } - return super.onKeyDown(keyCode, event); - } + @Override + public boolean onKeyDown(int keyCode, KeyEvent event) { + if (keyCode == KeyEvent.KEYCODE_BACK) { + if (useBackAsPrev) { + getCalculator().doHistoryAction(HistoryAction.undo); + return true; + } + } + return super.onKeyDown(keyCode, event); + } - @Override - protected void onResume() { - super.onResume(); + @Override + protected void onResume() { + super.onResume(); - final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); - final Preferences.Gui.Layout newLayout = Preferences.Gui.layout.getPreference(preferences); - if (newLayout != ui.getLayout()) { - Activities.restartActivity(this); - } + final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); + final Preferences.Gui.Layout newLayout = Preferences.Gui.layout.getPreference(preferences); + if (newLayout != ui.getLayout()) { + Activities.restartActivity(this); + } - final Window window = getWindow(); - if (preventScreenFromFading.getPreference(preferences)) { - window.addFlags(FLAG_KEEP_SCREEN_ON); - } else { - window.clearFlags(FLAG_KEEP_SCREEN_ON); - } - } + final Window window = getWindow(); + if (preventScreenFromFading.getPreference(preferences)) { + window.addFlags(FLAG_KEEP_SCREEN_ON); + } else { + window.clearFlags(FLAG_KEEP_SCREEN_ON); + } + } - @Override - protected void onDestroy() { - PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(this); + @Override + protected void onDestroy() { + PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(this); - super.onDestroy(); - } + super.onDestroy(); + } - @Override - public void onSharedPreferenceChanged(SharedPreferences preferences, @Nullable String key) { - if (Preferences.Gui.usePrevAsBack.getKey().equals(key)) { - useBackAsPrev = Preferences.Gui.usePrevAsBack.getPreference(preferences); - } + @Override + public void onSharedPreferenceChanged(SharedPreferences preferences, @Nullable String key) { + if (Preferences.Gui.usePrevAsBack.getKey().equals(key)) { + useBackAsPrev = Preferences.Gui.usePrevAsBack.getPreference(preferences); + } - if (Preferences.Gui.autoOrientation.getKey().equals(key)) { - toggleOrientationChange(preferences); - } - } + if (Preferences.Gui.autoOrientation.getKey().equals(key)) { + toggleOrientationChange(preferences); + } + } - private void toggleOrientationChange(@Nullable SharedPreferences preferences) { - preferences = preferences == null ? PreferenceManager.getDefaultSharedPreferences(this) : preferences; - if (Preferences.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 (Preferences.Gui.autoOrientation.getPreference(preferences)) { + setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); + } else { + setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); + } + } - @Override - public void onCalculatorEvent(@Nonnull CalculatorEventData calculatorEventData, @Nonnull CalculatorEventType calculatorEventType, @Nullable Object data) { - switch (calculatorEventType) { - case plot_graph: - Threads.tryRunOnUiThread(this, new Runnable() { - @Override - public void run() { - if (isMultiPane()) { - final ActionBar.Tab selectedTab = getSupportActionBar().getSelectedTab(); - if (selectedTab != null && CalculatorFragmentType.plotter.getFragmentTag().equals(selectedTab.getTag())) { - // do nothing - fragment shown and already registered for plot updates - } else { - // otherwise - open fragment - ui.selectTab(CalculatorActivity.this, CalculatorFragmentType.plotter); - } - } else { - // start new activity - CalculatorActivityLauncher.plotGraph(CalculatorActivity.this); - } - } - }); - break; - } - } + @Override + public void onCalculatorEvent(@Nonnull CalculatorEventData calculatorEventData, @Nonnull CalculatorEventType calculatorEventType, @Nullable Object data) { + switch (calculatorEventType) { + case plot_graph: + Threads.tryRunOnUiThread(this, new Runnable() { + @Override + public void run() { + if (isMultiPane()) { + final ActionBar.Tab selectedTab = getSupportActionBar().getSelectedTab(); + if (selectedTab != null && CalculatorFragmentType.plotter.getFragmentTag().equals(selectedTab.getTag())) { + // do nothing - fragment shown and already registered for plot updates + } else { + // otherwise - open fragment + ui.selectTab(CalculatorActivity.this, CalculatorFragmentType.plotter); + } + } else { + // start new activity + CalculatorActivityLauncher.plotGraph(CalculatorActivity.this); + } + } + }); + break; + } + } } \ No newline at end of file diff --git a/android-app/src/main/java/org/solovyev/android/calculator/CalculatorActivityLauncher.java b/android-app/src/main/java/org/solovyev/android/calculator/CalculatorActivityLauncher.java index c32a007b..f1ba3a39 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/CalculatorActivityLauncher.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/CalculatorActivityLauncher.java @@ -29,16 +29,20 @@ import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.preference.PreferenceManager; +import android.support.v7.app.ActionBarActivity; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; -import android.support.v7.app.ActionBarActivity; -import jscl.math.Generic; + import org.solovyev.android.Android; import org.solovyev.android.calculator.about.CalculatorAboutActivity; import org.solovyev.android.calculator.function.FunctionEditDialogFragment; import org.solovyev.android.calculator.history.CalculatorHistoryActivity; -import org.solovyev.android.calculator.math.edit.*; +import org.solovyev.android.calculator.math.edit.CalculatorFunctionsActivity; +import org.solovyev.android.calculator.math.edit.CalculatorOperatorsActivity; +import org.solovyev.android.calculator.math.edit.CalculatorVarsActivity; +import org.solovyev.android.calculator.math.edit.CalculatorVarsFragment; +import org.solovyev.android.calculator.math.edit.VarEditDialogFragment; import org.solovyev.android.calculator.matrix.CalculatorMatrixActivity; import org.solovyev.android.calculator.plot.CalculatorPlotActivity; import org.solovyev.android.calculator.plot.CalculatorPlotter; @@ -47,9 +51,12 @@ import org.solovyev.common.msg.Message; import org.solovyev.common.msg.MessageType; import org.solovyev.common.text.Strings; +import java.util.List; + import javax.annotation.Nonnull; import javax.annotation.Nullable; -import java.util.List; + +import jscl.math.Generic; /** * User: serso @@ -58,235 +65,235 @@ import java.util.List; */ public final class CalculatorActivityLauncher implements CalculatorEventListener { - public CalculatorActivityLauncher() { - } + public CalculatorActivityLauncher() { + } - public static void showHistory(@Nonnull final Context context) { - showHistory(context, false); - } + public static void showHistory(@Nonnull final Context context) { + showHistory(context, false); + } - public static void showHistory(@Nonnull final Context context, boolean detached) { - final Intent intent = new Intent(context, CalculatorHistoryActivity.class); - Android.addIntentFlags(intent, detached, context); - context.startActivity(intent); - } + public static void showHistory(@Nonnull final Context context, boolean detached) { + final Intent intent = new Intent(context, CalculatorHistoryActivity.class); + Android.addIntentFlags(intent, detached, context); + context.startActivity(intent); + } - public static void showSettings(@Nonnull final Context context) { - showSettings(context, false); - } + public static void showSettings(@Nonnull final Context context) { + showSettings(context, false); + } - public static void showSettings(@Nonnull final Context context, boolean detached) { - final Intent intent = new Intent(context, PreferencesActivity.class); - Android.addIntentFlags(intent, detached, context); - context.startActivity(intent); - } + public static void showSettings(@Nonnull final Context context, boolean detached) { + final Intent intent = new Intent(context, PreferencesActivity.class); + Android.addIntentFlags(intent, detached, context); + context.startActivity(intent); + } - public static void showAbout(@Nonnull final Context context) { - context.startActivity(new Intent(context, CalculatorAboutActivity.class)); - } + public static void showAbout(@Nonnull final Context context) { + context.startActivity(new Intent(context, CalculatorAboutActivity.class)); + } - public static void showFunctions(@Nonnull final Context context) { - showFunctions(context, false); - } + public static void showFunctions(@Nonnull final Context context) { + showFunctions(context, false); + } - public static void showFunctions(@Nonnull final Context context, boolean detached) { - final Intent intent = new Intent(context, CalculatorFunctionsActivity.class); - Android.addIntentFlags(intent, detached, context); - context.startActivity(intent); - } + public static void showFunctions(@Nonnull final Context context, boolean detached) { + final Intent intent = new Intent(context, CalculatorFunctionsActivity.class); + Android.addIntentFlags(intent, detached, context); + context.startActivity(intent); + } - public static void showOperators(@Nonnull final Context context) { - showOperators(context, false); - } + public static void showOperators(@Nonnull final Context context) { + showOperators(context, false); + } - public static void showOperators(@Nonnull final Context context, boolean detached) { - final Intent intent = new Intent(context, CalculatorOperatorsActivity.class); - Android.addIntentFlags(intent, detached, context); - context.startActivity(intent); - } + public static void showOperators(@Nonnull final Context context, boolean detached) { + final Intent intent = new Intent(context, CalculatorOperatorsActivity.class); + Android.addIntentFlags(intent, detached, context); + context.startActivity(intent); + } - public static void showVars(@Nonnull final Context context) { - showVars(context, false); - } + public static void showVars(@Nonnull final Context context) { + showVars(context, false); + } - public static void showVars(@Nonnull final Context context, boolean detached) { - final Intent intent = new Intent(context, CalculatorVarsActivity.class); - Android.addIntentFlags(intent, detached, context); - context.startActivity(intent); - } + public static void showVars(@Nonnull 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(@Nonnull final Context context) { - final Intent intent = new Intent(); - intent.setClass(context, CalculatorPlotActivity.class); - Android.addIntentFlags(intent, false, context); - context.startActivity(intent); - } + public static void plotGraph(@Nonnull final Context context) { + final Intent intent = new Intent(); + intent.setClass(context, CalculatorPlotActivity.class); + Android.addIntentFlags(intent, false, context); + context.startActivity(intent); + } - public static void tryCreateVar(@Nonnull final Context context) { - 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 ActionBarActivity) { - VarEditDialogFragment.showDialog(VarEditDialogFragment.Input.newFromValue(varValue), ((ActionBarActivity) 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); - } - } else { - getNotifier().showMessage(R.string.not_valid_result, MessageType.error); - } - } + public static void tryCreateVar(@Nonnull final Context context) { + 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 ActionBarActivity) { + VarEditDialogFragment.showDialog(VarEditDialogFragment.Input.newFromValue(varValue), ((ActionBarActivity) 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); + } + } else { + getNotifier().showMessage(R.string.not_valid_result, MessageType.error); + } + } - public static void tryCreateFunction(@Nonnull final Context context) { - final CalculatorDisplay display = Locator.getInstance().getDisplay(); - final CalculatorDisplayViewState viewState = display.getViewState(); + public static void tryCreateFunction(@Nonnull 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); + } + } - @Nonnull - private static CalculatorNotifier getNotifier() { - return Locator.getInstance().getNotifier(); - } + @Nonnull + 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(@Nonnull 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(@Nonnull 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(@Nonnull final Context context) { - final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(context.getString(R.string.cpp_share_link))); - Android.addIntentFlags(intent, false, context); - context.startActivity(intent); - } + public static void likeButtonPressed(@Nonnull final Context context) { + final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(context.getString(R.string.cpp_share_link))); + Android.addIntentFlags(intent, false, context); + context.startActivity(intent); + } - public static void showCalculationMessagesDialog(@Nonnull Context context, @Nonnull List messages) { - final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); + public static void showCalculationMessagesDialog(@Nonnull Context context, @Nonnull List messages) { + final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); - if (Preferences.Calculations.showCalculationMessagesDialog.getPreference(prefs)) { - FixableMessagesDialog.showDialogForMessages(messages, context, true); - } - } + if (Preferences.Calculations.showCalculationMessagesDialog.getPreference(prefs)) { + FixableMessagesDialog.showDialogForMessages(messages, context, true); + } + } - @Override - public void onCalculatorEvent(@Nonnull CalculatorEventData calculatorEventData, @Nonnull CalculatorEventType calculatorEventType, @Nullable Object data) { - final Context context; + public static void showEvaluationError(@Nonnull Context context, @Nonnull final String errorMessage) { + final LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE); - final Object source = calculatorEventData.getSource(); - if (source instanceof Context) { - context = ((Context) source); - } else { - context = App.getApplication(); - } + final View errorMessageView = layoutInflater.inflate(R.layout.display_error_message, null); + ((TextView) errorMessageView.findViewById(R.id.error_message_text_view)).setText(errorMessage); - 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; + final AlertDialog.Builder builder = new AlertDialog.Builder(context) + .setPositiveButton(R.string.c_cancel, null) + .setView(errorMessageView); - } - } + builder.create().show(); + } - public static void showEvaluationError(@Nonnull Context context, @Nonnull final String errorMessage) { - final LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE); + @Override + public void onCalculatorEvent(@Nonnull CalculatorEventData calculatorEventData, @Nonnull CalculatorEventType calculatorEventType, @Nullable Object data) { + final Context context; - final View errorMessageView = layoutInflater.inflate(R.layout.display_error_message, null); - ((TextView) errorMessageView.findViewById(R.id.error_message_text_view)).setText(errorMessage); + final Object source = calculatorEventData.getSource(); + if (source instanceof Context) { + context = ((Context) source); + } else { + context = App.getApplication(); + } - final AlertDialog.Builder builder = new AlertDialog.Builder(context) - .setPositiveButton(R.string.c_cancel, null) - .setView(errorMessageView); + 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; - builder.create().show(); - } + } + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/CalculatorActivityMobile.java b/android-app/src/main/java/org/solovyev/android/calculator/CalculatorActivityMobile.java index ba90ecec..10b05a94 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/CalculatorActivityMobile.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/CalculatorActivityMobile.java @@ -35,15 +35,15 @@ import javax.annotation.Nullable; */ public class CalculatorActivityMobile extends CalculatorActivity { - @Override - public void onCreate(@Nullable Bundle savedInstanceState) { - final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); - Preferences.Gui.layout.putPreference(prefs, Preferences.Gui.Layout.main_calculator_mobile); + @Override + public void onCreate(@Nullable Bundle savedInstanceState) { + final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); + Preferences.Gui.layout.putPreference(prefs, Preferences.Gui.Layout.main_calculator_mobile); - super.onCreate(savedInstanceState); + super.onCreate(savedInstanceState); - if (!CalculatorApplication.isMonkeyRunner(this)) { - this.finish(); - } - } + if (!CalculatorApplication.isMonkeyRunner(this)) { + this.finish(); + } + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/CalculatorApplication.java b/android-app/src/main/java/org/solovyev/android/calculator/CalculatorApplication.java index a5a6c1da..db8883c5 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/CalculatorApplication.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/CalculatorApplication.java @@ -55,34 +55,31 @@ import java.util.concurrent.TimeUnit; import javax.annotation.Nonnull; @ReportsCrashes(formKey = "", - formUri = "https://serso.cloudant.com/acra-cpp/_design/acra-storage/_update/report", - reportType = org.acra.sender.HttpSender.Type.JSON, - httpMethod = org.acra.sender.HttpSender.Method.PUT, - formUriBasicAuthLogin="timbeenterumisideffecird", - formUriBasicAuthPassword="ECL65PO2TH5quIFNAK4hQ5Ng", - mode = ReportingInteractionMode.TOAST, - resToastText = R.string.crashed) + formUri = "https://serso.cloudant.com/acra-cpp/_design/acra-storage/_update/report", + reportType = org.acra.sender.HttpSender.Type.JSON, + httpMethod = org.acra.sender.HttpSender.Method.PUT, + formUriBasicAuthLogin = "timbeenterumisideffecird", + formUriBasicAuthPassword = "ECL65PO2TH5quIFNAK4hQ5Ng", + mode = ReportingInteractionMode.TOAST, + resToastText = R.string.crashed) public class CalculatorApplication extends android.app.Application implements SharedPreferences.OnSharedPreferenceChangeListener { /* - ********************************************************************** + ********************************************************************** * * CONSTANTS * ********************************************************************** */ - @Nonnull - static final String MAIL = "se.solovyev@gmail.com"; - - private static final String TAG = "C++"; - - 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 = "ca-app-pub-2228934497384784/2916398892"; - - @Nonnull - private static CalculatorApplication instance; + 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 = "ca-app-pub-2228934497384784/2916398892"; + @Nonnull + static final String MAIL = "se.solovyev@gmail.com"; + private static final String TAG = "C++"; + @Nonnull + private static CalculatorApplication instance; /* ********************************************************************** @@ -91,17 +88,14 @@ public class CalculatorApplication extends android.app.Application implements Sh * ********************************************************************** */ + @Nonnull + protected final Handler uiHandler = new Handler(); + @Nonnull + private final List listeners = new ArrayList(); + @Nonnull + private final Wizards wizards = new CalculatorWizards(this); - @Nonnull - private final List listeners = new ArrayList(); - - @Nonnull - protected final Handler uiHandler = new Handler(); - - @Nonnull - private final Wizards wizards = new CalculatorWizards(this); - - private Typeface typeFace; + private Typeface typeFace; /* ********************************************************************** @@ -111,9 +105,9 @@ public class CalculatorApplication extends android.app.Application implements Sh ********************************************************************** */ - public CalculatorApplication() { - instance = this; - } + public CalculatorApplication() { + instance = this; + } /* ********************************************************************** @@ -123,131 +117,128 @@ public class CalculatorApplication extends android.app.Application implements Sh ********************************************************************** */ - @Override - public void onCreate() { - if (!BuildConfig.DEBUG) { - ACRA.init(this); - } else { - LeakCanary.install(this); - } + @Nonnull + public static CalculatorApplication getInstance() { + return instance; + } - if (!App.isInitialized()) { - App.init(this); - } + @Nonnull + public static SharedPreferences getPreferences() { + return PreferenceManager.getDefaultSharedPreferences(getInstance()); + } - final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); - Preferences.setDefaultValues(preferences); + public static boolean isMonkeyRunner(@Nonnull Context context) { + // NOTE: this code is only for monkeyrunner + return context.checkCallingOrSelfPermission(android.Manifest.permission.DISABLE_KEYGUARD) == PackageManager.PERMISSION_GRANTED; + } - preferences.registerOnSharedPreferenceChangeListener(this); + @Override + public void onCreate() { + if (!BuildConfig.DEBUG) { + ACRA.init(this); + } else { + LeakCanary.install(this); + } - setTheme(preferences); - setLanguageInitially(); + if (!App.isInitialized()) { + App.init(this); + } - super.onCreate(); - App.getLanguages().updateLanguage(this, true); + final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); + Preferences.setDefaultValues(preferences); - if (!Preferences.Ga.initialReportDone.getPreference(preferences)) { - App.getGa().reportInitially(preferences); - Preferences.Ga.initialReportDone.putPreference(preferences, true); - } + preferences.registerOnSharedPreferenceChangeListener(this); - final AndroidCalculator calculator = new AndroidCalculator(this); + setTheme(preferences); + setLanguageInitially(); - final EditorTextProcessor editorTextProcessor = new EditorTextProcessor(); + super.onCreate(); + App.getLanguages().updateLanguage(this, true); - 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 AndroidCalculatorPlotter(this, new CalculatorPlotterImpl(calculator)), - editorTextProcessor); + if (!Preferences.Ga.initialReportDone.getPreference(preferences)) { + App.getGa().reportInitially(preferences); + Preferences.Ga.initialReportDone.putPreference(preferences, true); + } - editorTextProcessor.init(this); + final AndroidCalculator calculator = new AndroidCalculator(this); - listeners.add(new CalculatorActivityLauncher()); - for (CalculatorEventListener listener : listeners) { - calculator.addCalculatorEventListener(listener); - } + final EditorTextProcessor editorTextProcessor = new EditorTextProcessor(); - calculator.addCalculatorEventListener(App.getBroadcaster()); + 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 AndroidCalculatorPlotter(this, new CalculatorPlotterImpl(calculator)), + editorTextProcessor); - Locator.getInstance().getCalculator().init(); + editorTextProcessor.init(this); - new Thread(new Runnable() { - @Override - public void run() { - 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); - } + listeners.add(new CalculatorActivityLauncher()); + for (CalculatorEventListener listener : listeners) { + calculator.addCalculatorEventListener(listener); + } - } - }).start(); + calculator.addCalculatorEventListener(App.getBroadcaster()); - Locator.getInstance().getLogger().debug(TAG, "Application started!"); - Locator.getInstance().getNotifier().showDebugMessage(TAG, "Application started!"); + Locator.getInstance().getCalculator().init(); - App.getUiThreadExecutor().execute(new Runnable() { - @Override - public void run() { - // we must update the widget when app starts - App.getBroadcaster().sendEditorStateChangedIntent(); - } - }, 100, TimeUnit.MILLISECONDS); - } + new Thread(new Runnable() { + @Override + public void run() { + 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); + } - private void setLanguageInitially() { - // should be called before onCreate() - final Language language = App.getLanguages().getCurrent(); - if (!language.isSystem() && !language.locale.equals(Locale.getDefault())) { - Locale.setDefault(language.locale); - } - } + } + }).start(); - private void setTheme(@Nonnull SharedPreferences preferences) { - final Preferences.Gui.Theme theme = Preferences.Gui.getTheme(preferences); - setTheme(theme.getThemeId()); - } + Locator.getInstance().getLogger().debug(TAG, "Application started!"); + Locator.getInstance().getNotifier().showDebugMessage(TAG, "Application started!"); - @Nonnull - public FragmentUi createFragmentHelper(int layoutId) { - return new FragmentUi(layoutId); - } + App.getUiThreadExecutor().execute(new Runnable() { + @Override + public void run() { + // we must update the widget when app starts + App.getBroadcaster().sendEditorStateChangedIntent(); + } + }, 100, TimeUnit.MILLISECONDS); + } - @Nonnull - public FragmentUi createFragmentHelper(int layoutId, int titleResId) { - return new FragmentUi(layoutId, titleResId); - } + private void setLanguageInitially() { + // should be called before onCreate() + final Language language = App.getLanguages().getCurrent(); + if (!language.isSystem() && !language.locale.equals(Locale.getDefault())) { + Locale.setDefault(language.locale); + } + } - @Nonnull - public FragmentUi createFragmentHelper(int layoutId, int titleResId, boolean listenersOnCreate) { - return new FragmentUi(layoutId, titleResId, listenersOnCreate); - } + private void setTheme(@Nonnull SharedPreferences preferences) { + final Preferences.Gui.Theme theme = Preferences.Gui.getTheme(preferences); + setTheme(theme.getThemeId()); + } - @Nonnull - public Handler getUiHandler() { - return uiHandler; - } + @Nonnull + public FragmentUi createFragmentHelper(int layoutId) { + return new FragmentUi(layoutId); + } - @Nonnull - public Wizards getWizards() { - return wizards; - } + @Nonnull + public FragmentUi createFragmentHelper(int layoutId, int titleResId) { + return new FragmentUi(layoutId, titleResId); + } - @Nonnull - public Typeface getTypeFace() { - if (typeFace == null) { - typeFace = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Regular.ttf"); - } - return typeFace; - } + @Nonnull + public FragmentUi createFragmentHelper(int layoutId, int titleResId, boolean listenersOnCreate) { + return new FragmentUi(layoutId, titleResId, listenersOnCreate); + } /* ********************************************************************** @@ -257,27 +248,30 @@ public class CalculatorApplication extends android.app.Application implements Sh ********************************************************************** */ - @Nonnull - public static CalculatorApplication getInstance() { - return instance; - } + @Nonnull + public Handler getUiHandler() { + return uiHandler; + } - @Nonnull - public static SharedPreferences getPreferences() { - return PreferenceManager.getDefaultSharedPreferences(getInstance()); - } + @Nonnull + public Wizards getWizards() { + return wizards; + } - public static boolean isMonkeyRunner(@Nonnull Context context) { - // NOTE: this code is only for monkeyrunner - return context.checkCallingOrSelfPermission(android.Manifest.permission.DISABLE_KEYGUARD) == PackageManager.PERMISSION_GRANTED; - } + @Nonnull + public Typeface getTypeFace() { + if (typeFace == null) { + typeFace = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Regular.ttf"); + } + return typeFace; + } - @Override - public void onSharedPreferenceChanged(SharedPreferences prefs, String key) { - if (Preferences.Onscreen.showAppIcon.getKey().equals(key)) { - boolean showAppIcon = Preferences.Onscreen.showAppIcon.getPreference(prefs); - Android.toggleComponent(this, CalculatorOnscreenStartActivity.class, showAppIcon); - Locator.getInstance().getNotifier().showMessage(R.string.cpp_this_change_may_require_reboot, MessageType.info); - } - } + @Override + public void onSharedPreferenceChanged(SharedPreferences prefs, String key) { + if (Preferences.Onscreen.showAppIcon.getKey().equals(key)) { + boolean showAppIcon = Preferences.Onscreen.showAppIcon.getPreference(prefs); + Android.toggleComponent(this, CalculatorOnscreenStartActivity.class, showAppIcon); + Locator.getInstance().getNotifier().showMessage(R.string.cpp_this_change_may_require_reboot, MessageType.info); + } + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/CalculatorBroadcaster.java b/android-app/src/main/java/org/solovyev/android/calculator/CalculatorBroadcaster.java index 662912d4..834c39fc 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/CalculatorBroadcaster.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/CalculatorBroadcaster.java @@ -9,48 +9,48 @@ import javax.annotation.Nullable; public final class CalculatorBroadcaster implements CalculatorEventListener, SharedPreferences.OnSharedPreferenceChangeListener { - public static final String ACTION_INIT = "org.solovyev.android.calculator.INIT"; - public static final String ACTION_EDITOR_STATE_CHANGED = "org.solovyev.android.calculator.EDITOR_STATE_CHANGED"; - public static final String ACTION_DISPLAY_STATE_CHANGED = "org.solovyev.android.calculator.DISPLAY_STATE_CHANGED"; - public static final String ACTION_THEME_CHANGED = "org.solovyev.android.calculator.THEME_CHANGED"; + public static final String ACTION_INIT = "org.solovyev.android.calculator.INIT"; + public static final String ACTION_EDITOR_STATE_CHANGED = "org.solovyev.android.calculator.EDITOR_STATE_CHANGED"; + public static final String ACTION_DISPLAY_STATE_CHANGED = "org.solovyev.android.calculator.DISPLAY_STATE_CHANGED"; + public static final String ACTION_THEME_CHANGED = "org.solovyev.android.calculator.THEME_CHANGED"; - @Nonnull - private final Context context; + @Nonnull + private final Context context; - public CalculatorBroadcaster(@Nonnull Context context, @Nonnull SharedPreferences preferences) { - this.context = context; - preferences.registerOnSharedPreferenceChangeListener(this); - } + public CalculatorBroadcaster(@Nonnull Context context, @Nonnull SharedPreferences preferences) { + this.context = context; + preferences.registerOnSharedPreferenceChangeListener(this); + } - @Override - public void onCalculatorEvent(@Nonnull CalculatorEventData calculatorEventData, @Nonnull CalculatorEventType calculatorEventType, @Nullable Object data) { - switch (calculatorEventType) { - case editor_state_changed: - case editor_state_changed_light: - sendEditorStateChangedIntent(); - break; - case display_state_changed: - sendDisplayStateChanged(); - break; - } - } + @Override + public void onCalculatorEvent(@Nonnull CalculatorEventData calculatorEventData, @Nonnull CalculatorEventType calculatorEventType, @Nullable Object data) { + switch (calculatorEventType) { + case editor_state_changed: + case editor_state_changed_light: + sendEditorStateChangedIntent(); + break; + case display_state_changed: + sendDisplayStateChanged(); + break; + } + } - public void sendDisplayStateChanged() { - sendBroadcastIntent(ACTION_DISPLAY_STATE_CHANGED); - } + public void sendDisplayStateChanged() { + sendBroadcastIntent(ACTION_DISPLAY_STATE_CHANGED); + } - public void sendEditorStateChangedIntent() { - sendBroadcastIntent(ACTION_EDITOR_STATE_CHANGED); - } + public void sendEditorStateChangedIntent() { + sendBroadcastIntent(ACTION_EDITOR_STATE_CHANGED); + } - public void sendBroadcastIntent(@Nonnull String action) { - context.sendBroadcast(new Intent(action)); - } + public void sendBroadcastIntent(@Nonnull String action) { + context.sendBroadcast(new Intent(action)); + } - @Override - public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { - if (Preferences.Gui.theme.isSameKey(key) || Preferences.Widget.theme.isSameKey(key)) { - sendBroadcastIntent(ACTION_THEME_CHANGED); - } - } + @Override + public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { + if (Preferences.Gui.theme.isSameKey(key) || Preferences.Widget.theme.isSameKey(key)) { + sendBroadcastIntent(ACTION_THEME_CHANGED); + } + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/CalculatorButton.java b/android-app/src/main/java/org/solovyev/android/calculator/CalculatorButton.java index 661d0bff..e4b60c56 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/CalculatorButton.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/CalculatorButton.java @@ -22,15 +22,19 @@ package org.solovyev.android.calculator; -import android.content.Context; import android.util.SparseArray; import javax.annotation.Nonnull; import javax.annotation.Nullable; -import java.util.HashMap; -import java.util.Map; -import static org.solovyev.android.calculator.CalculatorSpecialButton.*; +import static org.solovyev.android.calculator.CalculatorSpecialButton.cursor_left; +import static org.solovyev.android.calculator.CalculatorSpecialButton.cursor_right; +import static org.solovyev.android.calculator.CalculatorSpecialButton.functions_detached; +import static org.solovyev.android.calculator.CalculatorSpecialButton.history_detached; +import static org.solovyev.android.calculator.CalculatorSpecialButton.open_app; +import static org.solovyev.android.calculator.CalculatorSpecialButton.operators_detached; +import static org.solovyev.android.calculator.CalculatorSpecialButton.settings_detached; +import static org.solovyev.android.calculator.CalculatorSpecialButton.vars_detached; /** * User: serso @@ -39,114 +43,111 @@ import static org.solovyev.android.calculator.CalculatorSpecialButton.*; */ public enum CalculatorButton { - /*digits*/ - one(R.id.cpp_button_1, "1"), - two(R.id.cpp_button_2, "2"), - three(R.id.cpp_button_3, "3"), - four(R.id.cpp_button_4, "4"), - five(R.id.cpp_button_5, "5"), - six(R.id.cpp_button_6, "6"), - seven(R.id.cpp_button_7, "7"), - eight(R.id.cpp_button_8, "8"), - nine(R.id.cpp_button_9, "9"), - zero(R.id.cpp_button_0, "0"), + /*digits*/ + one(R.id.cpp_button_1, "1"), + two(R.id.cpp_button_2, "2"), + three(R.id.cpp_button_3, "3"), + four(R.id.cpp_button_4, "4"), + five(R.id.cpp_button_5, "5"), + six(R.id.cpp_button_6, "6"), + seven(R.id.cpp_button_7, "7"), + eight(R.id.cpp_button_8, "8"), + nine(R.id.cpp_button_9, "9"), + zero(R.id.cpp_button_0, "0"), - period(R.id.cpp_button_period, "."), - brackets(R.id.cpp_button_round_brackets, "()"), + period(R.id.cpp_button_period, "."), + brackets(R.id.cpp_button_round_brackets, "()"), - settings(R.id.cpp_button_settings, settings_detached), - like(R.id.cpp_button_like, CalculatorSpecialButton.like), + settings(R.id.cpp_button_settings, settings_detached), + like(R.id.cpp_button_like, CalculatorSpecialButton.like), - /*last row*/ - left(R.id.cpp_button_left, cursor_left), - right(R.id.cpp_button_right, cursor_right), - vars(R.id.cpp_button_vars, vars_detached), - functions(R.id.cpp_button_functions, functions_detached), - operators(R.id.cpp_button_operators, operators_detached), - app(R.id.cpp_button_app, open_app), - history(R.id.cpp_button_history, history_detached), + /*last row*/ + left(R.id.cpp_button_left, cursor_left), + right(R.id.cpp_button_right, cursor_right), + vars(R.id.cpp_button_vars, vars_detached), + functions(R.id.cpp_button_functions, functions_detached), + operators(R.id.cpp_button_operators, operators_detached), + app(R.id.cpp_button_app, open_app), + history(R.id.cpp_button_history, history_detached), - /*operations*/ - multiplication(R.id.cpp_button_multiplication, "*"), - division(R.id.cpp_button_division, "/"), - plus(R.id.cpp_button_plus, "+"), - subtraction(R.id.cpp_button_subtraction, "−"), - percent(R.id.cpp_button_percent, "%"), - power(R.id.cpp_button_power, "^"), + /*operations*/ + multiplication(R.id.cpp_button_multiplication, "*"), + division(R.id.cpp_button_division, "/"), + plus(R.id.cpp_button_plus, "+"), + subtraction(R.id.cpp_button_subtraction, "−"), + percent(R.id.cpp_button_percent, "%"), + power(R.id.cpp_button_power, "^"), - /*last column*/ - clear(R.id.cpp_button_clear, CalculatorSpecialButton.clear), - erase(R.id.cpp_button_erase, CalculatorSpecialButton.erase, CalculatorSpecialButton.clear), - copy(R.id.cpp_button_copy, CalculatorSpecialButton.copy), - paste(R.id.cpp_button_paste, CalculatorSpecialButton.paste), + /*last column*/ + clear(R.id.cpp_button_clear, CalculatorSpecialButton.clear), + erase(R.id.cpp_button_erase, CalculatorSpecialButton.erase, CalculatorSpecialButton.clear), + copy(R.id.cpp_button_copy, CalculatorSpecialButton.copy), + paste(R.id.cpp_button_paste, CalculatorSpecialButton.paste), - /*equals*/ - equals(R.id.cpp_button_equals, CalculatorSpecialButton.equals); + /*equals*/ + equals(R.id.cpp_button_equals, CalculatorSpecialButton.equals); - private final int buttonId; + @Nonnull + private static SparseArray buttonsByIds = new SparseArray<>(); + private final int buttonId; + @Nonnull + private final String onClickText; + @Nullable + private final String onLongClickText; - @Nonnull - private final String onClickText; + CalculatorButton(int buttonId, @Nonnull CalculatorSpecialButton onClickButton, @Nullable CalculatorSpecialButton onLongClickButton) { + this(buttonId, onClickButton.getActionCode(), onLongClickButton == null ? null : onLongClickButton.getActionCode()); + } - @Nullable - private final String onLongClickText; + CalculatorButton(int buttonId, @Nonnull CalculatorSpecialButton onClickButton) { + this(buttonId, onClickButton, null); + } - @Nonnull - private static SparseArray buttonsByIds = new SparseArray<>(); + CalculatorButton(int buttonId, @Nonnull String onClickText, @Nullable String onLongClickText) { + this.buttonId = buttonId; + this.onClickText = onClickText; + this.onLongClickText = onLongClickText; - CalculatorButton(int buttonId, @Nonnull CalculatorSpecialButton onClickButton, @Nullable CalculatorSpecialButton onLongClickButton) { - this(buttonId, onClickButton.getActionCode(), onLongClickButton == null ? null : onLongClickButton.getActionCode()); - } + } - CalculatorButton(int buttonId, @Nonnull CalculatorSpecialButton onClickButton) { - this(buttonId, onClickButton, null); - } + CalculatorButton(int buttonId, @Nonnull String onClickText) { + this(buttonId, onClickText, null); + } - CalculatorButton(int buttonId, @Nonnull String onClickText, @Nullable String onLongClickText) { - this.buttonId = buttonId; - this.onClickText = onClickText; - this.onLongClickText = onLongClickText; + @Nullable + public static CalculatorButton getById(int buttonId) { + initButtonsByIdsMap(); - } + return buttonsByIds.get(buttonId); + } - CalculatorButton(int buttonId, @Nonnull String onClickText) { - this(buttonId, onClickText, null); - } + private static void initButtonsByIdsMap() { + if (buttonsByIds.size() == 0) { + // if not initialized - public void onLongClick() { - if (onLongClickText != null) { - Locator.getInstance().getKeyboard().buttonPressed(onLongClickText); - } - } + final CalculatorButton[] calculatorButtons = values(); - public void onClick() { - Locator.getInstance().getKeyboard().buttonPressed(onClickText); - } + final SparseArray localButtonsByIds = new SparseArray<>(); + for (CalculatorButton calculatorButton : calculatorButtons) { + localButtonsByIds.append(calculatorButton.getButtonId(), calculatorButton); + } - @Nullable - public static CalculatorButton getById(int buttonId) { - initButtonsByIdsMap(); + buttonsByIds = localButtonsByIds; + } + } - return buttonsByIds.get(buttonId); - } + public void onLongClick() { + if (onLongClickText != null) { + Locator.getInstance().getKeyboard().buttonPressed(onLongClickText); + } + } - private static void initButtonsByIdsMap() { - if (buttonsByIds.size() == 0) { - // if not initialized + public void onClick() { + Locator.getInstance().getKeyboard().buttonPressed(onClickText); + } - final CalculatorButton[] calculatorButtons = values(); - - final SparseArray localButtonsByIds = new SparseArray<>(); - for (CalculatorButton calculatorButton : calculatorButtons) { - localButtonsByIds.append(calculatorButton.getButtonId(), calculatorButton); - } - - buttonsByIds = localButtonsByIds; - } - } - - public int getButtonId() { - return buttonId; - } + public int getButtonId() { + return buttonId; + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/CalculatorButtons.java b/android-app/src/main/java/org/solovyev/android/calculator/CalculatorButtons.java index 361a7825..5b5b43e7 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/CalculatorButtons.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/CalculatorButtons.java @@ -33,22 +33,23 @@ import android.view.MotionEvent; import android.view.View; import android.widget.Button; import android.widget.RemoteViews; -import jscl.AngleUnit; -import jscl.NumeralBase; import org.solovyev.android.Views; -import org.solovyev.android.calculator.model.AndroidCalculatorEngine; -import org.solovyev.android.calculator.view.AngleUnitsButton; -import org.solovyev.android.calculator.view.NumeralBasesButton; import org.solovyev.android.calculator.drag.DragButton; import org.solovyev.android.calculator.drag.DragDirection; import org.solovyev.android.calculator.drag.SimpleDragListener; +import org.solovyev.android.calculator.model.AndroidCalculatorEngine; +import org.solovyev.android.calculator.view.AngleUnitsButton; +import org.solovyev.android.calculator.view.NumeralBasesButton; import org.solovyev.android.calculator.view.ScreenMetrics; import org.solovyev.common.math.Point2d; import javax.annotation.Nonnull; import javax.annotation.Nullable; +import jscl.AngleUnit; +import jscl.NumeralBase; + /** * User: serso * Date: 9/28/12 @@ -56,243 +57,243 @@ import javax.annotation.Nullable; */ public final class CalculatorButtons { - private CalculatorButtons() { - } + private CalculatorButtons() { + } - public static void fixButtonsTextSize(@Nonnull Preferences.Gui.Theme theme, - @Nonnull Preferences.Gui.Layout layout, - @Nonnull View root) { - if (!layout.isOptimized()) { + public static void fixButtonsTextSize(@Nonnull Preferences.Gui.Theme theme, + @Nonnull Preferences.Gui.Layout layout, + @Nonnull View root) { + if (!layout.isOptimized()) { - final ScreenMetrics metrics = App.getScreenMetrics(); - final boolean portrait = metrics.isInPortraitMode(); - final int buttonsCount = portrait ? 5 : 4; - final int buttonsWeight = portrait ? (2 + 1 + buttonsCount) : (2 + buttonsCount); - final int buttonSize = metrics.getHeightPxs() / buttonsWeight; - final int textSize = 5 * buttonSize / 12; + final ScreenMetrics metrics = App.getScreenMetrics(); + final boolean portrait = metrics.isInPortraitMode(); + final int buttonsCount = portrait ? 5 : 4; + final int buttonsWeight = portrait ? (2 + 1 + buttonsCount) : (2 + buttonsCount); + final int buttonSize = metrics.getHeightPxs() / buttonsWeight; + final int textSize = 5 * buttonSize / 12; - Views.processViewsOfType(root, DragButton.class, new Views.ViewProcessor() { - @Override - public void process(@Nonnull DragButton button) { - button.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize); - } - }); - } - } + Views.processViewsOfType(root, DragButton.class, new Views.ViewProcessor() { + @Override + public void process(@Nonnull DragButton button) { + button.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize); + } + }); + } + } - static void initMultiplicationButton(@Nonnull View root) { - final View multiplicationButton = root.findViewById(R.id.cpp_button_multiplication); - if (multiplicationButton instanceof Button) { - ((Button) multiplicationButton).setText(Locator.getInstance().getEngine().getMultiplicationSign()); - } - } + static void initMultiplicationButton(@Nonnull View root) { + final View multiplicationButton = root.findViewById(R.id.cpp_button_multiplication); + if (multiplicationButton instanceof Button) { + ((Button) multiplicationButton).setText(Locator.getInstance().getEngine().getMultiplicationSign()); + } + } - public static void initMultiplicationButton(@Nonnull RemoteViews views) { - views.setTextViewText(R.id.cpp_button_multiplication, Locator.getInstance().getEngine().getMultiplicationSign()); - } + public static void initMultiplicationButton(@Nonnull RemoteViews views) { + views.setTextViewText(R.id.cpp_button_multiplication, Locator.getInstance().getEngine().getMultiplicationSign()); + } - public static void toggleEqualsButton(@Nullable SharedPreferences preferences, - @Nonnull Activity activity) { - preferences = preferences == null ? PreferenceManager.getDefaultSharedPreferences(activity) : preferences; + public static void toggleEqualsButton(@Nullable SharedPreferences preferences, + @Nonnull Activity activity) { + preferences = preferences == null ? PreferenceManager.getDefaultSharedPreferences(activity) : preferences; - final boolean large = App.isLargeScreen() && Preferences.Gui.getLayout(preferences).isOptimized(); + final boolean large = App.isLargeScreen() && Preferences.Gui.getLayout(preferences).isOptimized(); - if (!large) { - if (Views.getScreenOrientation(activity) == Configuration.ORIENTATION_PORTRAIT - || !Preferences.Gui.autoOrientation.getPreference(preferences)) { + if (!large) { + if (Views.getScreenOrientation(activity) == Configuration.ORIENTATION_PORTRAIT + || !Preferences.Gui.autoOrientation.getPreference(preferences)) { - final DragButton equalsButton = (DragButton) activity.findViewById(R.id.cpp_button_equals); - if (equalsButton != null) { - if (Preferences.Gui.showEqualsButton.getPreference(preferences)) { - equalsButton.setVisibility(View.VISIBLE); - } else { - equalsButton.setVisibility(View.GONE); - } - } - } - } - } + final DragButton equalsButton = (DragButton) activity.findViewById(R.id.cpp_button_equals); + if (equalsButton != null) { + if (Preferences.Gui.showEqualsButton.getPreference(preferences)) { + equalsButton.setVisibility(View.VISIBLE); + } else { + equalsButton.setVisibility(View.GONE); + } + } + } + } + } /* - ********************************************************************** + ********************************************************************** * * STATIC CLASSES * ********************************************************************** */ - static class RoundBracketsDragProcessor implements SimpleDragListener.DragProcessor { + @Nonnull + private static CalculatorKeyboard getKeyboard() { + return Locator.getInstance().getKeyboard(); + } - @Nonnull - private final DigitButtonDragProcessor upDownProcessor = new DigitButtonDragProcessor(getKeyboard()); + static class RoundBracketsDragProcessor implements SimpleDragListener.DragProcessor { - @Override - public boolean processDragEvent(@Nonnull DragDirection dragDirection, @Nonnull DragButton dragButton, @Nonnull Point2d startPoint2d, @Nonnull MotionEvent motionEvent) { - final boolean result; + @Nonnull + private final DigitButtonDragProcessor upDownProcessor = new DigitButtonDragProcessor(getKeyboard()); - if (dragDirection == DragDirection.left) { - App.getVibrator().vibrate(); - getKeyboard().roundBracketsButtonPressed(); - result = true; - } else { - result = upDownProcessor.processDragEvent(dragDirection, dragButton, startPoint2d, motionEvent); - } + @Override + public boolean processDragEvent(@Nonnull DragDirection dragDirection, @Nonnull DragButton dragButton, @Nonnull Point2d startPoint2d, @Nonnull MotionEvent motionEvent) { + final boolean result; - return result; - } - } + if (dragDirection == DragDirection.left) { + App.getVibrator().vibrate(); + getKeyboard().roundBracketsButtonPressed(); + result = true; + } else { + result = upDownProcessor.processDragEvent(dragDirection, dragButton, startPoint2d, motionEvent); + } - @Nonnull - private static CalculatorKeyboard getKeyboard() { - return Locator.getInstance().getKeyboard(); - } + return result; + } + } - static class VarsDragProcessor implements SimpleDragListener.DragProcessor { + static class VarsDragProcessor implements SimpleDragListener.DragProcessor { - @Nonnull - private Context context; + @Nonnull + private Context context; - VarsDragProcessor(@Nonnull Context context) { - this.context = context; - } + VarsDragProcessor(@Nonnull Context context) { + this.context = context; + } - @Override - public boolean processDragEvent(@Nonnull DragDirection dragDirection, - @Nonnull DragButton dragButton, - @Nonnull Point2d startPoint2d, - @Nonnull MotionEvent motionEvent) { - boolean result = false; + @Override + public boolean processDragEvent(@Nonnull DragDirection dragDirection, + @Nonnull DragButton dragButton, + @Nonnull Point2d startPoint2d, + @Nonnull MotionEvent motionEvent) { + boolean result = false; - if (dragDirection == DragDirection.up) { - App.getVibrator().vibrate(); - Locator.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.show_create_var_dialog, null, context); - result = true; - }/* else if (dragDirection == DragDirection.down) { + if (dragDirection == DragDirection.up) { + App.getVibrator().vibrate(); + Locator.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.show_create_var_dialog, null, context); + result = true; + }/* else if (dragDirection == DragDirection.down) { Locator.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.show_create_matrix_dialog, null, context); result = true; }*/ - return result; - } - } + return result; + } + } - static class AngleUnitsChanger implements SimpleDragListener.DragProcessor { + static class AngleUnitsChanger implements SimpleDragListener.DragProcessor { - @Nonnull - private final DigitButtonDragProcessor processor; + @Nonnull + private final DigitButtonDragProcessor processor; - @Nonnull - private final Context context; + @Nonnull + private final Context context; - AngleUnitsChanger(@Nonnull Context context) { - this.context = context; - this.processor = new DigitButtonDragProcessor(Locator.getInstance().getKeyboard()); - } + AngleUnitsChanger(@Nonnull Context context) { + this.context = context; + this.processor = new DigitButtonDragProcessor(Locator.getInstance().getKeyboard()); + } - @Override - public boolean processDragEvent(@Nonnull DragDirection dragDirection, - @Nonnull DragButton dragButton, - @Nonnull Point2d startPoint2d, - @Nonnull MotionEvent motionEvent) { - boolean result = false; + @Override + public boolean processDragEvent(@Nonnull DragDirection dragDirection, + @Nonnull DragButton dragButton, + @Nonnull Point2d startPoint2d, + @Nonnull MotionEvent motionEvent) { + boolean result = false; - if (dragButton instanceof AngleUnitsButton) { - if (dragDirection != DragDirection.left) { - final String directionText = ((AngleUnitsButton) dragButton).getText(dragDirection); - if (directionText != null) { - try { + if (dragButton instanceof AngleUnitsButton) { + if (dragDirection != DragDirection.left) { + final String directionText = ((AngleUnitsButton) dragButton).getText(dragDirection); + if (directionText != null) { + try { - final AngleUnit angleUnits = AngleUnit.valueOf(directionText); + final AngleUnit angleUnits = AngleUnit.valueOf(directionText); - final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); + final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); - final AngleUnit oldAngleUnits = AndroidCalculatorEngine.Preferences.angleUnit.getPreference(preferences); - if (oldAngleUnits != angleUnits) { - App.getVibrator().vibrate(); - Locator.getInstance().getPreferenceService().setAngleUnits(angleUnits); - } + final AngleUnit oldAngleUnits = AndroidCalculatorEngine.Preferences.angleUnit.getPreference(preferences); + if (oldAngleUnits != angleUnits) { + App.getVibrator().vibrate(); + Locator.getInstance().getPreferenceService().setAngleUnits(angleUnits); + } - result = true; - } catch (IllegalArgumentException e) { - Log.d(this.getClass().getName(), "Unsupported angle units: " + directionText); - } - } - } else if (dragDirection == DragDirection.left) { - result = processor.processDragEvent(dragDirection, dragButton, startPoint2d, motionEvent); - } - } + result = true; + } catch (IllegalArgumentException e) { + Log.d(this.getClass().getName(), "Unsupported angle units: " + directionText); + } + } + } else if (dragDirection == DragDirection.left) { + result = processor.processDragEvent(dragDirection, dragButton, startPoint2d, motionEvent); + } + } - return result; - } - } + return result; + } + } - static class NumeralBasesChanger implements SimpleDragListener.DragProcessor { + static class NumeralBasesChanger implements SimpleDragListener.DragProcessor { - @Nonnull - private final Context context; + @Nonnull + private final Context context; - NumeralBasesChanger(@Nonnull Context context) { - this.context = context; - } + NumeralBasesChanger(@Nonnull Context context) { + this.context = context; + } - @Override - public boolean processDragEvent(@Nonnull DragDirection dragDirection, - @Nonnull DragButton dragButton, - @Nonnull Point2d startPoint2d, - @Nonnull MotionEvent motionEvent) { - boolean result = false; + @Override + public boolean processDragEvent(@Nonnull DragDirection dragDirection, + @Nonnull DragButton dragButton, + @Nonnull Point2d startPoint2d, + @Nonnull MotionEvent motionEvent) { + boolean result = false; - if (dragButton instanceof NumeralBasesButton) { - final String directionText = ((NumeralBasesButton) dragButton).getText(dragDirection); - if (directionText != null) { - try { + if (dragButton instanceof NumeralBasesButton) { + final String directionText = ((NumeralBasesButton) dragButton).getText(dragDirection); + if (directionText != null) { + try { - final NumeralBase numeralBase = NumeralBase.valueOf(directionText); + final NumeralBase numeralBase = NumeralBase.valueOf(directionText); - final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); + final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); - final NumeralBase oldNumeralBase = AndroidCalculatorEngine.Preferences.numeralBase.getPreference(preferences); - if (oldNumeralBase != numeralBase) { - App.getVibrator().vibrate(); - Locator.getInstance().getPreferenceService().setNumeralBase(numeralBase); - } + final NumeralBase oldNumeralBase = AndroidCalculatorEngine.Preferences.numeralBase.getPreference(preferences); + if (oldNumeralBase != numeralBase) { + App.getVibrator().vibrate(); + Locator.getInstance().getPreferenceService().setNumeralBase(numeralBase); + } - result = true; - } catch (IllegalArgumentException e) { - Log.d(this.getClass().getName(), "Unsupported numeral base: " + directionText); - } - } - } + result = true; + } catch (IllegalArgumentException e) { + Log.d(this.getClass().getName(), "Unsupported numeral base: " + directionText); + } + } + } - return result; - } - } + return result; + } + } - static class FunctionsDragProcessor implements SimpleDragListener.DragProcessor { + static class FunctionsDragProcessor implements SimpleDragListener.DragProcessor { - @Nonnull - private Context context; + @Nonnull + private Context context; - FunctionsDragProcessor(@Nonnull Context context) { - this.context = context; - } + FunctionsDragProcessor(@Nonnull Context context) { + this.context = context; + } - @Override - public boolean processDragEvent(@Nonnull DragDirection dragDirection, - @Nonnull DragButton dragButton, - @Nonnull Point2d startPoint2d, - @Nonnull MotionEvent motionEvent) { - boolean result = false; + @Override + public boolean processDragEvent(@Nonnull DragDirection dragDirection, + @Nonnull DragButton dragButton, + @Nonnull Point2d startPoint2d, + @Nonnull MotionEvent motionEvent) { + boolean result = false; - if (dragDirection == DragDirection.up) { - App.getVibrator().vibrate(); - Locator.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.show_create_function_dialog, null, context); - result = true; - } + if (dragDirection == DragDirection.up) { + App.getVibrator().vibrate(); + Locator.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.show_create_function_dialog, null, context); + result = true; + } - return result; - } - } + return result; + } + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/CalculatorDialogActivity.java b/android-app/src/main/java/org/solovyev/android/calculator/CalculatorDialogActivity.java index b22c4c92..894c6bc4 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/CalculatorDialogActivity.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/CalculatorDialogActivity.java @@ -26,21 +26,20 @@ import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Parcelable; +import android.support.v7.app.ActionBarActivity; import android.text.method.ScrollingMovementMethod; import android.view.View; import android.widget.Button; import android.widget.TextView; -import android.support.v7.app.ActionBarActivity; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - import org.solovyev.android.Android; import org.solovyev.android.fragments.FragmentUtils; import org.solovyev.common.msg.MessageType; import org.solovyev.common.text.Strings; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + /** * User: serso * Date: 1/20/13 @@ -48,106 +47,106 @@ import org.solovyev.common.text.Strings; */ public class CalculatorDialogActivity extends ActionBarActivity { - @Nonnull - private static final String TAG = CalculatorDialogActivity.class.getSimpleName(); + @Nonnull + private static final String TAG = CalculatorDialogActivity.class.getSimpleName(); - @Nonnull - private static final String DIALOG_DATA_EXTRA = "dialog_data"; + @Nonnull + private static final String DIALOG_DATA_EXTRA = "dialog_data"; - public static void showDialog(@Nonnull Context context, @Nonnull 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(@Nonnull Context context, @Nonnull 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); + @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; + } + } - 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); + return null; + } - final String title = dialogData.getTitle(); - if (!Strings.isEmpty(title)) { - setTitle(title); - } + @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; + } + + @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 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; - } - } + public static class CalculatorDialogFragment extends CalculatorFragment { - return null; - } + public CalculatorDialogFragment() { + super(CalculatorFragmentType.dialog); + } - @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; - } - } + @Override + public void onViewCreated(@Nonnull View root, Bundle savedInstanceState) { + super.onViewCreated(root, savedInstanceState); - return null; - } + final DialogData dialogData = readDialogData(getArguments()); - public static class CalculatorDialogFragment extends CalculatorFragment { + if (dialogData != null) { + final TextView messageTextView = (TextView) root.findViewById(R.id.cpp_dialog_message_textview); + messageTextView.setMovementMethod(ScrollingMovementMethod.getInstance()); + messageTextView.setText(dialogData.getMessage()); - public CalculatorDialogFragment() { - super(CalculatorFragmentType.dialog); - } + 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)); + } + }); - @Override - public void onViewCreated(@Nonnull View root, Bundle savedInstanceState) { - super.onViewCreated(root, savedInstanceState); + } + } - 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.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(); + } + }); + } + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/CalculatorDisplayFragment.java b/android-app/src/main/java/org/solovyev/android/calculator/CalculatorDisplayFragment.java index ee30cf2c..6406bc4f 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/CalculatorDisplayFragment.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/CalculatorDisplayFragment.java @@ -25,12 +25,11 @@ package org.solovyev.android.calculator; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; +import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; -import android.support.v4.app.Fragment; - import javax.annotation.Nonnull; /** @@ -40,72 +39,72 @@ import javax.annotation.Nonnull; */ public class CalculatorDisplayFragment extends Fragment { - @Nonnull - private FragmentUi fragmentUi; - @Nonnull - private AndroidCalculatorDisplayView displayView; + @Nonnull + private FragmentUi fragmentUi; + @Nonnull + private AndroidCalculatorDisplayView displayView; - @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 Preferences.Gui.Layout layout = Preferences.Gui.getLayout(prefs); - if (!layout.isOptimized()) { - fragmentUi = CalculatorApplication.getInstance().createFragmentHelper(R.layout.cpp_app_display_mobile, R.string.result); - } else { - fragmentUi = CalculatorApplication.getInstance().createFragmentHelper(R.layout.cpp_app_display, R.string.result); - } + final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.getActivity()); + final Preferences.Gui.Layout layout = Preferences.Gui.getLayout(prefs); + if (!layout.isOptimized()) { + fragmentUi = CalculatorApplication.getInstance().createFragmentHelper(R.layout.cpp_app_display_mobile, R.string.result); + } else { + fragmentUi = CalculatorApplication.getInstance().createFragmentHelper(R.layout.cpp_app_display, R.string.result); + } - fragmentUi.onCreate(this); - } + fragmentUi.onCreate(this); + } - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - return fragmentUi.onCreateView(this, inflater, container); - } + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + return fragmentUi.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); - displayView = (AndroidCalculatorDisplayView) root.findViewById(R.id.calculator_display); - displayView.init(getActivity()); - Locator.getInstance().getDisplay().setView(displayView); + displayView = (AndroidCalculatorDisplayView) root.findViewById(R.id.calculator_display); + displayView.init(getActivity()); + Locator.getInstance().getDisplay().setView(displayView); - fragmentUi.onViewCreated(this, root); - } + fragmentUi.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(); - fragmentUi.onResume(this); - } + fragmentUi.onResume(this); + } - @Override - public void onPause() { - fragmentUi.onPause(this); + @Override + public void onPause() { + fragmentUi.onPause(this); - super.onPause(); - } + super.onPause(); + } - @Override - public void onDestroyView() { - Locator.getInstance().getDisplay().clearView(displayView); - fragmentUi.onDestroyView(this); - super.onDestroyView(); - } + @Override + public void onDestroyView() { + Locator.getInstance().getDisplay().clearView(displayView); + fragmentUi.onDestroyView(this); + super.onDestroyView(); + } - @Override - public void onDestroy() { - fragmentUi.onDestroy(this); + @Override + public void onDestroy() { + fragmentUi.onDestroy(this); - super.onDestroy(); - } + super.onDestroy(); + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/CalculatorDisplayMenuItem.java b/android-app/src/main/java/org/solovyev/android/calculator/CalculatorDisplayMenuItem.java index 5adcff22..24ac3253 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/CalculatorDisplayMenuItem.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/CalculatorDisplayMenuItem.java @@ -23,7 +23,7 @@ package org.solovyev.android.calculator; import android.content.Context; -import jscl.math.Generic; + import org.solovyev.android.calculator.jscl.JsclOperation; import org.solovyev.android.calculator.plot.CalculatorPlotter; import org.solovyev.android.calculator.view.NumeralBaseConverterDialog; @@ -31,6 +31,8 @@ import org.solovyev.android.menu.LabeledMenuItem; import javax.annotation.Nonnull; +import jscl.math.Generic; + /** * User: Solovyev_S * Date: 21.09.12 @@ -38,99 +40,99 @@ import javax.annotation.Nonnull; */ public enum CalculatorDisplayMenuItem implements LabeledMenuItem { - copy(R.string.c_copy) { - @Override - public void onClick(@Nonnull CalculatorDisplayViewState data, @Nonnull Context context) { - Locator.getInstance().getKeyboard().copyButtonPressed(); - } - }, + copy(R.string.c_copy) { + @Override + public void onClick(@Nonnull CalculatorDisplayViewState data, @Nonnull Context context) { + Locator.getInstance().getKeyboard().copyButtonPressed(); + } + }, - convert_to_bin(R.string.convert_to_bin) { - @Override - public void onClick(@Nonnull CalculatorDisplayViewState data, @Nonnull Context context) { - ConversionMenuItem.convert_to_bin.onClick(data, context); - } + convert_to_bin(R.string.convert_to_bin) { + @Override + public void onClick(@Nonnull CalculatorDisplayViewState data, @Nonnull Context context) { + ConversionMenuItem.convert_to_bin.onClick(data, context); + } - @Override - protected boolean isItemVisibleFor(@Nonnull Generic generic, @Nonnull JsclOperation operation) { - return ConversionMenuItem.convert_to_bin.isItemVisibleFor(generic, operation); - } - }, + @Override + protected boolean isItemVisibleFor(@Nonnull Generic generic, @Nonnull JsclOperation operation) { + return ConversionMenuItem.convert_to_bin.isItemVisibleFor(generic, operation); + } + }, - convert_to_dec(R.string.convert_to_dec) { - @Override - public void onClick(@Nonnull CalculatorDisplayViewState data, @Nonnull Context context) { - ConversionMenuItem.convert_to_dec.onClick(data, context); - } + convert_to_dec(R.string.convert_to_dec) { + @Override + public void onClick(@Nonnull CalculatorDisplayViewState data, @Nonnull Context context) { + ConversionMenuItem.convert_to_dec.onClick(data, context); + } - @Override - protected boolean isItemVisibleFor(@Nonnull Generic generic, @Nonnull JsclOperation operation) { - return ConversionMenuItem.convert_to_dec.isItemVisibleFor(generic, operation); - } - }, + @Override + protected boolean isItemVisibleFor(@Nonnull Generic generic, @Nonnull JsclOperation operation) { + return ConversionMenuItem.convert_to_dec.isItemVisibleFor(generic, operation); + } + }, - convert_to_hex(R.string.convert_to_hex) { - @Override - public void onClick(@Nonnull CalculatorDisplayViewState data, @Nonnull Context context) { - ConversionMenuItem.convert_to_hex.onClick(data, context); - } + convert_to_hex(R.string.convert_to_hex) { + @Override + public void onClick(@Nonnull CalculatorDisplayViewState data, @Nonnull Context context) { + ConversionMenuItem.convert_to_hex.onClick(data, context); + } - @Override - protected boolean isItemVisibleFor(@Nonnull Generic generic, @Nonnull JsclOperation operation) { - return ConversionMenuItem.convert_to_hex.isItemVisibleFor(generic, operation); - } - }, + @Override + protected boolean isItemVisibleFor(@Nonnull Generic generic, @Nonnull JsclOperation operation) { + return ConversionMenuItem.convert_to_hex.isItemVisibleFor(generic, operation); + } + }, - convert(R.string.c_convert) { - @Override - public void onClick(@Nonnull CalculatorDisplayViewState data, @Nonnull Context context) { - final Generic result = data.getResult(); - if (result != null) { - new NumeralBaseConverterDialog(result.toString()).show(context); - } - } + convert(R.string.c_convert) { + @Override + public void onClick(@Nonnull CalculatorDisplayViewState data, @Nonnull Context context) { + final Generic result = data.getResult(); + if (result != null) { + new NumeralBaseConverterDialog(result.toString()).show(context); + } + } - @Override - protected boolean isItemVisibleFor(@Nonnull Generic generic, @Nonnull JsclOperation operation) { - return operation == JsclOperation.numeric && generic.getConstants().isEmpty(); - } - }, + @Override + protected boolean isItemVisibleFor(@Nonnull Generic generic, @Nonnull JsclOperation operation) { + return operation == JsclOperation.numeric && generic.getConstants().isEmpty(); + } + }, - plot(R.string.c_plot) { - @Override - public void onClick(@Nonnull CalculatorDisplayViewState data, @Nonnull Context context) { - final Generic expression = data.getResult(); - if (expression == null) throw new AssertionError(); + plot(R.string.c_plot) { + @Override + public void onClick(@Nonnull CalculatorDisplayViewState data, @Nonnull Context context) { + final Generic expression = data.getResult(); + if (expression == null) throw new AssertionError(); - final CalculatorPlotter plotter = Locator.getInstance().getPlotter(); - plotter.plot(expression); - } + final CalculatorPlotter plotter = Locator.getInstance().getPlotter(); + plotter.plot(expression); + } - @Override - protected boolean isItemVisibleFor(@Nonnull Generic generic, @Nonnull JsclOperation operation) { - return Locator.getInstance().getPlotter().isPlotPossibleFor(generic); - } + @Override + protected boolean isItemVisibleFor(@Nonnull Generic generic, @Nonnull JsclOperation operation) { + return Locator.getInstance().getPlotter().isPlotPossibleFor(generic); + } - }; + }; - private final int captionId; + private final int captionId; - CalculatorDisplayMenuItem(int captionId) { - this.captionId = captionId; - } + CalculatorDisplayMenuItem(int captionId) { + this.captionId = captionId; + } - public final boolean isItemVisible(@Nonnull CalculatorDisplayViewState displayViewState) { - //noinspection ConstantConditions - return displayViewState.isValid() && displayViewState.getResult() != null && isItemVisibleFor(displayViewState.getResult(), displayViewState.getOperation()); - } + public final boolean isItemVisible(@Nonnull CalculatorDisplayViewState displayViewState) { + //noinspection ConstantConditions + return displayViewState.isValid() && displayViewState.getResult() != null && isItemVisibleFor(displayViewState.getResult(), displayViewState.getOperation()); + } - protected boolean isItemVisibleFor(@Nonnull Generic generic, @Nonnull JsclOperation operation) { - return true; - } + protected boolean isItemVisibleFor(@Nonnull Generic generic, @Nonnull JsclOperation operation) { + return true; + } - @Nonnull - @Override - public String getCaption(@Nonnull Context context) { - return context.getString(captionId); - } + @Nonnull + @Override + public String getCaption(@Nonnull Context context) { + return context.getString(captionId); + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/CalculatorDisplayOnClickListener.java b/android-app/src/main/java/org/solovyev/android/calculator/CalculatorDisplayOnClickListener.java index b15c5e85..736cfd9f 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/CalculatorDisplayOnClickListener.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/CalculatorDisplayOnClickListener.java @@ -25,14 +25,14 @@ package org.solovyev.android.calculator; import android.support.v4.app.FragmentActivity; import android.view.View; -import javax.annotation.Nonnull; - import org.solovyev.android.menu.ContextMenuBuilder; import org.solovyev.android.menu.ListContextMenu; import java.util.ArrayList; import java.util.List; +import javax.annotation.Nonnull; + /** * User: Solovyev_S * Date: 21.09.12 @@ -40,38 +40,38 @@ import java.util.List; */ public class CalculatorDisplayOnClickListener implements View.OnClickListener { - @Nonnull - private final FragmentActivity activity; + @Nonnull + private final FragmentActivity activity; - public CalculatorDisplayOnClickListener(@Nonnull FragmentActivity activity) { - this.activity = activity; - } + public CalculatorDisplayOnClickListener(@Nonnull FragmentActivity activity) { + this.activity = activity; + } - @Override - public void onClick(View v) { - if (v instanceof CalculatorDisplayView) { - final CalculatorDisplay cd = Locator.getInstance().getDisplay(); + @Override + public void onClick(View v) { + if (v instanceof CalculatorDisplayView) { + final CalculatorDisplay cd = Locator.getInstance().getDisplay(); - final CalculatorDisplayViewState displayViewState = cd.getViewState(); + final CalculatorDisplayViewState displayViewState = cd.getViewState(); - if (displayViewState.isValid()) { - final List filteredMenuItems = new ArrayList(CalculatorDisplayMenuItem.values().length); - for (CalculatorDisplayMenuItem menuItem : CalculatorDisplayMenuItem.values()) { - if (menuItem.isItemVisible(displayViewState)) { - filteredMenuItems.add(menuItem); - } - } + if (displayViewState.isValid()) { + final List filteredMenuItems = new ArrayList(CalculatorDisplayMenuItem.values().length); + for (CalculatorDisplayMenuItem menuItem : CalculatorDisplayMenuItem.values()) { + if (menuItem.isItemVisible(displayViewState)) { + filteredMenuItems.add(menuItem); + } + } - if (!filteredMenuItems.isEmpty()) { - ContextMenuBuilder.newInstance(activity, "display-menu", ListContextMenu.newInstance(filteredMenuItems)).build(displayViewState).show(); - } + if (!filteredMenuItems.isEmpty()) { + ContextMenuBuilder.newInstance(activity, "display-menu", ListContextMenu.newInstance(filteredMenuItems)).build(displayViewState).show(); + } - } else { - final String errorMessage = displayViewState.getErrorMessage(); - if (errorMessage != null) { - Locator.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.show_evaluation_error, errorMessage, activity); - } - } - } - } + } else { + final String errorMessage = displayViewState.getErrorMessage(); + if (errorMessage != null) { + Locator.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.show_evaluation_error, errorMessage, activity); + } + } + } + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/CalculatorEditorFragment.java b/android-app/src/main/java/org/solovyev/android/calculator/CalculatorEditorFragment.java index 91638ab8..72473461 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/CalculatorEditorFragment.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/CalculatorEditorFragment.java @@ -27,7 +27,13 @@ import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; -import android.view.*; +import android.view.LayoutInflater; +import android.view.Menu; +import android.view.MenuInflater; +import android.view.MenuItem; +import android.view.View; +import android.view.ViewGroup; + import org.solovyev.android.menu.ActivityMenu; import org.solovyev.android.menu.AndroidMenuHelper; import org.solovyev.android.menu.ListActivityMenu; @@ -41,105 +47,105 @@ import javax.annotation.Nonnull; */ public class CalculatorEditorFragment extends Fragment { - @Nonnull - private FragmentUi fragmentUi; + @Nonnull + private FragmentUi fragmentUi; - @Nonnull - private ActivityMenu menu = ListActivityMenu.fromEnum(CalculatorMenu.class, AndroidMenuHelper.getInstance()); + @Nonnull + private ActivityMenu menu = ListActivityMenu.fromEnum(CalculatorMenu.class, AndroidMenuHelper.getInstance()); - @Nonnull - private AndroidCalculatorEditorView editorView; + @Nonnull + private AndroidCalculatorEditorView editorView; - 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); - fragmentUi.onViewCreated(this, view); + fragmentUi.onViewCreated(this, view); - editorView = (AndroidCalculatorEditorView) view.findViewById(R.id.calculator_editor); - editorView.init(); - Locator.getInstance().getEditor().setView(editorView); - } + editorView = (AndroidCalculatorEditorView) view.findViewById(R.id.calculator_editor); + editorView.init(); + Locator.getInstance().getEditor().setView(editorView); + } - @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 Preferences.Gui.Layout layout = Preferences.Gui.getLayout(prefs); - if (!layout.isOptimized()) { - fragmentUi = CalculatorApplication.getInstance().createFragmentHelper(R.layout.cpp_app_editor_mobile, R.string.editor); - } else { - fragmentUi = CalculatorApplication.getInstance().createFragmentHelper(R.layout.cpp_app_editor, R.string.editor); - } + final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.getActivity()); + final Preferences.Gui.Layout layout = Preferences.Gui.getLayout(prefs); + if (!layout.isOptimized()) { + fragmentUi = CalculatorApplication.getInstance().createFragmentHelper(R.layout.cpp_app_editor_mobile, R.string.editor); + } else { + fragmentUi = CalculatorApplication.getInstance().createFragmentHelper(R.layout.cpp_app_editor, R.string.editor); + } - fragmentUi.onCreate(this); - setHasOptionsMenu(true); - } + fragmentUi.onCreate(this); + setHasOptionsMenu(true); + } - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - return fragmentUi.onCreateView(this, inflater, container); - } + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + return fragmentUi.onCreateView(this, inflater, container); + } - @Override - public void onResume() { - super.onResume(); - this.fragmentUi.onResume(this); - } + @Override + public void onResume() { + super.onResume(); + this.fragmentUi.onResume(this); + } - @Override - public void onPause() { - this.fragmentUi.onPause(this); - super.onPause(); - } + @Override + public void onPause() { + this.fragmentUi.onPause(this); + super.onPause(); + } - @Override - public void onDestroyView() { - Locator.getInstance().getEditor().clearView(editorView); - fragmentUi.onDestroyView(this); - super.onDestroyView(); - } + @Override + public void onDestroyView() { + Locator.getInstance().getEditor().clearView(editorView); + fragmentUi.onDestroyView(this); + super.onDestroyView(); + } - @Override - public void onDestroy() { - fragmentUi.onDestroy(this); - super.onDestroy(); - } + @Override + public void onDestroy() { + fragmentUi.onDestroy(this); + super.onDestroy(); + } - @Override - public void onDetach() { - super.onDetach(); - } + @Override + public void onDetach() { + super.onDetach(); + } /* - ********************************************************************** + ********************************************************************** * * 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); + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/CalculatorFragment.java b/android-app/src/main/java/org/solovyev/android/calculator/CalculatorFragment.java index 06e0b095..0aacbb32 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/CalculatorFragment.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/CalculatorFragment.java @@ -24,12 +24,11 @@ package org.solovyev.android.calculator; import android.app.Activity; import android.os.Bundle; +import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; -import android.support.v4.app.Fragment; - import javax.annotation.Nonnull; /** @@ -39,77 +38,77 @@ import javax.annotation.Nonnull; */ public abstract class CalculatorFragment extends Fragment { - @Nonnull - private final FragmentUi fragmentUi; + @Nonnull + private final FragmentUi fragmentUi; - protected CalculatorFragment(int layoutResId, int titleResId) { - fragmentUi = CalculatorApplication.getInstance().createFragmentHelper(layoutResId, titleResId); - } + protected CalculatorFragment(int layoutResId, int titleResId) { + fragmentUi = CalculatorApplication.getInstance().createFragmentHelper(layoutResId, titleResId); + } - protected CalculatorFragment(@Nonnull CalculatorFragmentType fragmentType) { - fragmentUi = CalculatorApplication.getInstance().createFragmentHelper(fragmentType.getDefaultLayoutId(), fragmentType.getDefaultTitleResId()); - } + protected CalculatorFragment(@Nonnull CalculatorFragmentType fragmentType) { + fragmentUi = CalculatorApplication.getInstance().createFragmentHelper(fragmentType.getDefaultLayoutId(), fragmentType.getDefaultTitleResId()); + } - protected CalculatorFragment(@Nonnull FragmentUi fragmentUi) { - this.fragmentUi = fragmentUi; - } + protected CalculatorFragment(@Nonnull FragmentUi fragmentUi) { + this.fragmentUi = fragmentUi; + } - @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); - fragmentUi.onCreate(this); - } + fragmentUi.onCreate(this); + } - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - return fragmentUi.onCreateView(this, inflater, container); - } + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + return fragmentUi.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); - fragmentUi.onViewCreated(this, view); - } + fragmentUi.onViewCreated(this, view); + } - @Override - public void onResume() { - super.onResume(); + @Override + public void onResume() { + super.onResume(); - this.fragmentUi.onResume(this); - } + this.fragmentUi.onResume(this); + } - @Override - public void onPause() { - this.fragmentUi.onPause(this); + @Override + public void onPause() { + this.fragmentUi.onPause(this); - super.onPause(); - } + super.onPause(); + } - @Override - public void onDestroyView() { - fragmentUi.onDestroyView(this); - super.onDestroyView(); - } + @Override + public void onDestroyView() { + fragmentUi.onDestroyView(this); + super.onDestroyView(); + } - @Override - public void onDestroy() { - fragmentUi.onDestroy(this); - super.onDestroy(); - } + @Override + public void onDestroy() { + fragmentUi.onDestroy(this); + super.onDestroy(); + } - @Override - public void onDetach() { - super.onDetach(); - } + @Override + public void onDetach() { + super.onDetach(); + } - public boolean isPaneFragment() { - return fragmentUi.isPane(this); - } + public boolean isPaneFragment() { + return fragmentUi.isPane(this); + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/CalculatorFragmentType.java b/android-app/src/main/java/org/solovyev/android/calculator/CalculatorFragmentType.java index 22b0538e..93467c49 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/CalculatorFragmentType.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/CalculatorFragmentType.java @@ -46,64 +46,62 @@ import javax.annotation.Nonnull; */ 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(HistoryFragment.class, R.layout.history_fragment, R.string.c_history), - saved_history(SavedHistoryFragment.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(PlotterFragment.class, R.layout.cpp_plotter_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), + 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(HistoryFragment.class, R.layout.history_fragment, R.string.c_history), + saved_history(SavedHistoryFragment.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(PlotterFragment.class, R.layout.cpp_plotter_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), + about(CalculatorAboutFragment.class, R.layout.about_fragment, R.string.c_about), - // todo serso: strings - matrix_edit(CalculatorMatrixEditFragment.class, R.layout.matrix_edit_fragment, R.string.c_release_notes), - 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_release_notes), + release_notes(CalculatorReleaseNotesFragment.class, R.layout.release_notes_fragment, R.string.c_release_notes); - @Nonnull - private Class fragmentClass; + private final int defaultLayoutId; + @Nonnull + private Class fragmentClass; + private int defaultTitleResId; - private final int defaultLayoutId; + private CalculatorFragmentType(@Nonnull Class fragmentClass, + int defaultLayoutId, + int defaultTitleResId) { + this.fragmentClass = fragmentClass; + this.defaultLayoutId = defaultLayoutId; + this.defaultTitleResId = defaultTitleResId; + } - private int defaultTitleResId; + @Nonnull + public String getFragmentTag() { + return this.name(); + } - private CalculatorFragmentType(@Nonnull Class fragmentClass, - int defaultLayoutId, - int defaultTitleResId) { - this.fragmentClass = fragmentClass; - this.defaultLayoutId = defaultLayoutId; - this.defaultTitleResId = defaultTitleResId; - } + public int getDefaultTitleResId() { + return defaultTitleResId; + } - @Nonnull - public String getFragmentTag() { - return this.name(); - } + @Nonnull + public Class getFragmentClass() { + return fragmentClass; + } - public int getDefaultTitleResId() { - return defaultTitleResId; - } + public int getDefaultLayoutId() { + return defaultLayoutId; + } - @Nonnull - public Class getFragmentClass() { - return fragmentClass; - } - - public int getDefaultLayoutId() { - return defaultLayoutId; - } - - @Nonnull - public String createSubFragmentTag(@Nonnull String subFragmentTag) { - return this.getFragmentTag() + "_" + subFragmentTag; - } + @Nonnull + public String createSubFragmentTag(@Nonnull String subFragmentTag) { + return this.getFragmentTag() + "_" + subFragmentTag; + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/CalculatorKeyboardFragment.java b/android-app/src/main/java/org/solovyev/android/calculator/CalculatorKeyboardFragment.java index fb7d2f42..2be3cd89 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/CalculatorKeyboardFragment.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/CalculatorKeyboardFragment.java @@ -24,10 +24,10 @@ package org.solovyev.android.calculator; import android.content.SharedPreferences; import android.os.Bundle; +import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; -import android.support.v4.app.Fragment; import javax.annotation.Nonnull; @@ -44,82 +44,82 @@ import static org.solovyev.android.calculator.model.AndroidCalculatorEngine.Pref */ public class CalculatorKeyboardFragment extends Fragment implements SharedPreferences.OnSharedPreferenceChangeListener { - @Nonnull - private FragmentUi ui; + @Nonnull + private FragmentUi ui; - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); - final SharedPreferences preferences = App.getPreferences(); + final SharedPreferences preferences = App.getPreferences(); - final Preferences.Gui.Layout layout = Preferences.Gui.getLayout(preferences); - if (!layout.isOptimized()) { - ui = CalculatorApplication.getInstance().createFragmentHelper(R.layout.cpp_app_keyboard_mobile); - } else { - ui = CalculatorApplication.getInstance().createFragmentHelper(R.layout.cpp_app_keyboard); - } + final Preferences.Gui.Layout layout = Preferences.Gui.getLayout(preferences); + if (!layout.isOptimized()) { + ui = CalculatorApplication.getInstance().createFragmentHelper(R.layout.cpp_app_keyboard_mobile); + } else { + ui = CalculatorApplication.getInstance().createFragmentHelper(R.layout.cpp_app_keyboard); + } - ui.onCreate(this); + ui.onCreate(this); - preferences.registerOnSharedPreferenceChangeListener(this); - } + preferences.registerOnSharedPreferenceChangeListener(this); + } - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - return ui.onCreateView(this, inflater, container); - } + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + return ui.onCreateView(this, inflater, container); + } - @Override - public void onViewCreated(View root, Bundle savedInstanceState) { - super.onViewCreated(root, savedInstanceState); - ui.onViewCreated(this, root); - } + @Override + public void onViewCreated(View root, Bundle savedInstanceState) { + super.onViewCreated(root, savedInstanceState); + ui.onViewCreated(this, root); + } - @Override - public void onResume() { - super.onResume(); - this.ui.onResume(this); - } + @Override + public void onResume() { + super.onResume(); + this.ui.onResume(this); + } - @Override - public void onPause() { - this.ui.onPause(this); - super.onPause(); - } + @Override + public void onPause() { + this.ui.onPause(this); + super.onPause(); + } - @Override - public void onDestroyView() { - ui.onDestroyView(this); - super.onDestroyView(); - } + @Override + public void onDestroyView() { + ui.onDestroyView(this); + super.onDestroyView(); + } - @Override - public void onDestroy() { - super.onDestroy(); - ui.onDestroy(this); - App.getPreferences().unregisterOnSharedPreferenceChangeListener(this); - } + @Override + public void onDestroy() { + super.onDestroy(); + ui.onDestroy(this); + App.getPreferences().unregisterOnSharedPreferenceChangeListener(this); + } - @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 (numeralBase.isSameKey(key) || hideNumeralBaseDigits.isSameKey(key)) { - toggleNumericDigits(this.getActivity(), preferences); - } + @Override + public void onSharedPreferenceChanged(SharedPreferences preferences, String key) { + if (numeralBase.isSameKey(key) || hideNumeralBaseDigits.isSameKey(key)) { + toggleNumericDigits(this.getActivity(), preferences); + } - if (showEqualsButton.isSameKey(key)) { - CalculatorButtons.toggleEqualsButton(preferences, this.getActivity()); - } + if (showEqualsButton.isSameKey(key)) { + CalculatorButtons.toggleEqualsButton(preferences, this.getActivity()); + } - if (multiplicationSign.isSameKey(key)) { - CalculatorButtons.initMultiplicationButton(getView()); - } - } + if (multiplicationSign.isSameKey(key)) { + CalculatorButtons.initMultiplicationButton(getView()); + } + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/CalculatorListFragment.java b/android-app/src/main/java/org/solovyev/android/calculator/CalculatorListFragment.java index 0bd9a3f9..79100c39 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/CalculatorListFragment.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/CalculatorListFragment.java @@ -24,12 +24,11 @@ package org.solovyev.android.calculator; import android.app.Activity; import android.os.Bundle; +import android.support.v4.app.ListFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; -import android.support.v4.app.ListFragment; - import javax.annotation.Nonnull; /** @@ -39,72 +38,72 @@ import javax.annotation.Nonnull; */ public abstract class CalculatorListFragment extends ListFragment { - @Nonnull - private final FragmentUi ui; + @Nonnull + private final FragmentUi ui; - protected CalculatorListFragment(int layoutResId, int titleResId) { - ui = CalculatorApplication.getInstance().createFragmentHelper(layoutResId, titleResId); - } + protected CalculatorListFragment(int layoutResId, int titleResId) { + ui = CalculatorApplication.getInstance().createFragmentHelper(layoutResId, titleResId); + } - protected CalculatorListFragment(@Nonnull CalculatorFragmentType fragmentType) { - ui = CalculatorApplication.getInstance().createFragmentHelper(fragmentType.getDefaultLayoutId(), fragmentType.getDefaultTitleResId()); - } + protected CalculatorListFragment(@Nonnull CalculatorFragmentType fragmentType) { + ui = CalculatorApplication.getInstance().createFragmentHelper(fragmentType.getDefaultLayoutId(), fragmentType.getDefaultTitleResId()); + } - protected CalculatorListFragment(@Nonnull FragmentUi ui) { - this.ui = ui; - } + protected CalculatorListFragment(@Nonnull FragmentUi ui) { + this.ui = ui; + } - @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); - ui.onCreate(this); - } + ui.onCreate(this); + } - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - return ui.onCreateView(this, inflater, container); - } + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + return ui.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); - ui.onViewCreated(this, view); - } + ui.onViewCreated(this, view); + } - @Override - public void onResume() { - super.onResume(); - this.ui.onResume(this); - } + @Override + public void onResume() { + super.onResume(); + this.ui.onResume(this); + } - @Override - public void onPause() { - this.ui.onPause(this); - super.onPause(); - } + @Override + public void onPause() { + this.ui.onPause(this); + super.onPause(); + } - @Override - public void onDestroyView() { - ui.onDestroyView(this); - super.onDestroyView(); - } + @Override + public void onDestroyView() { + ui.onDestroyView(this); + super.onDestroyView(); + } - @Override - public void onDestroy() { - ui.onDestroy(this); - super.onDestroy(); - } + @Override + public void onDestroy() { + ui.onDestroy(this); + super.onDestroy(); + } - @Override - public void onDetach() { - super.onDetach(); - } + @Override + public void onDetach() { + super.onDetach(); + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/CalculatorMenu.java b/android-app/src/main/java/org/solovyev/android/calculator/CalculatorMenu.java index 654e73a3..8d05335d 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/CalculatorMenu.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/CalculatorMenu.java @@ -25,14 +25,13 @@ package org.solovyev.android.calculator; import android.app.Activity; import android.content.Context; import android.util.Log; - import android.view.MenuItem; -import javax.annotation.Nonnull; - import org.solovyev.android.calculator.view.NumeralBaseConverterDialog; import org.solovyev.android.menu.LabeledMenuItem; +import javax.annotation.Nonnull; + /** * User: serso * Date: 4/23/12 @@ -40,61 +39,61 @@ import org.solovyev.android.menu.LabeledMenuItem; */ enum CalculatorMenu implements LabeledMenuItem { - settings(R.string.c_settings) { - @Override - public void onClick(@Nonnull MenuItem data, @Nonnull Context context) { - CalculatorActivityLauncher.showSettings(context); - } - }, + settings(R.string.c_settings) { + @Override + public void onClick(@Nonnull MenuItem data, @Nonnull Context context) { + CalculatorActivityLauncher.showSettings(context); + } + }, - history(R.string.c_history) { - @Override - public void onClick(@Nonnull MenuItem data, @Nonnull Context context) { - CalculatorActivityLauncher.showHistory(context); - } - }, + history(R.string.c_history) { + @Override + public void onClick(@Nonnull MenuItem data, @Nonnull Context context) { + CalculatorActivityLauncher.showHistory(context); + } + }, - plotter(R.string.cpp_plotter) { - @Override - public void onClick(@Nonnull MenuItem data, @Nonnull Context context) { - Locator.getInstance().getPlotter().plot(); - } - }, + plotter(R.string.cpp_plotter) { + @Override + public void onClick(@Nonnull MenuItem data, @Nonnull Context context) { + Locator.getInstance().getPlotter().plot(); + } + }, - conversion_tool(R.string.c_conversion_tool) { - @Override - public void onClick(@Nonnull MenuItem data, @Nonnull Context context) { - new NumeralBaseConverterDialog(null).show(context); - } - }, + conversion_tool(R.string.c_conversion_tool) { + @Override + public void onClick(@Nonnull MenuItem data, @Nonnull Context context) { + new NumeralBaseConverterDialog(null).show(context); + } + }, - exit(R.string.c_exit) { - @Override - public void onClick(@Nonnull MenuItem data, @Nonnull 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(@Nonnull MenuItem data, @Nonnull Context context) { + if (context instanceof Activity) { + ((Activity) context).finish(); + } else { + Log.e(CalculatorActivity.TAG, "Activity menu used with context"); + } + } + }, - about(R.string.c_about) { - @Override - public void onClick(@Nonnull MenuItem data, @Nonnull Context context) { - CalculatorActivityLauncher.showAbout(context); - } - }; + about(R.string.c_about) { + @Override + public void onClick(@Nonnull MenuItem data, @Nonnull 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; + } - @Nonnull - @Override - public String getCaption(@Nonnull Context context) { - return context.getString(captionResId); - } + @Nonnull + @Override + public String getCaption(@Nonnull Context context) { + return context.getString(captionResId); + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/CalculatorReceiver.java b/android-app/src/main/java/org/solovyev/android/calculator/CalculatorReceiver.java index 4d3ba721..ac7b3ec5 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/CalculatorReceiver.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/CalculatorReceiver.java @@ -8,28 +8,28 @@ import javax.annotation.Nonnull; public final class CalculatorReceiver extends BroadcastReceiver { - public static final String ACTION_BUTTON_ID_EXTRA = "buttonId"; - public static final String ACTION_BUTTON_PRESSED = "org.solovyev.android.calculator.BUTTON_PRESSED"; + public static final String ACTION_BUTTON_ID_EXTRA = "buttonId"; + public static final String ACTION_BUTTON_PRESSED = "org.solovyev.android.calculator.BUTTON_PRESSED"; - @Override - public void onReceive(Context context, Intent intent) { - final String action = intent.getAction(); + @Nonnull + public static Intent newButtonClickedIntent(@Nonnull Context context, @Nonnull CalculatorButton button) { + final Intent intent = new Intent(context, CalculatorReceiver.class); + intent.setAction(ACTION_BUTTON_PRESSED); + intent.putExtra(ACTION_BUTTON_ID_EXTRA, button.getButtonId()); + return intent; + } - if (ACTION_BUTTON_PRESSED.equals(action)) { - final int buttonId = intent.getIntExtra(ACTION_BUTTON_ID_EXTRA, 0); + @Override + public void onReceive(Context context, Intent intent) { + final String action = intent.getAction(); - final CalculatorButton button = CalculatorButton.getById(buttonId); - if (button != null) { - button.onClick(); - } - } - } + if (ACTION_BUTTON_PRESSED.equals(action)) { + final int buttonId = intent.getIntExtra(ACTION_BUTTON_ID_EXTRA, 0); - @Nonnull - public static Intent newButtonClickedIntent(@Nonnull Context context, @Nonnull CalculatorButton button) { - final Intent intent = new Intent(context, CalculatorReceiver.class); - intent.setAction(ACTION_BUTTON_PRESSED); - intent.putExtra(ACTION_BUTTON_ID_EXTRA, button.getButtonId()); - return intent; - } + final CalculatorButton button = CalculatorButton.getById(buttonId); + if (button != null) { + button.onClick(); + } + } + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/CalculatorSecurity.java b/android-app/src/main/java/org/solovyev/android/calculator/CalculatorSecurity.java index 66586b36..c28365c7 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/CalculatorSecurity.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/CalculatorSecurity.java @@ -31,21 +31,21 @@ import javax.annotation.Nonnull; */ public final class CalculatorSecurity { - private CalculatorSecurity() { - } + private CalculatorSecurity() { + } - @Nonnull - public static String getPK() { - final StringBuilder result = new StringBuilder(); + @Nonnull + public static String getPK() { + final StringBuilder result = new StringBuilder(); - result.append("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A"); - result.append("MIIBCgKCAQEAquP2a7dEhTaJEQeXtSyreH5dCmTDOd"); - result.append("dElCfg0ijOeB8JTxBiJTXLWnLA0kMaT/sRXswUaYI61YCQOoik82"); - result.append("qrFH7W4+OFtiLb8WGX+YPEpQQ/IBZu9qm3xzS9Nolu79EBff0/CLa1FuT9RtjO"); - result.append("iTW8Q0VP9meQdJEkfqJEyVCgHain+MGoQaRXI45EzkYmkz8TBx6X6aJF5NBAXnAWeyD0wPX1"); - result.append("uedHH7+LgLcjnPVw82YjyJSzYnaaD2GX0Y7PGoFe6J5K4yJGGX5mih45pe2HWcG5lAkQhu1uX2hCcCBdF3"); - result.append("W7paRq9mJvCsbn+BNTh9gq8QKui0ltmiWpa5U+/9L+FQIDAQAB"); + result.append("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A"); + result.append("MIIBCgKCAQEAquP2a7dEhTaJEQeXtSyreH5dCmTDOd"); + result.append("dElCfg0ijOeB8JTxBiJTXLWnLA0kMaT/sRXswUaYI61YCQOoik82"); + result.append("qrFH7W4+OFtiLb8WGX+YPEpQQ/IBZu9qm3xzS9Nolu79EBff0/CLa1FuT9RtjO"); + result.append("iTW8Q0VP9meQdJEkfqJEyVCgHain+MGoQaRXI45EzkYmkz8TBx6X6aJF5NBAXnAWeyD0wPX1"); + result.append("uedHH7+LgLcjnPVw82YjyJSzYnaaD2GX0Y7PGoFe6J5K4yJGGX5mih45pe2HWcG5lAkQhu1uX2hCcCBdF3"); + result.append("W7paRq9mJvCsbn+BNTh9gq8QKui0ltmiWpa5U+/9L+FQIDAQAB"); - return result.toString(); - } + return result.toString(); + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/CharacterAtPositionFinder.java b/android-app/src/main/java/org/solovyev/android/calculator/CharacterAtPositionFinder.java index 3fff7145..70b99a49 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/CharacterAtPositionFinder.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/CharacterAtPositionFinder.java @@ -22,11 +22,11 @@ package org.solovyev.android.calculator; +import org.solovyev.common.JPredicate; + import javax.annotation.Nonnull; import javax.annotation.Nullable; -import org.solovyev.common.JPredicate; - /** * User: serso * Date: 10/3/11 @@ -34,22 +34,21 @@ import org.solovyev.common.JPredicate; */ public class CharacterAtPositionFinder implements JPredicate { - private int i; + @Nonnull + private final String targetString; + private int i; - @Nonnull - private final String targetString; + public CharacterAtPositionFinder(@Nonnull String targetString, int i) { + this.targetString = targetString; + this.i = i; + } - public CharacterAtPositionFinder(@Nonnull String targetString, int i) { - this.targetString = targetString; - this.i = i; - } + @Override + public boolean apply(@Nullable Character s) { + return s != null && s.equals(targetString.charAt(i)); + } - @Override - public boolean apply(@Nullable Character s) { - return s != null && s.equals(targetString.charAt(i)); - } - - public void setI(int i) { - this.i = i; - } + public void setI(int i) { + this.i = i; + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/ConversionMenuItem.java b/android-app/src/main/java/org/solovyev/android/calculator/ConversionMenuItem.java index 8a048941..f528f99c 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/ConversionMenuItem.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/ConversionMenuItem.java @@ -23,14 +23,15 @@ package org.solovyev.android.calculator; import android.content.Context; -import jscl.NumeralBase; -import jscl.math.Generic; - -import javax.annotation.Nonnull; import org.solovyev.android.calculator.jscl.JsclOperation; import org.solovyev.android.menu.AMenuItem; +import javax.annotation.Nonnull; + +import jscl.NumeralBase; +import jscl.math.Generic; + /** * User: serso * Date: 9/21/12 @@ -38,39 +39,39 @@ import org.solovyev.android.menu.AMenuItem; */ enum ConversionMenuItem implements AMenuItem { - convert_to_bin(NumeralBase.bin), - convert_to_dec(NumeralBase.dec), - convert_to_hex(NumeralBase.hex); + convert_to_bin(NumeralBase.bin), + convert_to_dec(NumeralBase.dec), + convert_to_hex(NumeralBase.hex); - @Nonnull - private final NumeralBase toNumeralBase; + @Nonnull + private final NumeralBase toNumeralBase; - ConversionMenuItem(@Nonnull NumeralBase toNumeralBase) { - this.toNumeralBase = toNumeralBase; - } + ConversionMenuItem(@Nonnull NumeralBase toNumeralBase) { + this.toNumeralBase = toNumeralBase; + } - protected boolean isItemVisibleFor(@Nonnull Generic generic, @Nonnull JsclOperation operation) { - boolean result = false; + protected boolean isItemVisibleFor(@Nonnull Generic generic, @Nonnull JsclOperation operation) { + boolean result = false; - if (operation == JsclOperation.numeric) { - if (generic.getConstants().isEmpty()) { - // conversion possible => return true - final NumeralBase fromNumeralBase = Locator.getInstance().getEngine().getNumeralBase(); - if (fromNumeralBase != toNumeralBase) { - result = Locator.getInstance().getCalculator().isConversionPossible(generic, fromNumeralBase, this.toNumeralBase); - } - } - } + if (operation == JsclOperation.numeric) { + if (generic.getConstants().isEmpty()) { + // conversion possible => return true + final NumeralBase fromNumeralBase = Locator.getInstance().getEngine().getNumeralBase(); + if (fromNumeralBase != toNumeralBase) { + result = Locator.getInstance().getCalculator().isConversionPossible(generic, fromNumeralBase, this.toNumeralBase); + } + } + } - return result; - } + return result; + } - @Override - public void onClick(@Nonnull CalculatorDisplayViewState data, @Nonnull Context context) { - final Generic result = data.getResult(); + @Override + public void onClick(@Nonnull CalculatorDisplayViewState data, @Nonnull Context context) { + final Generic result = data.getResult(); - if (result != null) { - Locator.getInstance().getCalculator().convert(result, this.toNumeralBase); - } - } + if (result != null) { + Locator.getInstance().getCalculator().convert(result, this.toNumeralBase); + } + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/CursorDragProcessor.java b/android-app/src/main/java/org/solovyev/android/calculator/CursorDragProcessor.java index 89fb3f30..a8ab1fc3 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/CursorDragProcessor.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/CursorDragProcessor.java @@ -23,6 +23,7 @@ package org.solovyev.android.calculator; import android.view.MotionEvent; + import org.solovyev.android.calculator.drag.DirectionDragButton; import org.solovyev.android.calculator.drag.DragButton; import org.solovyev.android.calculator.drag.DragDirection; @@ -38,26 +39,26 @@ import javax.annotation.Nonnull; */ public class CursorDragProcessor implements SimpleDragListener.DragProcessor { - public CursorDragProcessor() { - } + public CursorDragProcessor() { + } - @Override - public boolean processDragEvent(@Nonnull DragDirection dragDirection, @Nonnull DragButton dragButton, @Nonnull Point2d startPoint2d, @Nonnull MotionEvent motionEvent) { - boolean result = false; + @Override + public boolean processDragEvent(@Nonnull DragDirection dragDirection, @Nonnull DragButton dragButton, @Nonnull Point2d startPoint2d, @Nonnull MotionEvent motionEvent) { + boolean result = false; - if (dragButton instanceof DirectionDragButton) { - String text = ((DirectionDragButton) dragButton).getText(dragDirection); - if ("◁◁".equals(text)) { - App.getVibrator().vibrate(); - Locator.getInstance().getEditor().setCursorOnStart(); - result = true; - } else if ("▷▷".equals(text)) { - App.getVibrator().vibrate(); - Locator.getInstance().getEditor().setCursorOnEnd(); - result = true; - } - } + if (dragButton instanceof DirectionDragButton) { + String text = ((DirectionDragButton) dragButton).getText(dragDirection); + if ("◁◁".equals(text)) { + App.getVibrator().vibrate(); + Locator.getInstance().getEditor().setCursorOnStart(); + result = true; + } else if ("▷▷".equals(text)) { + App.getVibrator().vibrate(); + Locator.getInstance().getEditor().setCursorOnEnd(); + result = true; + } + } - return result; - } + return result; + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/DigitButtonDragProcessor.java b/android-app/src/main/java/org/solovyev/android/calculator/DigitButtonDragProcessor.java index 95ec9587..e618aaf9 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/DigitButtonDragProcessor.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/DigitButtonDragProcessor.java @@ -23,6 +23,7 @@ package org.solovyev.android.calculator; import android.view.MotionEvent; + import org.solovyev.android.calculator.drag.DirectionDragButton; import org.solovyev.android.calculator.drag.DragButton; import org.solovyev.android.calculator.drag.DragDirection; @@ -38,19 +39,19 @@ import javax.annotation.Nonnull; */ public class DigitButtonDragProcessor implements SimpleDragListener.DragProcessor { - @Nonnull - private CalculatorKeyboard calculatorKeyboard; + @Nonnull + private CalculatorKeyboard calculatorKeyboard; - public DigitButtonDragProcessor(@Nonnull CalculatorKeyboard calculatorKeyboard) { - this.calculatorKeyboard = calculatorKeyboard; - } + public DigitButtonDragProcessor(@Nonnull CalculatorKeyboard calculatorKeyboard) { + this.calculatorKeyboard = calculatorKeyboard; + } - @Override - public boolean processDragEvent(@Nonnull DragDirection dragDirection, @Nonnull DragButton dragButton, @Nonnull Point2d startPoint2d, @Nonnull MotionEvent motionEvent) { - if (!(dragButton instanceof DirectionDragButton)) throw new AssertionError(); - final String text = ((DirectionDragButton) dragButton).getText(dragDirection); - calculatorKeyboard.buttonPressed(text); - return true; - } + @Override + public boolean processDragEvent(@Nonnull DragDirection dragDirection, @Nonnull DragButton dragButton, @Nonnull Point2d startPoint2d, @Nonnull MotionEvent motionEvent) { + if (!(dragButton instanceof DirectionDragButton)) throw new AssertionError(); + final String text = ((DirectionDragButton) dragButton).getText(dragDirection); + calculatorKeyboard.buttonPressed(text); + return true; + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/EmptyActivity.java b/android-app/src/main/java/org/solovyev/android/calculator/EmptyActivity.java index 1222c795..e027d2b0 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/EmptyActivity.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/EmptyActivity.java @@ -24,11 +24,11 @@ package org.solovyev.android.calculator; public abstract class EmptyActivity extends BaseActivity { - protected EmptyActivity() { - this(R.layout.main_empty); - } + protected EmptyActivity() { + this(R.layout.main_empty); + } - protected EmptyActivity(int layoutResId) { - super(layoutResId); - } + protected EmptyActivity(int layoutResId) { + super(layoutResId); + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/EqualsDragProcessor.java b/android-app/src/main/java/org/solovyev/android/calculator/EqualsDragProcessor.java index 2ed66dc1..81bdbf26 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/EqualsDragProcessor.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/EqualsDragProcessor.java @@ -24,14 +24,14 @@ package org.solovyev.android.calculator; import android.view.MotionEvent; -import javax.annotation.Nonnull; - import org.solovyev.android.calculator.drag.DirectionDragButton; import org.solovyev.android.calculator.drag.DragButton; import org.solovyev.android.calculator.drag.DragDirection; import org.solovyev.android.calculator.drag.SimpleDragListener; import org.solovyev.common.math.Point2d; +import javax.annotation.Nonnull; + /** * User: serso * Date: 10/24/11 @@ -39,28 +39,28 @@ import org.solovyev.common.math.Point2d; */ public class EqualsDragProcessor implements SimpleDragListener.DragProcessor { - public EqualsDragProcessor() { - } + public EqualsDragProcessor() { + } - @Override - public boolean processDragEvent(@Nonnull DragDirection dragDirection, @Nonnull DragButton dragButton, @Nonnull Point2d startPoint2d, @Nonnull MotionEvent motionEvent) { - boolean result = false; + @Override + public boolean processDragEvent(@Nonnull DragDirection dragDirection, @Nonnull DragButton dragButton, @Nonnull Point2d startPoint2d, @Nonnull MotionEvent motionEvent) { + boolean result = false; - if (dragButton instanceof DirectionDragButton) { - if (dragDirection == DragDirection.down) { - App.getVibrator().vibrate(); - CalculatorActivityLauncher.tryPlot(); - result = true; - } else { - final String text = ((DirectionDragButton) dragButton).getText(dragDirection); - if ("≡".equals(text)) { - App.getVibrator().vibrate(); - Locator.getInstance().getCalculator().simplify(); - result = true; - } - } - } + if (dragButton instanceof DirectionDragButton) { + if (dragDirection == DragDirection.down) { + App.getVibrator().vibrate(); + CalculatorActivityLauncher.tryPlot(); + result = true; + } else { + final String text = ((DirectionDragButton) dragButton).getText(dragDirection); + if ("≡".equals(text)) { + App.getVibrator().vibrate(); + Locator.getInstance().getCalculator().simplify(); + result = true; + } + } + } - return result; - } + return result; + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/FixableMessage.java b/android-app/src/main/java/org/solovyev/android/calculator/FixableMessage.java index c76fb0e8..83a2a4bc 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/FixableMessage.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/FixableMessage.java @@ -24,6 +24,7 @@ package org.solovyev.android.calculator; import android.os.Parcel; import android.os.Parcelable; + import org.solovyev.common.msg.Message; import org.solovyev.common.msg.MessageType; @@ -37,75 +38,72 @@ import javax.annotation.Nullable; */ public class FixableMessage implements Parcelable { - public static final Creator CREATOR = new Creator() { - @Override - public FixableMessage createFromParcel(@Nonnull Parcel in) { - return FixableMessage.fromParcel(in); - } + public static final Creator CREATOR = new Creator() { + @Override + public FixableMessage createFromParcel(@Nonnull Parcel in) { + return FixableMessage.fromParcel(in); + } - @Override - public FixableMessage[] newArray(int size) { - return new FixableMessage[size]; - } - }; + @Override + public FixableMessage[] newArray(int size) { + return new FixableMessage[size]; + } + }; + @Nonnull + private final String message; + @Nonnull + private final MessageType messageType; + @Nullable + private final FixableError fixableError; - @Nonnull - private static FixableMessage fromParcel(@Nonnull Parcel in) { - final String message = in.readString(); - final MessageType messageType = (MessageType) in.readSerializable(); - final FixableError fixableError = (FixableError) in.readSerializable(); + public FixableMessage(@Nonnull Message message) { + this.message = message.getLocalizedMessage(); + final int messageLevel = message.getMessageLevel().getMessageLevel(); + this.messageType = CalculatorMessages.toMessageType(messageLevel); + this.fixableError = CalculatorFixableError.getErrorByMessageCode(message.getMessageCode()); + } - return new FixableMessage(message, messageType, fixableError); - } + public FixableMessage(@Nonnull String message, + @Nonnull MessageType messageType, + @Nullable FixableError fixableError) { + this.message = message; + this.messageType = messageType; + this.fixableError = fixableError; + } - @Nonnull - private final String message; + @Nonnull + private static FixableMessage fromParcel(@Nonnull Parcel in) { + final String message = in.readString(); + final MessageType messageType = (MessageType) in.readSerializable(); + final FixableError fixableError = (FixableError) in.readSerializable(); - @Nonnull - private final MessageType messageType; + return new FixableMessage(message, messageType, fixableError); + } - @Nullable - private final FixableError fixableError; + @Override + public int describeContents() { + return 0; + } - public FixableMessage(@Nonnull Message message) { - this.message = message.getLocalizedMessage(); - final int messageLevel = message.getMessageLevel().getMessageLevel(); - this.messageType = CalculatorMessages.toMessageType(messageLevel); - this.fixableError = CalculatorFixableError.getErrorByMessageCode(message.getMessageCode()); - } + @Override + public void writeToParcel(@Nonnull Parcel out, int flags) { + out.writeString(message); + out.writeSerializable(messageType); + out.writeSerializable(fixableError); + } - public FixableMessage(@Nonnull String message, - @Nonnull MessageType messageType, - @Nullable FixableError fixableError) { - this.message = message; - this.messageType = messageType; - this.fixableError = fixableError; - } + @Nonnull + public String getMessage() { + return message; + } - @Override - public int describeContents() { - return 0; - } + @Nonnull + public MessageType getMessageType() { + return messageType; + } - @Override - public void writeToParcel(@Nonnull Parcel out, int flags) { - out.writeString(message); - out.writeSerializable(messageType); - out.writeSerializable(fixableError); - } - - @Nonnull - public String getMessage() { - return message; - } - - @Nonnull - public MessageType getMessageType() { - return messageType; - } - - @Nullable - public FixableError getFixableError() { - return fixableError; - } + @Nullable + public FixableError getFixableError() { + return fixableError; + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/FixableMessagesDialog.java b/android-app/src/main/java/org/solovyev/android/calculator/FixableMessagesDialog.java index a93bf83b..c41668f5 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/FixableMessagesDialog.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/FixableMessagesDialog.java @@ -36,14 +36,16 @@ import android.view.ViewGroup; import android.widget.Button; import android.widget.CheckBox; import android.widget.TextView; + import org.solovyev.common.msg.Message; import org.solovyev.common.text.Strings; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.Collections; import java.util.List; +import javax.annotation.Nonnull; + /** * User: serso * Date: 11/17/12 @@ -51,226 +53,223 @@ import java.util.List; */ public class FixableMessagesDialog extends ActionBarActivity { - private static final String INPUT = "input"; + private static final String INPUT = "input"; - @Nonnull - private Input input = new Input(Collections.emptyList(), false); + @Nonnull + private Input input = new Input(Collections.emptyList(), false); - public FixableMessagesDialog() { - } + public FixableMessagesDialog() { + } - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); + public static void showDialogForMessages(@Nonnull List messages, + @Nonnull Context context, + boolean showCheckbox) { + if (!messages.isEmpty()) { + final Intent intent = new Intent(context, FixableMessagesDialog.class); - setContentView(R.layout.cpp_fixable_messages_dialog); + intent.putExtra(INPUT, Input.fromMessages(messages, showCheckbox)); + intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - final Intent intent = getIntent(); - if (intent != null) { - parseIntent(intent); - } + context.startActivity(intent); + } + } - final CheckBox doNotShowCalculationMessagesCheckbox = (CheckBox) findViewById(R.id.cpp_do_not_show_fixable_messages_checkbox); - if (input.isShowCheckbox()) { - doNotShowCalculationMessagesCheckbox.setVisibility(View.VISIBLE); - } else { - doNotShowCalculationMessagesCheckbox.setVisibility(View.GONE); - } + public static void showDialog(@Nonnull List messages, + @Nonnull Context context, + boolean showCheckbox) { + if (!messages.isEmpty()) { + final Intent intent = new Intent(context, FixableMessagesDialog.class); - final Button closeButton = (Button) findViewById(R.id.close_button); - closeButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (doNotShowCalculationMessagesCheckbox.isChecked()) { - final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(FixableMessagesDialog.this); - Preferences.Calculations.showCalculationMessagesDialog.putPreference(prefs, false); - } + intent.putExtra(INPUT, new Input(messages, showCheckbox)); + intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - FixableMessagesDialog.this.finish(); - } - }); - } + context.startActivity(intent); + } + } - private void parseIntent(@Nonnull Intent intent) { - final Input input = intent.getParcelableExtra(INPUT); - if (input != null) { - this.input = input; - onInputChanged(); - } - } + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); - private void onInputChanged() { - final ViewGroup viewGroup = (ViewGroup) findViewById(R.id.cpp_fixable_messages_container); - viewGroup.removeAllViews(); + setContentView(R.layout.cpp_fixable_messages_dialog); - final LayoutInflater layoutInflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + final Intent intent = getIntent(); + if (intent != null) { + parseIntent(intent); + } - final List messages = input.getMessages(); - for (final FixableMessage message : messages) { - final View view = layoutInflater.inflate(R.layout.cpp_fixable_messages_dialog_message, null); + final CheckBox doNotShowCalculationMessagesCheckbox = (CheckBox) findViewById(R.id.cpp_do_not_show_fixable_messages_checkbox); + if (input.isShowCheckbox()) { + doNotShowCalculationMessagesCheckbox.setVisibility(View.VISIBLE); + } else { + doNotShowCalculationMessagesCheckbox.setVisibility(View.GONE); + } - final TextView calculationMessagesTextView = (TextView) view.findViewById(R.id.cpp_fixable_messages_text_view); - calculationMessagesTextView.setText(message.getMessage()); + final Button closeButton = (Button) findViewById(R.id.close_button); + closeButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + if (doNotShowCalculationMessagesCheckbox.isChecked()) { + final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(FixableMessagesDialog.this); + Preferences.Calculations.showCalculationMessagesDialog.putPreference(prefs, false); + } - final Button fixButton = (Button) view.findViewById(R.id.cpp_fix_button); - final FixableError fixableError = message.getFixableError(); - if (fixableError == null) { - fixButton.setVisibility(View.GONE); - fixButton.setOnClickListener(null); - } else { - fixButton.setVisibility(View.VISIBLE); - fixButton.setOnClickListener(new FixErrorOnClickListener(messages, message)); + FixableMessagesDialog.this.finish(); + } + }); + } - final CharSequence fixCaption = fixableError.getFixCaption(); - if (!Strings.isEmpty(fixCaption)) { - fixButton.setText(fixCaption); - } - } - - - viewGroup.addView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); - } - - } - - @Override - protected void onNewIntent(@Nonnull Intent intent) { - super.onNewIntent(intent); - parseIntent(intent); - } + private void parseIntent(@Nonnull Intent intent) { + final Input input = intent.getParcelableExtra(INPUT); + if (input != null) { + this.input = input; + onInputChanged(); + } + } /* - ********************************************************************** + ********************************************************************** * * STATIC * ********************************************************************** */ - public static void showDialogForMessages(@Nonnull List messages, - @Nonnull Context context, - boolean showCheckbox) { - if (!messages.isEmpty()) { - final Intent intent = new Intent(context, FixableMessagesDialog.class); + private void onInputChanged() { + final ViewGroup viewGroup = (ViewGroup) findViewById(R.id.cpp_fixable_messages_container); + viewGroup.removeAllViews(); - intent.putExtra(INPUT, Input.fromMessages(messages, showCheckbox)); - intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + final LayoutInflater layoutInflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); - context.startActivity(intent); - } - } + final List messages = input.getMessages(); + for (final FixableMessage message : messages) { + final View view = layoutInflater.inflate(R.layout.cpp_fixable_messages_dialog_message, null); - public static void showDialog(@Nonnull List messages, - @Nonnull Context context, - boolean showCheckbox) { - if (!messages.isEmpty()) { - final Intent intent = new Intent(context, FixableMessagesDialog.class); + final TextView calculationMessagesTextView = (TextView) view.findViewById(R.id.cpp_fixable_messages_text_view); + calculationMessagesTextView.setText(message.getMessage()); - intent.putExtra(INPUT, new Input(messages, showCheckbox)); - intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + final Button fixButton = (Button) view.findViewById(R.id.cpp_fix_button); + final FixableError fixableError = message.getFixableError(); + if (fixableError == null) { + fixButton.setVisibility(View.GONE); + fixButton.setOnClickListener(null); + } else { + fixButton.setVisibility(View.VISIBLE); + fixButton.setOnClickListener(new FixErrorOnClickListener(messages, message)); - context.startActivity(intent); - } - } - - private static final class Input implements Parcelable { - - public static final Creator CREATOR = new Creator() { - @Override - public Input createFromParcel(@Nonnull Parcel in) { - return Input.fromParcel(in); - } - - @Override - public Input[] newArray(int size) { - return new Input[size]; - } - }; - - @Nonnull - private static Input fromParcel(@Nonnull Parcel in) { - final List messages = new ArrayList(); - boolean showCheckbox = in.readInt() == 1; - in.readTypedList(messages, FixableMessage.CREATOR); - return new Input(messages, showCheckbox); - } + final CharSequence fixCaption = fixableError.getFixCaption(); + if (!Strings.isEmpty(fixCaption)) { + fixButton.setText(fixCaption); + } + } - @Nonnull - private List messages = new ArrayList(); + viewGroup.addView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); + } - private boolean showCheckbox; + } - private Input(@Nonnull List messages, boolean showCheckbox) { - this.messages = messages; - this.showCheckbox = showCheckbox; - } + @Override + protected void onNewIntent(@Nonnull Intent intent) { + super.onNewIntent(intent); + parseIntent(intent); + } - @Nonnull - public List getMessages() { - return messages; - } + private static final class Input implements Parcelable { - @Override - public int describeContents() { - return 0; - } + public static final Creator CREATOR = new Creator() { + @Override + public Input createFromParcel(@Nonnull Parcel in) { + return Input.fromParcel(in); + } - @Override - public void writeToParcel(@Nonnull Parcel out, int flags) { - out.writeInt(showCheckbox ? 1 : 0); - out.writeTypedList(messages); - } + @Override + public Input[] newArray(int size) { + return new Input[size]; + } + }; + @Nonnull + private List messages = new ArrayList(); + private boolean showCheckbox; - @Nonnull - public static Input fromMessages(@Nonnull List messages, boolean showCheckbox) { - final List stringMessages = new ArrayList(messages.size()); - for (Message message : messages) { - stringMessages.add(new FixableMessage(message)); - } + private Input(@Nonnull List messages, boolean showCheckbox) { + this.messages = messages; + this.showCheckbox = showCheckbox; + } - return new Input(stringMessages, showCheckbox); - } + @Nonnull + private static Input fromParcel(@Nonnull Parcel in) { + final List messages = new ArrayList(); + boolean showCheckbox = in.readInt() == 1; + in.readTypedList(messages, FixableMessage.CREATOR); + return new Input(messages, showCheckbox); + } - public boolean isShowCheckbox() { - return showCheckbox; - } - } + @Nonnull + public static Input fromMessages(@Nonnull List messages, boolean showCheckbox) { + final List stringMessages = new ArrayList(messages.size()); + for (Message message : messages) { + stringMessages.add(new FixableMessage(message)); + } - private class FixErrorOnClickListener implements View.OnClickListener { + return new Input(stringMessages, showCheckbox); + } - @Nonnull - private final List messages; + @Nonnull + public List getMessages() { + return messages; + } - @Nonnull - private final FixableMessage currentMessage; + @Override + public int describeContents() { + return 0; + } - public FixErrorOnClickListener(@Nonnull List messages, - @Nonnull FixableMessage message) { - this.messages = messages; - this.currentMessage = message; - } + @Override + public void writeToParcel(@Nonnull Parcel out, int flags) { + out.writeInt(showCheckbox ? 1 : 0); + out.writeTypedList(messages); + } - @Override - public void onClick(View v) { - final List filteredMessages = new ArrayList(messages.size() - 1); - for (FixableMessage message : messages) { - if (message.getFixableError() == null) { - filteredMessages.add(message); - } else if (message.getFixableError() != currentMessage.getFixableError()) { - filteredMessages.add(message); - } - } + public boolean isShowCheckbox() { + return showCheckbox; + } + } - currentMessage.getFixableError().fix(); + private class FixErrorOnClickListener implements View.OnClickListener { - if (!filteredMessages.isEmpty()) { - FixableMessagesDialog.this.input = new Input(filteredMessages, FixableMessagesDialog.this.input.showCheckbox); - onInputChanged(); - } else { - FixableMessagesDialog.this.finish(); - } - } - } + @Nonnull + private final List messages; + + @Nonnull + private final FixableMessage currentMessage; + + public FixErrorOnClickListener(@Nonnull List messages, + @Nonnull FixableMessage message) { + this.messages = messages; + this.currentMessage = message; + } + + @Override + public void onClick(View v) { + final List filteredMessages = new ArrayList(messages.size() - 1); + for (FixableMessage message : messages) { + if (message.getFixableError() == null) { + filteredMessages.add(message); + } else if (message.getFixableError() != currentMessage.getFixableError()) { + filteredMessages.add(message); + } + } + + currentMessage.getFixableError().fix(); + + if (!filteredMessages.isEmpty()) { + FixableMessagesDialog.this.input = new Input(filteredMessages, FixableMessagesDialog.this.input.showCheckbox); + onInputChanged(); + } else { + FixableMessagesDialog.this.finish(); + } + } + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/FragmentUi.java b/android-app/src/main/java/org/solovyev/android/calculator/FragmentUi.java index ce1abb46..60d14830 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/FragmentUi.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/FragmentUi.java @@ -27,7 +27,6 @@ import android.support.v4.app.FragmentActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; -import android.view.ViewParent; import android.widget.TextView; import org.solovyev.android.checkout.ActivityCheckout; @@ -47,151 +46,151 @@ import javax.annotation.Nullable; */ public class FragmentUi extends BaseUi { - private ActivityCheckout checkout; + private ActivityCheckout checkout; - @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; - @Nullable - private Boolean adFree = null; + @Nullable + private Boolean adFree = null; - public FragmentUi(int layoutId) { - this.layoutId = layoutId; - } + public FragmentUi(int layoutId) { + this.layoutId = layoutId; + } - public FragmentUi(int layoutId, int titleResId) { - this.layoutId = layoutId; - this.titleResId = titleResId; - } + public FragmentUi(int layoutId, int titleResId) { + this.layoutId = layoutId; + this.titleResId = titleResId; + } - public FragmentUi(int layoutId, int titleResId, boolean listenersOnCreate) { - this.layoutId = layoutId; - this.titleResId = titleResId; - this.listenersOnCreate = listenersOnCreate; - } + public FragmentUi(int layoutId, int titleResId, boolean listenersOnCreate) { + this.layoutId = layoutId; + this.titleResId = titleResId; + this.listenersOnCreate = listenersOnCreate; + } - public boolean isPane(@Nonnull Fragment fragment) { - return fragment.getActivity() instanceof CalculatorActivity; - } + public boolean isPane(@Nonnull Fragment fragment) { + return fragment.getActivity() instanceof CalculatorActivity; + } - public void setPaneTitle(@Nonnull 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(Locale.getDefault())); - } - } - } + public void setPaneTitle(@Nonnull 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(Locale.getDefault())); + } + } + } - public void onCreate(@Nonnull Fragment fragment) { - final FragmentActivity activity = fragment.getActivity(); - super.onCreate(activity); - checkout = Checkout.forActivity(activity, App.getBilling(), App.getProducts()); + public void onCreate(@Nonnull Fragment fragment) { + final FragmentActivity activity = fragment.getActivity(); + super.onCreate(activity); + checkout = Checkout.forActivity(activity, App.getBilling(), App.getProducts()); - if (listenersOnCreate) { - if (fragment instanceof CalculatorEventListener) { - Locator.getInstance().getCalculator().addCalculatorEventListener((CalculatorEventListener) fragment); - } - } + if (listenersOnCreate) { + if (fragment instanceof CalculatorEventListener) { + Locator.getInstance().getCalculator().addCalculatorEventListener((CalculatorEventListener) fragment); + } + } - checkout.start(); - } + checkout.start(); + } - public void onResume(@Nonnull Fragment fragment) { - if (adView != null) { - adView.resume(); - } - if (!listenersOnCreate) { - if (fragment instanceof CalculatorEventListener) { - Locator.getInstance().getCalculator().addCalculatorEventListener((CalculatorEventListener) fragment); - } - } + public void onResume(@Nonnull Fragment fragment) { + if (adView != null) { + adView.resume(); + } + if (!listenersOnCreate) { + if (fragment instanceof CalculatorEventListener) { + Locator.getInstance().getCalculator().addCalculatorEventListener((CalculatorEventListener) fragment); + } + } - checkout.loadInventory().whenLoaded(new Inventory.Listener() { - @Override - public void onLoaded(@Nonnull Inventory.Products products) { - adFree = products.get(ProductTypes.IN_APP).isPurchased("ad_free"); - updateAdViewState(); - } - }); - } + checkout.loadInventory().whenLoaded(new Inventory.Listener() { + @Override + public void onLoaded(@Nonnull Inventory.Products products) { + adFree = products.get(ProductTypes.IN_APP).isPurchased("ad_free"); + updateAdViewState(); + } + }); + } - private void updateAdViewState() { - if(adFree == null || adView == null) { - return; - } + private void updateAdViewState() { + if (adFree == null || adView == null) { + return; + } - if (adFree) { - adView.hide(); - } else { - adView.show(); - } - } + if (adFree) { + adView.hide(); + } else { + adView.show(); + } + } - public void onPause(@Nonnull Fragment fragment) { - adFree = null; - if (adView != null) { - adView.pause(); - } - if (!listenersOnCreate) { - if (fragment instanceof CalculatorEventListener) { - Locator.getInstance().getCalculator().removeCalculatorEventListener((CalculatorEventListener) fragment); - } - } - } + public void onPause(@Nonnull Fragment fragment) { + adFree = null; + if (adView != null) { + adView.pause(); + } + if (!listenersOnCreate) { + if (fragment instanceof CalculatorEventListener) { + Locator.getInstance().getCalculator().removeCalculatorEventListener((CalculatorEventListener) fragment); + } + } + } - public void onViewCreated(@Nonnull Fragment fragment, @Nonnull View root) { - adView = (AdView) root.findViewById(R.id.ad); - final ViewGroup mainFragmentLayout = (ViewGroup) root.findViewById(R.id.main_fragment_layout); + public void onViewCreated(@Nonnull Fragment fragment, @Nonnull View root) { + adView = (AdView) root.findViewById(R.id.ad); + 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 (adView != null) { - updateAdViewState(); - } else if (mainFragmentLayout != null) { - } - } + if (fragment instanceof CalculatorDisplayFragment || fragment instanceof CalculatorEditorFragment || fragment instanceof CalculatorKeyboardFragment) { + // no ads in those fragments + } else { + if (adView != null) { + updateAdViewState(); + } else if (mainFragmentLayout != null) { + } + } - if (fragment instanceof CalculatorKeyboardFragment) { - processButtons(fragment.getActivity(), root); - } - fixFonts(root); + if (fragment instanceof CalculatorKeyboardFragment) { + processButtons(fragment.getActivity(), root); + } + fixFonts(root); - if (titleResId >= 0) { - this.setPaneTitle(fragment, titleResId); - } - } + if (titleResId >= 0) { + this.setPaneTitle(fragment, titleResId); + } + } - public void onDestroy(@Nonnull Fragment fragment) { - if (listenersOnCreate) { - if (fragment instanceof CalculatorEventListener) { - Locator.getInstance().getCalculator().removeCalculatorEventListener((CalculatorEventListener) fragment); - } - } + public void onDestroy(@Nonnull Fragment fragment) { + if (listenersOnCreate) { + if (fragment instanceof CalculatorEventListener) { + Locator.getInstance().getCalculator().removeCalculatorEventListener((CalculatorEventListener) fragment); + } + } - checkout.stop(); + checkout.stop(); - super.onDestroy(fragment.getActivity()); - } + super.onDestroy(fragment.getActivity()); + } - @Nonnull - public View onCreateView(@Nonnull Fragment fragment, @Nonnull LayoutInflater inflater, @Nullable ViewGroup container) { - return inflater.inflate(layoutId, container, false); - } + @Nonnull + public View onCreateView(@Nonnull Fragment fragment, @Nonnull LayoutInflater inflater, @Nullable ViewGroup container) { + return inflater.inflate(layoutId, container, false); + } - public void onDestroyView(@Nonnull Fragment fragment) { - if (adView != null) { - adView.destroy(); - adView = null; - } - } + public void onDestroyView(@Nonnull Fragment fragment) { + if (adView != null) { + adView.destroy(); + adView = null; + } + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/NumeralBaseButtons.java b/android-app/src/main/java/org/solovyev/android/calculator/NumeralBaseButtons.java index 184bfc99..5a8ebe82 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/NumeralBaseButtons.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/NumeralBaseButtons.java @@ -24,11 +24,10 @@ package org.solovyev.android.calculator; import android.app.Activity; import android.content.SharedPreferences; -import jscl.NumeralBase; import javax.annotation.Nonnull; -import org.solovyev.android.calculator.model.AndroidCalculatorEngine; +import jscl.NumeralBase; import static jscl.NumeralBase.hex; import static org.solovyev.android.calculator.Preferences.Gui.hideNumeralBaseDigits; @@ -41,23 +40,23 @@ import static org.solovyev.android.calculator.model.AndroidCalculatorEngine.Pref */ public class NumeralBaseButtons { - public static void toggleNumericDigits(@Nonnull Activity activity, @Nonnull NumeralBase currentNumeralBase) { - for (NumeralBase numeralBase : NumeralBase.values()) { - if (currentNumeralBase != numeralBase) { - AndroidNumeralBase.valueOf(numeralBase).toggleButtons(false, activity); - } - } + public static void toggleNumericDigits(@Nonnull Activity activity, @Nonnull 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(@Nonnull Activity activity, @Nonnull SharedPreferences preferences) { - if (hideNumeralBaseDigits.getPreference(preferences)) { - final NumeralBase nb = numeralBase.getPreference(preferences); - toggleNumericDigits(activity, nb); - } else { - // set HEX to show all digits - AndroidNumeralBase.valueOf(hex).toggleButtons(true, activity); - } - } + public static void toggleNumericDigits(@Nonnull Activity activity, @Nonnull SharedPreferences preferences) { + if (hideNumeralBaseDigits.getPreference(preferences)) { + final NumeralBase nb = numeralBase.getPreference(preferences); + toggleNumericDigits(activity, nb); + } else { + // set HEX to show all digits + AndroidNumeralBase.valueOf(hex).toggleButtons(true, activity); + } + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/ParcelableDialogData.java b/android-app/src/main/java/org/solovyev/android/calculator/ParcelableDialogData.java index 38c03794..4206ad22 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/ParcelableDialogData.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/ParcelableDialogData.java @@ -24,6 +24,7 @@ package org.solovyev.android.calculator; import android.os.Parcel; import android.os.Parcelable; + import org.solovyev.common.msg.MessageLevel; import org.solovyev.common.msg.MessageType; @@ -38,24 +39,24 @@ import javax.annotation.Nullable; public final class ParcelableDialogData implements DialogData, Parcelable { /* - ********************************************************************** + ********************************************************************** * * STATIC * ********************************************************************** */ - public final static Creator CREATOR = new Creator() { - @Override - public ParcelableDialogData createFromParcel(@Nonnull Parcel in) { - return fromParcel(in); - } + public final static Creator CREATOR = new Creator() { + @Override + public ParcelableDialogData createFromParcel(@Nonnull Parcel in) { + return fromParcel(in); + } - @Override - public ParcelableDialogData[] newArray(int size) { - return new ParcelableDialogData[size]; - } - }; + @Override + public ParcelableDialogData[] newArray(int size) { + return new ParcelableDialogData[size]; + } + }; /* ********************************************************************** @@ -65,8 +66,8 @@ public final class ParcelableDialogData implements DialogData, Parcelable { ********************************************************************** */ - @Nonnull - private DialogData nestedData; + @Nonnull + private DialogData nestedData; /* ********************************************************************** @@ -76,54 +77,54 @@ public final class ParcelableDialogData implements DialogData, Parcelable { ********************************************************************** */ - public ParcelableDialogData(@Nonnull DialogData nestedData) { - this.nestedData = nestedData; - } + public ParcelableDialogData(@Nonnull DialogData nestedData) { + this.nestedData = nestedData; + } - @Nonnull - public static ParcelableDialogData wrap(@Nonnull DialogData nestedData) { - if (nestedData instanceof ParcelableDialogData) { - return ((ParcelableDialogData) nestedData); - } else { - return new ParcelableDialogData(nestedData); - } - } + @Nonnull + public static ParcelableDialogData wrap(@Nonnull DialogData nestedData) { + if (nestedData instanceof ParcelableDialogData) { + return ((ParcelableDialogData) nestedData); + } else { + return new ParcelableDialogData(nestedData); + } + } - @Nonnull - public static ParcelableDialogData fromParcel(@Nonnull Parcel in) { - final String message = in.readString(); - final MessageType messageType = CalculatorMessages.toMessageType(in.readInt()); - final String title = in.readString(); - return wrap(StringDialogData.newInstance(message, messageType, title)); - } + @Nonnull + public static ParcelableDialogData fromParcel(@Nonnull Parcel in) { + final String message = in.readString(); + final MessageType messageType = CalculatorMessages.toMessageType(in.readInt()); + final String title = in.readString(); + return wrap(StringDialogData.newInstance(message, messageType, title)); + } - @Nonnull - @Override - public String getMessage() { - return nestedData.getMessage(); - } + @Nonnull + @Override + public String getMessage() { + return nestedData.getMessage(); + } - @Nonnull - @Override - public MessageLevel getMessageLevel() { - return nestedData.getMessageLevel(); - } + @Nonnull + @Override + public MessageLevel getMessageLevel() { + return nestedData.getMessageLevel(); + } - @Nullable - @Override - public String getTitle() { - return nestedData.getTitle(); - } + @Nullable + @Override + public String getTitle() { + return nestedData.getTitle(); + } - @Override - public int describeContents() { - return 0; - } + @Override + public int describeContents() { + return 0; + } - @Override - public void writeToParcel(@Nonnull Parcel out, int flags) { - out.writeString(this.getMessage()); - out.writeInt(this.getMessageLevel().getMessageLevel()); - out.writeString(this.getTitle()); - } + @Override + public void writeToParcel(@Nonnull Parcel out, int flags) { + out.writeString(this.getMessage()); + out.writeInt(this.getMessageLevel().getMessageLevel()); + out.writeString(this.getTitle()); + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/Preferences.java b/android-app/src/main/java/org/solovyev/android/calculator/Preferences.java index 020b012f..b8133fc5 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/Preferences.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/Preferences.java @@ -61,347 +61,345 @@ import static org.solovyev.android.DeviceModel.samsung_galaxy_s_2; public final class Preferences { - private Preferences() { - throw new AssertionError(); - } - - public static final Preference appVersion = IntegerPreference.of("application.version", -1); - public static final Preference appOpenedCounter = IntegerPreference.of("app_opened_counter", 0); - - public enum SimpleTheme { - - default_theme(0, 0, null), - metro_blue_theme(R.layout.onscreen_layout, R.layout.widget_layout, Gui.Theme.metro_blue_theme), - material_theme(R.layout.onscreen_layout_material, R.layout.widget_layout_material, Gui.Theme.material_theme), - material_light_theme(R.layout.onscreen_layout_material_light, R.layout.widget_layout_material_light, Gui.Theme.material_light_theme); - - @LayoutRes - private final int onscreenLayout; - - @LayoutRes - private final int widgetLayout; - - @Nullable - private final Gui.Theme appTheme; - - @Nonnull - private final Map cache = new EnumMap<>(Gui.Theme.class); - - SimpleTheme(int onscreenLayout, int widgetLayout, @Nullable Gui.Theme appTheme) { - this.onscreenLayout = onscreenLayout; - this.widgetLayout = widgetLayout; - this.appTheme = appTheme; - } - - public int getOnscreenLayout(@Nonnull Gui.Theme appTheme) { - return resolveThemeFor(appTheme).onscreenLayout; - } - - public int getWidgetLayout(@Nonnull Gui.Theme appTheme) { - return resolveThemeFor(appTheme).widgetLayout; - } - - @Nonnull - public SimpleTheme resolveThemeFor(@Nonnull Gui.Theme appTheme) { - if (this == default_theme) { - SimpleTheme theme = cache.get(appTheme); - if (theme == null) { - theme = lookUpThemeFor(appTheme); - cache.put(appTheme, theme); - } - return theme; - } - return this; - } - - @Nonnull - private SimpleTheme lookUpThemeFor(@Nonnull Gui.Theme appTheme) { - Check.isTrue(this == default_theme); - // find direct match - for (SimpleTheme theme : values()) { - if (theme.appTheme == appTheme) { - return theme; - } - } - - // for metro themes return metro theme - if (appTheme == Gui.Theme.metro_green_theme || appTheme == Gui.Theme.metro_purple_theme) { - return metro_blue_theme; - } - - // for old themes return dark material - return material_theme; - } - - @Nullable - public Gui.Theme getAppTheme() { - return appTheme; - } - } - - public static class Widget { - public static final Preference theme = StringPreference.ofEnum("widget.theme", SimpleTheme.default_theme, SimpleTheme.class); - - @Nonnull - public static SimpleTheme getTheme(@Nonnull SharedPreferences preferences) { - return theme.getPreferenceNoError(preferences); - } - - } - public static class Onscreen { - public static final Preference startOnBoot = BooleanPreference.of("onscreen_start_on_boot", false); - public static final Preference showAppIcon = BooleanPreference.of("onscreen_show_app_icon", true); - public static final Preference theme = StringPreference.ofEnum("onscreen.theme", SimpleTheme.default_theme, SimpleTheme.class); - - @Nonnull - public static SimpleTheme getTheme(@Nonnull SharedPreferences preferences) { - return theme.getPreferenceNoError(preferences); - } - } - - public static class Calculations { - - public static final Preference calculateOnFly = BooleanPreference.of("calculations_calculate_on_fly", true); - public static final Preference showCalculationMessagesDialog = BooleanPreference.of("show_calculation_messages_dialog", true); - - public static final Preference preferredNumeralBase = StringPreference.ofEnum("preferred_numeral_base", AndroidCalculatorEngine.Preferences.numeralBase.getDefaultValue(), NumeralBase.class); - public static final Preference preferredAngleUnits = StringPreference.ofEnum("preferred_angle_units", AndroidCalculatorEngine.Preferences.angleUnit.getDefaultValue(), AngleUnit.class); - public static final Preference lastPreferredPreferencesCheck = LongPreference.of("preferred_preferences_check_time", 0L); - - } - - public static class Ga { - public static final Preference initialReportDone = BooleanPreference.of("ga.initial_report_done", false); - } - - public static class Gui { - - public static final Preference theme = StringPreference.ofEnum("org.solovyev.android.calculator.CalculatorActivity_calc_theme", Theme.material_theme, Theme.class); - public static final Preference layout = StringPreference.ofEnum("org.solovyev.android.calculator.CalculatorActivity_calc_layout", Layout.simple, Layout.class); - public static final Preference language = StringPreference.of("gui.language", Languages.SYSTEM_LANGUAGE_CODE); - public static final Preference feedbackWindowShown = BooleanPreference.of("feedback_window_shown", false); - public static final Preference showReleaseNotes = BooleanPreference.of("org.solovyev.android.calculator.CalculatorActivity_show_release_notes", true); - public static final Preference usePrevAsBack = BooleanPreference.of("org.solovyev.android.calculator.CalculatorActivity_use_back_button_as_prev", false); - public static final Preference showEqualsButton = BooleanPreference.of("showEqualsButton", true); - public static final Preference autoOrientation = BooleanPreference.of("autoOrientation", true); - public static final Preference hideNumeralBaseDigits = BooleanPreference.of("hideNumeralBaseDigits", true); - public static final Preference preventScreenFromFading = BooleanPreference.of("preventScreenFromFading", true); - public static final Preference colorDisplay = BooleanPreference.of("org.solovyev.android.calculator.CalculatorModel_color_display", true); - public static final Preference hapticFeedback = NumberToStringPreference.of("hapticFeedback", 60L, Long.class); - - private static final Preference hapticFeedbackEnabled = BooleanPreference.of("org.solovyev.android.calculator.CalculatorModel_haptic_feedback", false); - private static final Preference hapticFeedbackDuration = NumberToStringPreference.of("org.solovyev.android.calculator.CalculatorActivity_calc_haptic_feedback_duration_key", 60L, Long.class); - - @Nonnull - public static Theme getTheme(@Nonnull SharedPreferences preferences) { - return theme.getPreferenceNoError(preferences); - } - - @Nonnull - public static Layout getLayout(@Nonnull SharedPreferences preferences) { - return layout.getPreferenceNoError(preferences); - } - - public enum Theme { - - default_theme(R.style.Cpp_Theme_Gray), - violet_theme(R.style.Cpp_Theme_Violet), - light_blue_theme(R.style.Cpp_Theme_Blue), - metro_blue_theme(R.style.cpp_metro_blue_theme), - metro_purple_theme(R.style.cpp_metro_purple_theme), - metro_green_theme(R.style.cpp_metro_green_theme), - material_theme(R.style.Cpp_Theme_Material), - material_light_theme(R.style.Cpp_Theme_Material_Light, R.style.Cpp_Theme_Wizard_Light, R.style.Cpp_Theme_Dialog_Material_Light), - ; - - private static final SparseArray textColors = new SparseArray<>(); - - private final int themeId; - private final int wizardThemeId; - private final int dialogThemeId; - - Theme(@StyleRes int themeId) { - this(themeId, R.style.Cpp_Theme_Wizard, R.style.Cpp_Theme_Dialog_Material); - } - - Theme(@StyleRes int themeId, @StyleRes int wizardThemeId, int dialogThemeId) { - this.themeId = themeId; - this.wizardThemeId = wizardThemeId; - this.dialogThemeId = dialogThemeId; - } - - public int getThemeId() { - return getThemeId(null); - } - - public int getThemeId(@Nullable Context context) { - if (context instanceof WizardActivity) { - return wizardThemeId; - } - if (context instanceof PurchaseDialogActivity) { - return dialogThemeId; - } - return themeId; - } - - @Nonnull - public TextColor getTextColor(@Nonnull Context context) { - final int themeId = getThemeId(context); - TextColor textColor = textColors.get(themeId); - if (textColor == null) { - final ContextThemeWrapper themeContext = new ContextThemeWrapper(context, themeId); - final TypedArray a = themeContext.obtainStyledAttributes(themeId, new int[]{R.attr.cpp_text_color, R.attr.cpp_text_color_error}); - final int normal = a.getColor(0, Color.BLACK); - final int error = a.getColor(1, Color.WHITE); - a.recycle(); - textColor = new TextColor(normal, error); - textColors.append(themeId, textColor); - } - return textColor; - } - - public boolean isLight() { - return themeId == R.style.Cpp_Theme_Material_Light; - } - } - - public static final class TextColor { - public final int normal; - public final int error; - - TextColor(int normal, int error) { - this.normal = normal; - this.error = error; - } - } - - public static enum Layout { - main_calculator(R.layout.main_calculator, R.string.p_layout_calculator, true), - main_calculator_mobile(R.layout.main_calculator_mobile, R.string.p_layout_calculator_mobile, false), - - // not used anymore - @Deprecated - main_cellphone(R.layout.main_calculator, 0, true), - - simple(R.layout.main_calculator, R.string.p_layout_simple, true), - simple_mobile(R.layout.main_calculator_mobile, R.string.p_layout_simple_mobile, false); - - private final int layoutId; - private final int nameResId; - private final boolean optimized; - - Layout(int layoutId, int nameResId, boolean optimized) { - this.layoutId = layoutId; - this.nameResId = nameResId; - this.optimized = optimized; - } - - public int getLayoutId() { - return layoutId; - } - - public int getNameResId() { - return nameResId; - } - - public boolean isOptimized() { - return optimized; - } - } - } - - public static class Graph { - public static final Preference plotImag = BooleanPreference.of("graph_plot_imag", false); - } - - public static class History { - public static final Preference showIntermediateCalculations = BooleanPreference.of("history_show_intermediate_calculations", false); - public static final Preference showDatetime = BooleanPreference.of("history_show_datetime", true); - } - - - static void setDefaultValues(@Nonnull SharedPreferences preferences) { - - if (!AndroidCalculatorEngine.Preferences.groupingSeparator.isSet(preferences)) { - final Locale locale = Locale.getDefault(); - if (locale != null) { - final DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols(locale); - int index = MathType.grouping_separator.getTokens().indexOf(String.valueOf(decimalFormatSymbols.getGroupingSeparator())); - final String groupingSeparator; - if (index >= 0) { - groupingSeparator = MathType.grouping_separator.getTokens().get(index); - } else { - groupingSeparator = " "; - } - - AndroidCalculatorEngine.Preferences.groupingSeparator.putPreference(preferences, groupingSeparator); - } - } - - if (!AndroidCalculatorEngine.Preferences.angleUnit.isSet(preferences)) { - AndroidCalculatorEngine.Preferences.angleUnit.putDefault(preferences); - } - - if (!AndroidCalculatorEngine.Preferences.numeralBase.isSet(preferences)) { - AndroidCalculatorEngine.Preferences.numeralBase.putDefault(preferences); - } - - if (!AndroidCalculatorEngine.Preferences.multiplicationSign.isSet(preferences)) { - if (isPhoneModel(samsung_galaxy_s) || isPhoneModel(samsung_galaxy_s_2)) { - // workaround ofr samsung galaxy s phones - AndroidCalculatorEngine.Preferences.multiplicationSign.putPreference(preferences, "*"); - } - } - - applyDefaultPreference(preferences, Gui.theme); - applyDefaultPreference(preferences, Gui.layout); - if (Gui.layout.getPreference(preferences) == Gui.Layout.main_cellphone) { - Gui.layout.putDefault(preferences); - } - applyDefaultPreference(preferences, Gui.feedbackWindowShown); - applyDefaultPreference(preferences, Gui.showReleaseNotes); - applyDefaultPreference(preferences, Gui.usePrevAsBack); - applyDefaultPreference(preferences, Gui.showEqualsButton); - applyDefaultPreference(preferences, Gui.autoOrientation); - applyDefaultPreference(preferences, Gui.hideNumeralBaseDigits); - applyDefaultPreference(preferences, Gui.preventScreenFromFading); - applyDefaultPreference(preferences, Gui.language); - - applyDefaultPreference(preferences, Graph.plotImag); - applyDefaultPreference(preferences, History.showIntermediateCalculations); - applyDefaultPreference(preferences, History.showDatetime); - applyDefaultPreference(preferences, Calculations.calculateOnFly); - applyDefaultPreference(preferences, Calculations.preferredAngleUnits); - applyDefaultPreference(preferences, Calculations.preferredNumeralBase); - - applyDefaultPreference(preferences, Onscreen.showAppIcon); - applyDefaultPreference(preferences, Onscreen.startOnBoot); - applyDefaultPreference(preferences, Onscreen.theme); - - applyDefaultPreference(preferences, Widget.theme); - - applyDefaultPreference(preferences, Ga.initialReportDone); - - - // renew value after each application start - Calculations.showCalculationMessagesDialog.putDefault(preferences); - Calculations.lastPreferredPreferencesCheck.putDefault(preferences); - - if (!Gui.hapticFeedback.isSet(preferences)) { - final Preference hfEnabled = Gui.hapticFeedbackEnabled; - final boolean enabled = !hfEnabled.isSet(preferences) ? true : hfEnabled.getPreference(preferences); - if (enabled) { - final Preference hfDuration = Gui.hapticFeedbackDuration; - final long duration = !hfDuration.isSet(preferences) ? 60L : hfDuration.getPreference(preferences); - Gui.hapticFeedback.putPreference(preferences, duration); - } else { - Gui.hapticFeedback.putPreference(preferences, 0L); - } - } - } - - private static void applyDefaultPreference(@Nonnull SharedPreferences preferences, @Nonnull Preference preference) { - preference.tryPutDefault(preferences); - } + public static final Preference appVersion = IntegerPreference.of("application.version", -1); + public static final Preference appOpenedCounter = IntegerPreference.of("app_opened_counter", 0); + private Preferences() { + throw new AssertionError(); + } + + static void setDefaultValues(@Nonnull SharedPreferences preferences) { + + if (!AndroidCalculatorEngine.Preferences.groupingSeparator.isSet(preferences)) { + final Locale locale = Locale.getDefault(); + if (locale != null) { + final DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols(locale); + int index = MathType.grouping_separator.getTokens().indexOf(String.valueOf(decimalFormatSymbols.getGroupingSeparator())); + final String groupingSeparator; + if (index >= 0) { + groupingSeparator = MathType.grouping_separator.getTokens().get(index); + } else { + groupingSeparator = " "; + } + + AndroidCalculatorEngine.Preferences.groupingSeparator.putPreference(preferences, groupingSeparator); + } + } + + if (!AndroidCalculatorEngine.Preferences.angleUnit.isSet(preferences)) { + AndroidCalculatorEngine.Preferences.angleUnit.putDefault(preferences); + } + + if (!AndroidCalculatorEngine.Preferences.numeralBase.isSet(preferences)) { + AndroidCalculatorEngine.Preferences.numeralBase.putDefault(preferences); + } + + if (!AndroidCalculatorEngine.Preferences.multiplicationSign.isSet(preferences)) { + if (isPhoneModel(samsung_galaxy_s) || isPhoneModel(samsung_galaxy_s_2)) { + // workaround ofr samsung galaxy s phones + AndroidCalculatorEngine.Preferences.multiplicationSign.putPreference(preferences, "*"); + } + } + + applyDefaultPreference(preferences, Gui.theme); + applyDefaultPreference(preferences, Gui.layout); + if (Gui.layout.getPreference(preferences) == Gui.Layout.main_cellphone) { + Gui.layout.putDefault(preferences); + } + applyDefaultPreference(preferences, Gui.feedbackWindowShown); + applyDefaultPreference(preferences, Gui.showReleaseNotes); + applyDefaultPreference(preferences, Gui.usePrevAsBack); + applyDefaultPreference(preferences, Gui.showEqualsButton); + applyDefaultPreference(preferences, Gui.autoOrientation); + applyDefaultPreference(preferences, Gui.hideNumeralBaseDigits); + applyDefaultPreference(preferences, Gui.preventScreenFromFading); + applyDefaultPreference(preferences, Gui.language); + + applyDefaultPreference(preferences, Graph.plotImag); + applyDefaultPreference(preferences, History.showIntermediateCalculations); + applyDefaultPreference(preferences, History.showDatetime); + applyDefaultPreference(preferences, Calculations.calculateOnFly); + applyDefaultPreference(preferences, Calculations.preferredAngleUnits); + applyDefaultPreference(preferences, Calculations.preferredNumeralBase); + + applyDefaultPreference(preferences, Onscreen.showAppIcon); + applyDefaultPreference(preferences, Onscreen.startOnBoot); + applyDefaultPreference(preferences, Onscreen.theme); + + applyDefaultPreference(preferences, Widget.theme); + + applyDefaultPreference(preferences, Ga.initialReportDone); + + + // renew value after each application start + Calculations.showCalculationMessagesDialog.putDefault(preferences); + Calculations.lastPreferredPreferencesCheck.putDefault(preferences); + + if (!Gui.hapticFeedback.isSet(preferences)) { + final Preference hfEnabled = Gui.hapticFeedbackEnabled; + final boolean enabled = !hfEnabled.isSet(preferences) ? true : hfEnabled.getPreference(preferences); + if (enabled) { + final Preference hfDuration = Gui.hapticFeedbackDuration; + final long duration = !hfDuration.isSet(preferences) ? 60L : hfDuration.getPreference(preferences); + Gui.hapticFeedback.putPreference(preferences, duration); + } else { + Gui.hapticFeedback.putPreference(preferences, 0L); + } + } + } + + private static void applyDefaultPreference(@Nonnull SharedPreferences preferences, @Nonnull Preference preference) { + preference.tryPutDefault(preferences); + } + + public enum SimpleTheme { + + default_theme(0, 0, null), + metro_blue_theme(R.layout.onscreen_layout, R.layout.widget_layout, Gui.Theme.metro_blue_theme), + material_theme(R.layout.onscreen_layout_material, R.layout.widget_layout_material, Gui.Theme.material_theme), + material_light_theme(R.layout.onscreen_layout_material_light, R.layout.widget_layout_material_light, Gui.Theme.material_light_theme); + + @LayoutRes + private final int onscreenLayout; + + @LayoutRes + private final int widgetLayout; + + @Nullable + private final Gui.Theme appTheme; + + @Nonnull + private final Map cache = new EnumMap<>(Gui.Theme.class); + + SimpleTheme(int onscreenLayout, int widgetLayout, @Nullable Gui.Theme appTheme) { + this.onscreenLayout = onscreenLayout; + this.widgetLayout = widgetLayout; + this.appTheme = appTheme; + } + + public int getOnscreenLayout(@Nonnull Gui.Theme appTheme) { + return resolveThemeFor(appTheme).onscreenLayout; + } + + public int getWidgetLayout(@Nonnull Gui.Theme appTheme) { + return resolveThemeFor(appTheme).widgetLayout; + } + + @Nonnull + public SimpleTheme resolveThemeFor(@Nonnull Gui.Theme appTheme) { + if (this == default_theme) { + SimpleTheme theme = cache.get(appTheme); + if (theme == null) { + theme = lookUpThemeFor(appTheme); + cache.put(appTheme, theme); + } + return theme; + } + return this; + } + + @Nonnull + private SimpleTheme lookUpThemeFor(@Nonnull Gui.Theme appTheme) { + Check.isTrue(this == default_theme); + // find direct match + for (SimpleTheme theme : values()) { + if (theme.appTheme == appTheme) { + return theme; + } + } + + // for metro themes return metro theme + if (appTheme == Gui.Theme.metro_green_theme || appTheme == Gui.Theme.metro_purple_theme) { + return metro_blue_theme; + } + + // for old themes return dark material + return material_theme; + } + + @Nullable + public Gui.Theme getAppTheme() { + return appTheme; + } + } + + public static class Widget { + public static final Preference theme = StringPreference.ofEnum("widget.theme", SimpleTheme.default_theme, SimpleTheme.class); + + @Nonnull + public static SimpleTheme getTheme(@Nonnull SharedPreferences preferences) { + return theme.getPreferenceNoError(preferences); + } + + } + + public static class Onscreen { + public static final Preference startOnBoot = BooleanPreference.of("onscreen_start_on_boot", false); + public static final Preference showAppIcon = BooleanPreference.of("onscreen_show_app_icon", true); + public static final Preference theme = StringPreference.ofEnum("onscreen.theme", SimpleTheme.default_theme, SimpleTheme.class); + + @Nonnull + public static SimpleTheme getTheme(@Nonnull SharedPreferences preferences) { + return theme.getPreferenceNoError(preferences); + } + } + + public static class Calculations { + + public static final Preference calculateOnFly = BooleanPreference.of("calculations_calculate_on_fly", true); + public static final Preference showCalculationMessagesDialog = BooleanPreference.of("show_calculation_messages_dialog", true); + + public static final Preference preferredNumeralBase = StringPreference.ofEnum("preferred_numeral_base", AndroidCalculatorEngine.Preferences.numeralBase.getDefaultValue(), NumeralBase.class); + public static final Preference preferredAngleUnits = StringPreference.ofEnum("preferred_angle_units", AndroidCalculatorEngine.Preferences.angleUnit.getDefaultValue(), AngleUnit.class); + public static final Preference lastPreferredPreferencesCheck = LongPreference.of("preferred_preferences_check_time", 0L); + + } + + public static class Ga { + public static final Preference initialReportDone = BooleanPreference.of("ga.initial_report_done", false); + } + + public static class Gui { + + public static final Preference theme = StringPreference.ofEnum("org.solovyev.android.calculator.CalculatorActivity_calc_theme", Theme.material_theme, Theme.class); + public static final Preference layout = StringPreference.ofEnum("org.solovyev.android.calculator.CalculatorActivity_calc_layout", Layout.simple, Layout.class); + public static final Preference language = StringPreference.of("gui.language", Languages.SYSTEM_LANGUAGE_CODE); + public static final Preference feedbackWindowShown = BooleanPreference.of("feedback_window_shown", false); + public static final Preference showReleaseNotes = BooleanPreference.of("org.solovyev.android.calculator.CalculatorActivity_show_release_notes", true); + public static final Preference usePrevAsBack = BooleanPreference.of("org.solovyev.android.calculator.CalculatorActivity_use_back_button_as_prev", false); + public static final Preference showEqualsButton = BooleanPreference.of("showEqualsButton", true); + public static final Preference autoOrientation = BooleanPreference.of("autoOrientation", true); + public static final Preference hideNumeralBaseDigits = BooleanPreference.of("hideNumeralBaseDigits", true); + public static final Preference preventScreenFromFading = BooleanPreference.of("preventScreenFromFading", true); + public static final Preference colorDisplay = BooleanPreference.of("org.solovyev.android.calculator.CalculatorModel_color_display", true); + public static final Preference hapticFeedback = NumberToStringPreference.of("hapticFeedback", 60L, Long.class); + + private static final Preference hapticFeedbackEnabled = BooleanPreference.of("org.solovyev.android.calculator.CalculatorModel_haptic_feedback", false); + private static final Preference hapticFeedbackDuration = NumberToStringPreference.of("org.solovyev.android.calculator.CalculatorActivity_calc_haptic_feedback_duration_key", 60L, Long.class); + + @Nonnull + public static Theme getTheme(@Nonnull SharedPreferences preferences) { + return theme.getPreferenceNoError(preferences); + } + + @Nonnull + public static Layout getLayout(@Nonnull SharedPreferences preferences) { + return layout.getPreferenceNoError(preferences); + } + + public enum Theme { + + default_theme(R.style.Cpp_Theme_Gray), + violet_theme(R.style.Cpp_Theme_Violet), + light_blue_theme(R.style.Cpp_Theme_Blue), + metro_blue_theme(R.style.cpp_metro_blue_theme), + metro_purple_theme(R.style.cpp_metro_purple_theme), + metro_green_theme(R.style.cpp_metro_green_theme), + material_theme(R.style.Cpp_Theme_Material), + material_light_theme(R.style.Cpp_Theme_Material_Light, R.style.Cpp_Theme_Wizard_Light, R.style.Cpp_Theme_Dialog_Material_Light),; + + private static final SparseArray textColors = new SparseArray<>(); + + private final int themeId; + private final int wizardThemeId; + private final int dialogThemeId; + + Theme(@StyleRes int themeId) { + this(themeId, R.style.Cpp_Theme_Wizard, R.style.Cpp_Theme_Dialog_Material); + } + + Theme(@StyleRes int themeId, @StyleRes int wizardThemeId, int dialogThemeId) { + this.themeId = themeId; + this.wizardThemeId = wizardThemeId; + this.dialogThemeId = dialogThemeId; + } + + public int getThemeId() { + return getThemeId(null); + } + + public int getThemeId(@Nullable Context context) { + if (context instanceof WizardActivity) { + return wizardThemeId; + } + if (context instanceof PurchaseDialogActivity) { + return dialogThemeId; + } + return themeId; + } + + @Nonnull + public TextColor getTextColor(@Nonnull Context context) { + final int themeId = getThemeId(context); + TextColor textColor = textColors.get(themeId); + if (textColor == null) { + final ContextThemeWrapper themeContext = new ContextThemeWrapper(context, themeId); + final TypedArray a = themeContext.obtainStyledAttributes(themeId, new int[]{R.attr.cpp_text_color, R.attr.cpp_text_color_error}); + final int normal = a.getColor(0, Color.BLACK); + final int error = a.getColor(1, Color.WHITE); + a.recycle(); + textColor = new TextColor(normal, error); + textColors.append(themeId, textColor); + } + return textColor; + } + + public boolean isLight() { + return themeId == R.style.Cpp_Theme_Material_Light; + } + } + + public static enum Layout { + main_calculator(R.layout.main_calculator, R.string.p_layout_calculator, true), + main_calculator_mobile(R.layout.main_calculator_mobile, R.string.p_layout_calculator_mobile, false), + + // not used anymore + @Deprecated + main_cellphone(R.layout.main_calculator, 0, true), + + simple(R.layout.main_calculator, R.string.p_layout_simple, true), + simple_mobile(R.layout.main_calculator_mobile, R.string.p_layout_simple_mobile, false); + + private final int layoutId; + private final int nameResId; + private final boolean optimized; + + Layout(int layoutId, int nameResId, boolean optimized) { + this.layoutId = layoutId; + this.nameResId = nameResId; + this.optimized = optimized; + } + + public int getLayoutId() { + return layoutId; + } + + public int getNameResId() { + return nameResId; + } + + public boolean isOptimized() { + return optimized; + } + } + + public static final class TextColor { + public final int normal; + public final int error; + + TextColor(int normal, int error) { + this.normal = normal; + this.error = error; + } + } + } + + public static class Graph { + public static final Preference plotImag = BooleanPreference.of("graph_plot_imag", false); + } + + public static class History { + public static final Preference showIntermediateCalculations = BooleanPreference.of("history_show_intermediate_calculations", false); + public static final Preference showDatetime = BooleanPreference.of("history_show_datetime", true); + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/Vibrator.java b/android-app/src/main/java/org/solovyev/android/calculator/Vibrator.java index b646fa42..8ae957d3 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/Vibrator.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/Vibrator.java @@ -8,35 +8,35 @@ import javax.annotation.Nonnull; public final class Vibrator implements SharedPreferences.OnSharedPreferenceChangeListener { - @Nonnull - private final android.os.Vibrator service; + @Nonnull + private final android.os.Vibrator service; - private long time = 0; + private long time = 0; - public Vibrator(@Nonnull Context context, @Nonnull SharedPreferences preferences) { - service = (android.os.Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); - preferences.registerOnSharedPreferenceChangeListener(this); - updateTime(preferences); - } + public Vibrator(@Nonnull Context context, @Nonnull SharedPreferences preferences) { + service = (android.os.Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); + preferences.registerOnSharedPreferenceChangeListener(this); + updateTime(preferences); + } - private void updateTime(@Nonnull SharedPreferences preferences) { - time = Preferences.Gui.hapticFeedback.getPreference(preferences) / 2; - } + private void updateTime(@Nonnull SharedPreferences preferences) { + time = Preferences.Gui.hapticFeedback.getPreference(preferences) / 2; + } - public void vibrate() { - try { - if (time > 0) { - service.vibrate(time); - } - } catch (SecurityException e) { - Log.e("Vibrator", e.getMessage(), e); - } - } + public void vibrate() { + try { + if (time > 0) { + service.vibrate(time); + } + } catch (SecurityException e) { + Log.e("Vibrator", e.getMessage(), e); + } + } - @Override - public void onSharedPreferenceChanged(@Nonnull SharedPreferences preferences, String key) { - if (Preferences.Gui.hapticFeedback.isSameKey(key)) { - updateTime(preferences); - } - } + @Override + public void onSharedPreferenceChanged(@Nonnull SharedPreferences preferences, String key) { + if (Preferences.Gui.hapticFeedback.isSameKey(key)) { + updateTime(preferences); + } + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/about/CalculatorAboutActivity.java b/android-app/src/main/java/org/solovyev/android/calculator/about/CalculatorAboutActivity.java index bcfd8e57..3785f188 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/about/CalculatorAboutActivity.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/about/CalculatorAboutActivity.java @@ -23,8 +23,9 @@ package org.solovyev.android.calculator.about; import android.os.Bundle; -import org.solovyev.android.calculator.EmptyActivity; + import org.solovyev.android.calculator.CalculatorFragmentType; +import org.solovyev.android.calculator.EmptyActivity; import org.solovyev.android.calculator.R; import javax.annotation.Nullable; @@ -36,11 +37,11 @@ import javax.annotation.Nullable; */ public class CalculatorAboutActivity extends EmptyActivity { - @Override - public void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); + @Override + public void onCreate(@Nullable Bundle savedInstanceState) { + super.onCreate(savedInstanceState); - getUi().addTab(this, CalculatorFragmentType.about, null, R.id.main_layout); - getUi().addTab(this, CalculatorFragmentType.release_notes, null, R.id.main_layout); - } + getUi().addTab(this, CalculatorFragmentType.about, null, R.id.main_layout); + getUi().addTab(this, CalculatorFragmentType.release_notes, null, R.id.main_layout); + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/about/CalculatorAboutFragment.java b/android-app/src/main/java/org/solovyev/android/calculator/about/CalculatorAboutFragment.java index 361f14d7..6d39ccc2 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/about/CalculatorAboutFragment.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/about/CalculatorAboutFragment.java @@ -27,6 +27,7 @@ import android.text.method.LinkMovementMethod; import android.view.View; import android.widget.ImageView; import android.widget.TextView; + import org.solovyev.android.calculator.App; import org.solovyev.android.calculator.CalculatorFragment; import org.solovyev.android.calculator.CalculatorFragmentType; @@ -42,27 +43,27 @@ import static org.solovyev.common.text.Strings.isEmpty; */ 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); - if (App.getTheme().isLight()) { - final ImageView image = (ImageView) root.findViewById(R.id.about_image); - image.setImageResource(R.drawable.logo_wizard_light); - } + if (App.getTheme().isLight()) { + final ImageView image = (ImageView) root.findViewById(R.id.about_image); + image.setImageResource(R.drawable.logo_wizard_light); + } - final TextView aboutTextView = (TextView) root.findViewById(R.id.cpp_about_textview); - aboutTextView.setMovementMethod(LinkMovementMethod.getInstance()); + final TextView aboutTextView = (TextView) root.findViewById(R.id.cpp_about_textview); + aboutTextView.setMovementMethod(LinkMovementMethod.getInstance()); - final TextView translatorsTextTextView = (TextView) root.findViewById(R.id.cpp_about_translators_text); - final TextView translatorsTextView = (TextView) root.findViewById(R.id.cpp_about_translators); - if(isEmpty(translatorsTextView.getText())) { - translatorsTextTextView.setVisibility(GONE); - translatorsTextView.setVisibility(GONE); - } - } + final TextView translatorsTextTextView = (TextView) root.findViewById(R.id.cpp_about_translators_text); + final TextView translatorsTextView = (TextView) root.findViewById(R.id.cpp_about_translators); + if (isEmpty(translatorsTextView.getText())) { + translatorsTextTextView.setVisibility(GONE); + translatorsTextView.setVisibility(GONE); + } + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/about/CalculatorReleaseNotesFragment.java b/android-app/src/main/java/org/solovyev/android/calculator/about/CalculatorReleaseNotesFragment.java index e6ad659f..09aacbaa 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/about/CalculatorReleaseNotesFragment.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/about/CalculatorReleaseNotesFragment.java @@ -27,6 +27,7 @@ import android.text.Html; import android.text.method.LinkMovementMethod; import android.view.View; import android.widget.TextView; + import org.solovyev.android.calculator.CalculatorFragment; import org.solovyev.android.calculator.CalculatorFragmentType; import org.solovyev.android.calculator.R; @@ -39,17 +40,17 @@ import org.solovyev.android.calculator.release.ReleaseNotes; */ 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(ReleaseNotes.getReleaseNotes(this.getActivity()))); - } + releaseNotes.setText(Html.fromHtml(ReleaseNotes.getReleaseNotes(this.getActivity()))); + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/about/TextHelper.java b/android-app/src/main/java/org/solovyev/android/calculator/about/TextHelper.java index 7569565a..3953c803 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/about/TextHelper.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/about/TextHelper.java @@ -34,28 +34,28 @@ import javax.annotation.Nullable; */ public class TextHelper { - @Nonnull - public String packageName; + @Nonnull + public String packageName; - @Nonnull - public Resources resources; + @Nonnull + public Resources resources; - public TextHelper(@Nonnull Resources resources, @Nonnull String packageName) { - this.packageName = packageName; - this.resources = resources; - } + public TextHelper(@Nonnull Resources resources, @Nonnull String packageName) { + this.packageName = packageName; + this.resources = resources; + } - @Nullable - public String getText(@Nonnull String stringName) { - final int stringId = this.resources.getIdentifier(stringName, "string", this.packageName); - try { - if (stringId == 0) { - return null; - } - return resources.getString(stringId); - } catch (Resources.NotFoundException e) { - return null; - } - } + @Nullable + public String getText(@Nonnull String stringName) { + final int stringId = this.resources.getIdentifier(stringName, "string", this.packageName); + try { + if (stringId == 0) { + return null; + } + return resources.getString(stringId); + } catch (Resources.NotFoundException e) { + return null; + } + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/drag/DirectionDragButton.java b/android-app/src/main/java/org/solovyev/android/calculator/drag/DirectionDragButton.java index afe35861..52261b1d 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/drag/DirectionDragButton.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/drag/DirectionDragButton.java @@ -30,395 +30,388 @@ import android.graphics.Paint; import android.text.TextPaint; import android.text.TextUtils; import android.util.AttributeSet; + import org.solovyev.common.math.Point2d; import org.solovyev.common.text.NumberParser; import org.solovyev.common.text.StringCollections; import org.solovyev.common.text.Strings; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.EnumMap; import java.util.HashMap; import java.util.List; import java.util.Map; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + public class DirectionDragButton extends DragButton { - @Nonnull - private final static Float DEFAULT_DIRECTION_TEXT_SCALE_FLOAT = 0.33f; - - @Nonnull - private final static Integer DEFAULT_DIRECTION_TEXT_ALPHA = 140; - - private final static int DEFAULT_DIRECTION_TEXT_COLOR = Color.WHITE; - - @Nonnull - private final static String DEFAULT_DIRECTION_TEXT_SCALE = "0.33;0.33;0.33;0.33"; - - protected static class DirectionTextData { - - @Nonnull - private final GuiDragDirection direction; - - @Nonnull - private String text; - - @Nonnull - private Point2d position; - - @Nonnull - private final TextPaint paint = new TextPaint(); - - @Nonnull - private Float scale = 0.5f; - - private boolean show = true; - - private DirectionTextData(@Nonnull GuiDragDirection direction, @Nonnull String text) { - this.direction = direction; - this.text = text; - } - - protected void init(@Nonnull Paint basePaint, - int color, - int alpha) { - paint.set(basePaint); - paint.setColor(color); - paint.setAlpha(alpha); - paint.setTextSize(basePaint.getTextSize() * scale); - } - - @Nonnull - public GuiDragDirection getDirection() { - return direction; - } - - @Nonnull - public String getText() { - return text; - } - - @Nonnull - public Point2d getPosition() { - return position; - } - - @Nonnull - public TextPaint getPaint() { - return paint; - } - - @Nonnull - public Float getScale() { - return scale; - } - - public boolean isShow() { - return show; - } - } - - public static enum GuiDragDirection { - up(DragDirection.up, 0) { - @Override - public int getAttributeId() { - return org.solovyev.android.view.R.styleable.DirectionDragButton_textUp; - } - - @Nonnull - @Override - public Point2d getTextPosition(@Nonnull Paint paint, @Nonnull Paint basePaint, @Nonnull CharSequence text, CharSequence baseText, int w, int h) { - return getUpDownTextPosition(paint, basePaint, text, baseText, 1, w, h); - } - }, - down(DragDirection.down, 2) { - @Override - public int getAttributeId() { - return org.solovyev.android.view.R.styleable.DirectionDragButton_textDown; - } - - @Nonnull - @Override - public Point2d getTextPosition(@Nonnull Paint paint, @Nonnull Paint basePaint, @Nonnull CharSequence text, CharSequence baseText, int w, int h) { - return getUpDownTextPosition(paint, basePaint, text, baseText, -1, w, h); - } - }, - left(DragDirection.left, 3) { - @Override - public int getAttributeId() { - return org.solovyev.android.view.R.styleable.DirectionDragButton_textLeft; - } - - @Nonnull - @Override - public Point2d getTextPosition(@Nonnull Paint paint, @Nonnull Paint basePaint, @Nonnull CharSequence text, CharSequence baseText, int w, int h) { - return getLeftRightTextPosition(paint, basePaint, text, baseText, w, h, true); - } - }, - - right(DragDirection.right, 1) { - @Override - public int getAttributeId() { - return org.solovyev.android.view.R.styleable.DirectionDragButton_textRight; - } - - @Nonnull - @Override - public Point2d getTextPosition(@Nonnull Paint paint, @Nonnull Paint basePaint, @Nonnull CharSequence text, CharSequence baseText, int w, int h) { - return getLeftRightTextPosition(paint, basePaint, text, baseText, w, h, false); - } - }; - - @Nonnull - private final DragDirection dragDirection; - - private final int attributePosition; - - GuiDragDirection(@Nonnull DragDirection dragDirection, int attributePosition) { - this.dragDirection = dragDirection; - this.attributePosition = attributePosition; - } - - public abstract int getAttributeId(); - - public int getAttributePosition() { - return attributePosition; - } - - @Nonnull - public abstract Point2d getTextPosition(@Nonnull Paint paint, @Nonnull Paint basePaint, @Nonnull CharSequence text, CharSequence baseText, int w, int h); - - @Nonnull - private static Point2d getLeftRightTextPosition(@Nonnull Paint paint, @Nonnull Paint basePaint, CharSequence text, @Nonnull CharSequence baseText, int w, int h, boolean left) { - final Point2d result = new Point2d(); - - if (left) { - float width = paint.measureText(" "); - result.setX(width); - } else { - float width = paint.measureText(text.toString() + " "); - result.setX(w - width); - } - - float selfHeight = paint.ascent() + paint.descent(); - - basePaint.measureText(Strings.getNotEmpty(baseText, "|")); - - result.setY(h / 2 - selfHeight / 2); - - return result; - } - - @Nonnull - private static Point2d getUpDownTextPosition(@Nonnull Paint paint, @Nonnull Paint basePaint, @Nonnull CharSequence text, CharSequence baseText, float direction, int w, int h) { - final Point2d result = new Point2d(); - - float width = paint.measureText(text.toString() + " "); - result.setX(w - width); - - float selfHeight = paint.ascent() + paint.descent(); - - basePaint.measureText(Strings.getNotEmpty(baseText, "|")); - - if (direction < 0) { - result.setY(h / 2 + h / 3 - selfHeight / 2); - } else { - result.setY(h / 2 - h / 3 - selfHeight / 2); - } - - return result; - } - - @Nullable - public static GuiDragDirection valueOf(@Nonnull DragDirection dragDirection) { - for (GuiDragDirection guiDragDirection : values()) { - if (guiDragDirection.dragDirection == dragDirection) { - return guiDragDirection; - } - } - return null; - } - } - - @Nonnull - private final Map textDataMap = new EnumMap<>(GuiDragDirection.class); - - @Nonnull - protected String directionTextScale = DEFAULT_DIRECTION_TEXT_SCALE; - - @Nonnull - protected Integer directionTextAlpha = DEFAULT_DIRECTION_TEXT_ALPHA; - - protected int directionTextColor = DEFAULT_DIRECTION_TEXT_COLOR; - - private boolean initialized = false; - - public DirectionDragButton(Context context, @Nonnull AttributeSet attrs) { - super(context, attrs); - init(context, attrs); - } - - private void init(@Nonnull Context context, @Nonnull AttributeSet attrs) { - - TypedArray a = context.obtainStyledAttributes(attrs, org.solovyev.android.view.R.styleable.DirectionDragButton); - - for (int i = 0; i < a.getIndexCount(); i++) { - int attr = a.getIndex(i); - - if (a.hasValue(attr)) { - if (attr == org.solovyev.android.view.R.styleable.DirectionDragButton_directionTextColor) { - this.directionTextColor = a.getColor(attr, DEFAULT_DIRECTION_TEXT_COLOR); - } else if (attr == org.solovyev.android.view.R.styleable.DirectionDragButton_directionTextScale) { - this.directionTextScale = a.getString(attr); - } else if (attr == org.solovyev.android.view.R.styleable.DirectionDragButton_directionTextAlpha) { - this.directionTextAlpha = a.getInt(attr, DEFAULT_DIRECTION_TEXT_ALPHA); - } else { - // try drag direction text - for (GuiDragDirection guiDragDirection : GuiDragDirection.values()) { - if (guiDragDirection.getAttributeId() == attr) { - this.textDataMap.put(guiDragDirection, new DirectionTextData(guiDragDirection, a.getString(attr))); - break; - } - } - } - } - } - - a.recycle(); - - for (Map.Entry entry : getDirectionTextScales().entrySet()) { - final DirectionTextData td = textDataMap.get(entry.getKey()); - if (td != null) { - td.scale = entry.getValue(); - } - } - - initialized = true; - } - - @Override - public void onSizeChanged(int w, int h, int oldW, int oldH) { - measureText(); - } - - @Override - protected void onTextChanged(CharSequence text, int start, int before, int after) { - measureText(); - } - - protected void measureText() { - if (initialized) { - final Paint basePaint = getPaint(); - for (DirectionTextData textData : textDataMap.values()) { - initDirectionTextPaint(basePaint, textData); - textData.position = textData.direction.getTextPosition(textData.paint, basePaint, textData.text, getText(), getWidth(), getHeight()); - } - invalidate(); - } - } - - protected void initDirectionTextPaint(@Nonnull Paint basePaint, @Nonnull DirectionTextData textData) { - textData.init(basePaint, directionTextColor, directionTextAlpha); - } - - @Override - public void onDraw(Canvas canvas) { - super.onDraw(canvas); - - final TextPaint paint = getPaint(); - for (DirectionTextData td : textDataMap.values()) { - if (td.show) { - initDirectionTextPaint(paint, td); - final String text = td.text; - final Point2d position = td.position; - canvas.drawText(text, 0, text.length(), position.getX(), position.getY(), td.paint); - } - } - } - - @SuppressWarnings("UnusedDeclaration") - @Nullable - public String getTextUp() { - return getText(GuiDragDirection.up); - } - - @SuppressWarnings("UnusedDeclaration") - @Nullable - public String getTextDown() { - return getText(GuiDragDirection.down); - } - - @Nullable - public String getText(@Nonnull DragDirection direction) { - final GuiDragDirection guiDragDirection = GuiDragDirection.valueOf(direction); - return guiDragDirection == null ? null : getText(guiDragDirection); - } - - @SuppressWarnings("UnusedDeclaration") - public void showDirectionText(boolean show, @Nonnull DragDirection direction) { - final GuiDragDirection guiDragDirection = GuiDragDirection.valueOf(direction); - final DirectionTextData td = this.textDataMap.get(guiDragDirection); - if (td != null) { - td.show = show; - } - } - - public void setText(@Nullable String text, @Nonnull GuiDragDirection direction) { - if (!TextUtils.isEmpty(text)) { - final DirectionTextData data = new DirectionTextData(direction, text); - initDirectionTextPaint(getPaint(), data); - textDataMap.put(direction, data); - } else { - textDataMap.remove(direction); - } - measureText(); - } - - @Nullable - private String getText(@Nonnull GuiDragDirection direction) { - DirectionTextData td = textDataMap.get(direction); - if (td == null) { - return null; - } else { - if (td.show) { - return td.text; - } else { - return null; - } - } - } - - - @Nonnull - public String getDirectionTextScale() { - return directionTextScale; - } - - @Nonnull - private Map getDirectionTextScales() { - final List scales = StringCollections.split(getDirectionTextScale(), ";", NumberParser.of(Float.class)); - - final Map result = new HashMap<>(); - for (GuiDragDirection direction : GuiDragDirection.values()) { - result.put(direction, DEFAULT_DIRECTION_TEXT_SCALE_FLOAT); - } - - if (scales.size() == 1) { - final Float scale = scales.get(0); - for (Map.Entry entry : result.entrySet()) { - entry.setValue(scale); - } - } else { - for (int i = 0; i < scales.size(); i++) { - for (GuiDragDirection direction : GuiDragDirection.values()) { - if (direction.getAttributePosition() == i) { - result.put(direction, scales.get(i)); - } - } - } - } - - return result; - } + @Nonnull + private final static Float DEFAULT_DIRECTION_TEXT_SCALE_FLOAT = 0.33f; + + @Nonnull + private final static Integer DEFAULT_DIRECTION_TEXT_ALPHA = 140; + + private final static int DEFAULT_DIRECTION_TEXT_COLOR = Color.WHITE; + + @Nonnull + private final static String DEFAULT_DIRECTION_TEXT_SCALE = "0.33;0.33;0.33;0.33"; + @Nonnull + private final Map textDataMap = new EnumMap<>(GuiDragDirection.class); + @Nonnull + protected String directionTextScale = DEFAULT_DIRECTION_TEXT_SCALE; + @Nonnull + protected Integer directionTextAlpha = DEFAULT_DIRECTION_TEXT_ALPHA; + protected int directionTextColor = DEFAULT_DIRECTION_TEXT_COLOR; + private boolean initialized = false; + + public DirectionDragButton(Context context, @Nonnull AttributeSet attrs) { + super(context, attrs); + init(context, attrs); + } + + private void init(@Nonnull Context context, @Nonnull AttributeSet attrs) { + + TypedArray a = context.obtainStyledAttributes(attrs, org.solovyev.android.view.R.styleable.DirectionDragButton); + + for (int i = 0; i < a.getIndexCount(); i++) { + int attr = a.getIndex(i); + + if (a.hasValue(attr)) { + if (attr == org.solovyev.android.view.R.styleable.DirectionDragButton_directionTextColor) { + this.directionTextColor = a.getColor(attr, DEFAULT_DIRECTION_TEXT_COLOR); + } else if (attr == org.solovyev.android.view.R.styleable.DirectionDragButton_directionTextScale) { + this.directionTextScale = a.getString(attr); + } else if (attr == org.solovyev.android.view.R.styleable.DirectionDragButton_directionTextAlpha) { + this.directionTextAlpha = a.getInt(attr, DEFAULT_DIRECTION_TEXT_ALPHA); + } else { + // try drag direction text + for (GuiDragDirection guiDragDirection : GuiDragDirection.values()) { + if (guiDragDirection.getAttributeId() == attr) { + this.textDataMap.put(guiDragDirection, new DirectionTextData(guiDragDirection, a.getString(attr))); + break; + } + } + } + } + } + + a.recycle(); + + for (Map.Entry entry : getDirectionTextScales().entrySet()) { + final DirectionTextData td = textDataMap.get(entry.getKey()); + if (td != null) { + td.scale = entry.getValue(); + } + } + + initialized = true; + } + + @Override + public void onSizeChanged(int w, int h, int oldW, int oldH) { + measureText(); + } + + @Override + protected void onTextChanged(CharSequence text, int start, int before, int after) { + measureText(); + } + + protected void measureText() { + if (initialized) { + final Paint basePaint = getPaint(); + for (DirectionTextData textData : textDataMap.values()) { + initDirectionTextPaint(basePaint, textData); + textData.position = textData.direction.getTextPosition(textData.paint, basePaint, textData.text, getText(), getWidth(), getHeight()); + } + invalidate(); + } + } + + protected void initDirectionTextPaint(@Nonnull Paint basePaint, @Nonnull DirectionTextData textData) { + textData.init(basePaint, directionTextColor, directionTextAlpha); + } + + @Override + public void onDraw(Canvas canvas) { + super.onDraw(canvas); + + final TextPaint paint = getPaint(); + for (DirectionTextData td : textDataMap.values()) { + if (td.show) { + initDirectionTextPaint(paint, td); + final String text = td.text; + final Point2d position = td.position; + canvas.drawText(text, 0, text.length(), position.getX(), position.getY(), td.paint); + } + } + } + + @SuppressWarnings("UnusedDeclaration") + @Nullable + public String getTextUp() { + return getText(GuiDragDirection.up); + } + + @SuppressWarnings("UnusedDeclaration") + @Nullable + public String getTextDown() { + return getText(GuiDragDirection.down); + } + + @Nullable + public String getText(@Nonnull DragDirection direction) { + final GuiDragDirection guiDragDirection = GuiDragDirection.valueOf(direction); + return guiDragDirection == null ? null : getText(guiDragDirection); + } + + @SuppressWarnings("UnusedDeclaration") + public void showDirectionText(boolean show, @Nonnull DragDirection direction) { + final GuiDragDirection guiDragDirection = GuiDragDirection.valueOf(direction); + final DirectionTextData td = this.textDataMap.get(guiDragDirection); + if (td != null) { + td.show = show; + } + } + + public void setText(@Nullable String text, @Nonnull GuiDragDirection direction) { + if (!TextUtils.isEmpty(text)) { + final DirectionTextData data = new DirectionTextData(direction, text); + initDirectionTextPaint(getPaint(), data); + textDataMap.put(direction, data); + } else { + textDataMap.remove(direction); + } + measureText(); + } + + @Nullable + private String getText(@Nonnull GuiDragDirection direction) { + DirectionTextData td = textDataMap.get(direction); + if (td == null) { + return null; + } else { + if (td.show) { + return td.text; + } else { + return null; + } + } + } + + @Nonnull + public String getDirectionTextScale() { + return directionTextScale; + } + + @Nonnull + private Map getDirectionTextScales() { + final List scales = StringCollections.split(getDirectionTextScale(), ";", NumberParser.of(Float.class)); + + final Map result = new HashMap<>(); + for (GuiDragDirection direction : GuiDragDirection.values()) { + result.put(direction, DEFAULT_DIRECTION_TEXT_SCALE_FLOAT); + } + + if (scales.size() == 1) { + final Float scale = scales.get(0); + for (Map.Entry entry : result.entrySet()) { + entry.setValue(scale); + } + } else { + for (int i = 0; i < scales.size(); i++) { + for (GuiDragDirection direction : GuiDragDirection.values()) { + if (direction.getAttributePosition() == i) { + result.put(direction, scales.get(i)); + } + } + } + } + + return result; + } + + + public static enum GuiDragDirection { + up(DragDirection.up, 0) { + @Override + public int getAttributeId() { + return org.solovyev.android.view.R.styleable.DirectionDragButton_textUp; + } + + @Nonnull + @Override + public Point2d getTextPosition(@Nonnull Paint paint, @Nonnull Paint basePaint, @Nonnull CharSequence text, CharSequence baseText, int w, int h) { + return getUpDownTextPosition(paint, basePaint, text, baseText, 1, w, h); + } + }, + down(DragDirection.down, 2) { + @Override + public int getAttributeId() { + return org.solovyev.android.view.R.styleable.DirectionDragButton_textDown; + } + + @Nonnull + @Override + public Point2d getTextPosition(@Nonnull Paint paint, @Nonnull Paint basePaint, @Nonnull CharSequence text, CharSequence baseText, int w, int h) { + return getUpDownTextPosition(paint, basePaint, text, baseText, -1, w, h); + } + }, + left(DragDirection.left, 3) { + @Override + public int getAttributeId() { + return org.solovyev.android.view.R.styleable.DirectionDragButton_textLeft; + } + + @Nonnull + @Override + public Point2d getTextPosition(@Nonnull Paint paint, @Nonnull Paint basePaint, @Nonnull CharSequence text, CharSequence baseText, int w, int h) { + return getLeftRightTextPosition(paint, basePaint, text, baseText, w, h, true); + } + }, + + right(DragDirection.right, 1) { + @Override + public int getAttributeId() { + return org.solovyev.android.view.R.styleable.DirectionDragButton_textRight; + } + + @Nonnull + @Override + public Point2d getTextPosition(@Nonnull Paint paint, @Nonnull Paint basePaint, @Nonnull CharSequence text, CharSequence baseText, int w, int h) { + return getLeftRightTextPosition(paint, basePaint, text, baseText, w, h, false); + } + }; + + @Nonnull + private final DragDirection dragDirection; + + private final int attributePosition; + + GuiDragDirection(@Nonnull DragDirection dragDirection, int attributePosition) { + this.dragDirection = dragDirection; + this.attributePosition = attributePosition; + } + + @Nonnull + private static Point2d getLeftRightTextPosition(@Nonnull Paint paint, @Nonnull Paint basePaint, CharSequence text, @Nonnull CharSequence baseText, int w, int h, boolean left) { + final Point2d result = new Point2d(); + + if (left) { + float width = paint.measureText(" "); + result.setX(width); + } else { + float width = paint.measureText(text.toString() + " "); + result.setX(w - width); + } + + float selfHeight = paint.ascent() + paint.descent(); + + basePaint.measureText(Strings.getNotEmpty(baseText, "|")); + + result.setY(h / 2 - selfHeight / 2); + + return result; + } + + @Nonnull + private static Point2d getUpDownTextPosition(@Nonnull Paint paint, @Nonnull Paint basePaint, @Nonnull CharSequence text, CharSequence baseText, float direction, int w, int h) { + final Point2d result = new Point2d(); + + float width = paint.measureText(text.toString() + " "); + result.setX(w - width); + + float selfHeight = paint.ascent() + paint.descent(); + + basePaint.measureText(Strings.getNotEmpty(baseText, "|")); + + if (direction < 0) { + result.setY(h / 2 + h / 3 - selfHeight / 2); + } else { + result.setY(h / 2 - h / 3 - selfHeight / 2); + } + + return result; + } + + @Nullable + public static GuiDragDirection valueOf(@Nonnull DragDirection dragDirection) { + for (GuiDragDirection guiDragDirection : values()) { + if (guiDragDirection.dragDirection == dragDirection) { + return guiDragDirection; + } + } + return null; + } + + public abstract int getAttributeId(); + + public int getAttributePosition() { + return attributePosition; + } + + @Nonnull + public abstract Point2d getTextPosition(@Nonnull Paint paint, @Nonnull Paint basePaint, @Nonnull CharSequence text, CharSequence baseText, int w, int h); + } + + protected static class DirectionTextData { + + @Nonnull + private final GuiDragDirection direction; + @Nonnull + private final TextPaint paint = new TextPaint(); + @Nonnull + private String text; + @Nonnull + private Point2d position; + @Nonnull + private Float scale = 0.5f; + + private boolean show = true; + + private DirectionTextData(@Nonnull GuiDragDirection direction, @Nonnull String text) { + this.direction = direction; + this.text = text; + } + + protected void init(@Nonnull Paint basePaint, + int color, + int alpha) { + paint.set(basePaint); + paint.setColor(color); + paint.setAlpha(alpha); + paint.setTextSize(basePaint.getTextSize() * scale); + } + + @Nonnull + public GuiDragDirection getDirection() { + return direction; + } + + @Nonnull + public String getText() { + return text; + } + + @Nonnull + public Point2d getPosition() { + return position; + } + + @Nonnull + public TextPaint getPaint() { + return paint; + } + + @Nonnull + public Float getScale() { + return scale; + } + + public boolean isShow() { + return show; + } + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/drag/DragButton.java b/android-app/src/main/java/org/solovyev/android/calculator/drag/DragButton.java index 1de55bb7..c99d11a5 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/drag/DragButton.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/drag/DragButton.java @@ -25,9 +25,9 @@ package org.solovyev.android.calculator.drag; import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; -import android.util.Log; import android.view.MotionEvent; import android.widget.Button; + import org.solovyev.android.view.AndroidViewUtils; import org.solovyev.common.math.Point2d; import org.solovyev.common.text.Strings; @@ -37,96 +37,96 @@ import javax.annotation.Nullable; public class DragButton extends Button { - @Nullable - private Point2d startPoint = null; + @Nullable + private Point2d startPoint = null; - @Nullable - private DragListener onDragListener; + @Nullable + private DragListener onDragListener; - private boolean showText = true; + private boolean showText = true; - @Nullable - private CharSequence textBackup; + @Nullable + private CharSequence textBackup; - public DragButton(@Nonnull Context context, @Nonnull AttributeSet attrs) { - super(context, attrs); - } + public DragButton(@Nonnull Context context, @Nonnull AttributeSet attrs) { + super(context, attrs); + } - public void setOnDragListener(@Nullable DragListener onDragListener) { - this.onDragListener = onDragListener; - } + public void setOnDragListener(@Nullable DragListener onDragListener) { + this.onDragListener = onDragListener; + } - @Override - public boolean onTouchEvent(@Nonnull MotionEvent event) { - boolean consumed = false; + @Override + public boolean onTouchEvent(@Nonnull MotionEvent event) { + boolean consumed = false; - // in order to avoid possible NPEs - final Point2d localStartPoint = startPoint; - final DragListener localOnDragListener = onDragListener; + // in order to avoid possible NPEs + final Point2d localStartPoint = startPoint; + final DragListener localOnDragListener = onDragListener; - if (localOnDragListener != null) { - // only if onDrag() listener specified + if (localOnDragListener != null) { + // only if onDrag() listener specified - switch (event.getAction()) { - case MotionEvent.ACTION_DOWN: - // start tracking: set start point - startPoint = new Point2d(event.getX(), event.getY()); - break; + switch (event.getAction()) { + case MotionEvent.ACTION_DOWN: + // start tracking: set start point + startPoint = new Point2d(event.getX(), event.getY()); + break; - case MotionEvent.ACTION_CANCEL: - case MotionEvent.ACTION_UP: - // stop tracking + case MotionEvent.ACTION_CANCEL: + case MotionEvent.ACTION_UP: + // stop tracking - startPoint = null; - if (localStartPoint != null) { - consumed = localOnDragListener.onDrag(DragButton.this, new DragEvent(localStartPoint, event)); - if (consumed && localOnDragListener.isSuppressOnClickEvent()) { - final MotionEvent newEvent = MotionEvent.obtain(event); - newEvent.setAction(MotionEvent.ACTION_CANCEL); - super.onTouchEvent(newEvent); - newEvent.recycle(); - return true; - } - } - break; - } - } + startPoint = null; + if (localStartPoint != null) { + consumed = localOnDragListener.onDrag(DragButton.this, new DragEvent(localStartPoint, event)); + if (consumed && localOnDragListener.isSuppressOnClickEvent()) { + final MotionEvent newEvent = MotionEvent.obtain(event); + newEvent.setAction(MotionEvent.ACTION_CANCEL); + super.onTouchEvent(newEvent); + newEvent.recycle(); + return true; + } + } + break; + } + } - return super.onTouchEvent(event) || consumed; - } + return super.onTouchEvent(event) || consumed; + } - @Override - public boolean dispatchTouchEvent(@Nonnull MotionEvent event) { - return super.dispatchTouchEvent(event); - } + @Override + public boolean dispatchTouchEvent(@Nonnull MotionEvent event) { + return super.dispatchTouchEvent(event); + } - @Override - protected void onDraw(Canvas canvas) { - CharSequence text = getText(); - if (!Strings.isEmpty(text)) { - super.onDraw(canvas); - } else { - if (!AndroidViewUtils.drawDrawables(canvas, this)) { - super.onDraw(canvas); - } - } - } + @Override + protected void onDraw(Canvas canvas) { + CharSequence text = getText(); + if (!Strings.isEmpty(text)) { + super.onDraw(canvas); + } else { + if (!AndroidViewUtils.drawDrawables(canvas, this)) { + super.onDraw(canvas); + } + } + } - public boolean isShowText() { - return showText; - } + public boolean isShowText() { + return showText; + } - public void setShowText(boolean showText) { - if (this.showText != showText) { - if (showText) { - setText(textBackup); - textBackup = null; - } else { - textBackup = this.getText(); - setText(null); - } - this.showText = showText; - } - } + public void setShowText(boolean showText) { + if (this.showText != showText) { + if (showText) { + setText(textBackup); + textBackup = null; + } else { + textBackup = this.getText(); + setText(null); + } + this.showText = showText; + } + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/drag/DragDirection.java b/android-app/src/main/java/org/solovyev/android/calculator/drag/DragDirection.java index 7a9d5dab..c1d45d4e 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/drag/DragDirection.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/drag/DragDirection.java @@ -24,8 +24,8 @@ package org.solovyev.android.calculator.drag; public enum DragDirection { - up, - down, - left, - right; + up, + down, + left, + right; } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/drag/DragEvent.java b/android-app/src/main/java/org/solovyev/android/calculator/drag/DragEvent.java index 33254d6b..032d6d3e 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/drag/DragEvent.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/drag/DragEvent.java @@ -23,38 +23,39 @@ package org.solovyev.android.calculator.drag; import android.view.MotionEvent; + import org.solovyev.common.math.Point2d; import javax.annotation.Nonnull; public class DragEvent { - @Nonnull - private final Point2d startPoint; + @Nonnull + private final Point2d startPoint; - @Nonnull - private final MotionEvent motionEvent; + @Nonnull + private final MotionEvent motionEvent; - public DragEvent(@Nonnull Point2d startPoint, @Nonnull MotionEvent motionEvent) { - this.startPoint = startPoint; - this.motionEvent = motionEvent; - } + public DragEvent(@Nonnull Point2d startPoint, @Nonnull MotionEvent motionEvent) { + this.startPoint = startPoint; + this.motionEvent = motionEvent; + } - /** - * @return motion event started at start point - */ - @Nonnull - public MotionEvent getMotionEvent() { - return motionEvent; - } + /** + * @return motion event started at start point + */ + @Nonnull + public MotionEvent getMotionEvent() { + return motionEvent; + } - /** - * @return start point of dragging - */ - @Nonnull - public Point2d getStartPoint() { - return startPoint; - } + /** + * @return start point of dragging + */ + @Nonnull + public Point2d getStartPoint() { + return startPoint; + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/drag/DragListener.java b/android-app/src/main/java/org/solovyev/android/calculator/drag/DragListener.java index 5a8173ac..8700397a 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/drag/DragListener.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/drag/DragListener.java @@ -22,22 +22,23 @@ package org.solovyev.android.calculator.drag; -import javax.annotation.Nonnull; import java.util.EventListener; +import javax.annotation.Nonnull; + public interface DragListener extends EventListener { - /** - * @return 'true': if drag event has taken place (i.e. onDrag() method returned true) then click action will be suppresed - */ - boolean isSuppressOnClickEvent(); + /** + * @return 'true': if drag event has taken place (i.e. onDrag() method returned true) then click action will be suppresed + */ + boolean isSuppressOnClickEvent(); - /** - * @param dragButton drag button object for which onDrag listener was set - * @param event drag event - * @return 'true' if drag event occurred, 'false' otherwise - */ - boolean onDrag(@Nonnull DragButton dragButton, @Nonnull DragEvent event); + /** + * @param dragButton drag button object for which onDrag listener was set + * @param event drag event + * @return 'true' if drag event occurred, 'false' otherwise + */ + boolean onDrag(@Nonnull DragButton dragButton, @Nonnull DragEvent event); } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/drag/DragListenerWrapper.java b/android-app/src/main/java/org/solovyev/android/calculator/drag/DragListenerWrapper.java index e9ff4ee9..4ca9dfd6 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/drag/DragListenerWrapper.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/drag/DragListenerWrapper.java @@ -31,20 +31,20 @@ import javax.annotation.Nonnull; */ public class DragListenerWrapper implements DragListener { - @Nonnull - private final DragListener dragListener; + @Nonnull + private final DragListener dragListener; - public DragListenerWrapper(@Nonnull DragListener dragListener) { - this.dragListener = dragListener; - } + public DragListenerWrapper(@Nonnull DragListener dragListener) { + this.dragListener = dragListener; + } - @Override - public boolean isSuppressOnClickEvent() { - return this.dragListener.isSuppressOnClickEvent(); - } + @Override + public boolean isSuppressOnClickEvent() { + return this.dragListener.isSuppressOnClickEvent(); + } - @Override - public boolean onDrag(@Nonnull DragButton dragButton, @Nonnull DragEvent event) { - return this.dragListener.onDrag(dragButton, event); - } + @Override + public boolean onDrag(@Nonnull DragButton dragButton, @Nonnull DragEvent event) { + return this.dragListener.onDrag(dragButton, event); + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/drag/SimpleDragListener.java b/android-app/src/main/java/org/solovyev/android/calculator/drag/SimpleDragListener.java index 8ab84f8a..5b8a4a2d 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/drag/SimpleDragListener.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/drag/SimpleDragListener.java @@ -23,9 +23,7 @@ package org.solovyev.android.calculator.drag; import android.content.Context; -import android.support.v4.view.ViewConfigurationCompat; import android.view.MotionEvent; -import android.view.ViewConfiguration; import org.solovyev.android.calculator.R; import org.solovyev.common.MutableObject; @@ -34,109 +32,109 @@ import org.solovyev.common.interval.Intervals; import org.solovyev.common.math.Maths; import org.solovyev.common.math.Point2d; +import java.util.EnumMap; + import javax.annotation.Nonnull; import javax.annotation.Nullable; -import java.util.EnumMap; - public class SimpleDragListener implements DragListener { - @Nonnull - private static final Point2d axis = new Point2d(0, 1); + @Nonnull + private static final Point2d axis = new Point2d(0, 1); - @Nonnull - private static final EnumMap> sAngleIntervals = new EnumMap<>(DragDirection.class); + @Nonnull + private static final EnumMap> sAngleIntervals = new EnumMap<>(DragDirection.class); - static { - for (DragDirection direction : DragDirection.values()) { - sAngleIntervals.put(direction, makeAngleInterval(direction, 0, 45)); - } - } + static { + for (DragDirection direction : DragDirection.values()) { + sAngleIntervals.put(direction, makeAngleInterval(direction, 0, 45)); + } + } - @Nonnull - private final DragProcessor processor; + @Nonnull + private final DragProcessor processor; - private final float minDistancePxs; + private final float minDistancePxs; - public SimpleDragListener(@Nonnull DragProcessor processor, @Nonnull Context context) { - this.processor = processor; - this.minDistancePxs = context.getResources().getDimensionPixelSize(R.dimen.cpp_min_drag_distance); - } + public SimpleDragListener(@Nonnull DragProcessor processor, @Nonnull Context context) { + this.processor = processor; + this.minDistancePxs = context.getResources().getDimensionPixelSize(R.dimen.cpp_min_drag_distance); + } - @Override - public boolean onDrag(@Nonnull DragButton dragButton, @Nonnull DragEvent event) { - boolean consumed = false; + @Nonnull + private static Interval makeAngleInterval(@Nonnull DragDirection direction, + float leftLimit, + float rightLimit) { + final Float newLeftLimit; + final Float newRightLimit; + switch (direction) { + case up: + newLeftLimit = 180f - rightLimit; + newRightLimit = 180f - leftLimit; + break; + case down: + newLeftLimit = leftLimit; + newRightLimit = rightLimit; + break; + case left: + newLeftLimit = 90f - rightLimit; + newRightLimit = 90f + rightLimit; + break; + case right: + newLeftLimit = 90f - rightLimit; + newRightLimit = 90f + rightLimit; + break; + default: + throw new AssertionError(); + } - final MotionEvent motionEvent = event.getMotionEvent(); + return Intervals.newClosedInterval(newLeftLimit, newRightLimit); + } - final Point2d start = event.getStartPoint(); - final Point2d end = new Point2d(motionEvent.getX(), motionEvent.getY()); - final float distance = Maths.getDistance(start, end); + @Override + public boolean onDrag(@Nonnull DragButton dragButton, @Nonnull DragEvent event) { + boolean consumed = false; - final MutableObject right = new MutableObject<>(); - final double angle = Math.toDegrees(Maths.getAngle(start, Maths.sum(start, axis), end, right)); + final MotionEvent motionEvent = event.getMotionEvent(); - final long duration = motionEvent.getEventTime() - motionEvent.getDownTime(); - final DragDirection direction = getDirection(distance, (float) angle, right.getObject()); - if (direction != null && duration > 40 && duration < 2500) { - consumed = processor.processDragEvent(direction, dragButton, start, motionEvent); - } + final Point2d start = event.getStartPoint(); + final Point2d end = new Point2d(motionEvent.getX(), motionEvent.getY()); + final float distance = Maths.getDistance(start, end); - return consumed; - } + final MutableObject right = new MutableObject<>(); + final double angle = Math.toDegrees(Maths.getAngle(start, Maths.sum(start, axis), end, right)); - @Nullable - private DragDirection getDirection(float distance, float angle, boolean right) { - if (distance > minDistancePxs) { - for (DragDirection direction : DragDirection.values()) { - final Interval angleInterval = sAngleIntervals.get(direction); - final boolean wrongDirection = (direction == DragDirection.left && right) || - (direction == DragDirection.right && !right); - if (!wrongDirection && angleInterval.contains(angle)) { - return direction; - } - } - } - return null; - } + final long duration = motionEvent.getEventTime() - motionEvent.getDownTime(); + final DragDirection direction = getDirection(distance, (float) angle, right.getObject()); + if (direction != null && duration > 40 && duration < 2500) { + consumed = processor.processDragEvent(direction, dragButton, start, motionEvent); + } - @Override - public boolean isSuppressOnClickEvent() { - return true; - } + return consumed; + } - public interface DragProcessor { + @Nullable + private DragDirection getDirection(float distance, float angle, boolean right) { + if (distance > minDistancePxs) { + for (DragDirection direction : DragDirection.values()) { + final Interval angleInterval = sAngleIntervals.get(direction); + final boolean wrongDirection = (direction == DragDirection.left && right) || + (direction == DragDirection.right && !right); + if (!wrongDirection && angleInterval.contains(angle)) { + return direction; + } + } + } + return null; + } - boolean processDragEvent(@Nonnull DragDirection dragDirection, @Nonnull DragButton dragButton, @Nonnull Point2d startPoint2d, @Nonnull MotionEvent motionEvent); - } + @Override + public boolean isSuppressOnClickEvent() { + return true; + } - @Nonnull - private static Interval makeAngleInterval(@Nonnull DragDirection direction, - float leftLimit, - float rightLimit) { - final Float newLeftLimit; - final Float newRightLimit; - switch (direction) { - case up: - newLeftLimit = 180f - rightLimit; - newRightLimit = 180f - leftLimit; - break; - case down: - newLeftLimit = leftLimit; - newRightLimit = rightLimit; - break; - case left: - newLeftLimit = 90f - rightLimit; - newRightLimit = 90f + rightLimit; - break; - case right: - newLeftLimit = 90f - rightLimit; - newRightLimit = 90f + rightLimit; - break; - default: - throw new AssertionError(); - } + public interface DragProcessor { - return Intervals.newClosedInterval(newLeftLimit, newRightLimit); - } + boolean processDragEvent(@Nonnull DragDirection dragDirection, @Nonnull DragButton dragButton, @Nonnull Point2d startPoint2d, @Nonnull MotionEvent motionEvent); + } } \ No newline at end of file diff --git a/android-app/src/main/java/org/solovyev/android/calculator/function/FunctionEditDialogFragment.java b/android-app/src/main/java/org/solovyev/android/calculator/function/FunctionEditDialogFragment.java index 92084214..bb82be28 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/function/FunctionEditDialogFragment.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/function/FunctionEditDialogFragment.java @@ -34,23 +34,33 @@ import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; -import jscl.math.Generic; -import jscl.math.function.Constant; -import jscl.math.function.CustomFunction; -import jscl.math.function.Function; -import jscl.math.function.IFunction; -import org.solovyev.android.calculator.*; + +import org.solovyev.android.calculator.App; +import org.solovyev.android.calculator.CalculatorDisplayViewState; +import org.solovyev.android.calculator.CalculatorEventData; +import org.solovyev.android.calculator.CalculatorEventListener; +import org.solovyev.android.calculator.CalculatorEventType; +import org.solovyev.android.calculator.CalculatorUtils; +import org.solovyev.android.calculator.Locator; +import org.solovyev.android.calculator.R; import org.solovyev.android.calculator.math.edit.CalculatorFunctionsActivity; import org.solovyev.android.calculator.math.edit.CalculatorFunctionsFragment; import org.solovyev.android.calculator.math.edit.MathEntityRemover; import org.solovyev.android.calculator.model.AFunction; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; import java.util.Set; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +import jscl.math.Generic; +import jscl.math.function.Constant; +import jscl.math.function.CustomFunction; +import jscl.math.function.Function; +import jscl.math.function.IFunction; + /** * User: serso * Date: 11/13/12 @@ -58,306 +68,300 @@ import java.util.Set; */ public class FunctionEditDialogFragment extends DialogFragment implements CalculatorEventListener { - private static final String INPUT = "input"; + private static final String INPUT = "input"; - private Input input; + private Input input; - public FunctionEditDialogFragment() { - } + public FunctionEditDialogFragment() { + } - @Nonnull - public static FunctionEditDialogFragment create(@Nonnull Input input) { - final FunctionEditDialogFragment fragment = new FunctionEditDialogFragment(); - fragment.input = input; - final Bundle args = new Bundle(); - args.putParcelable("input", input); - fragment.setArguments(args); - return fragment; - } + @Nonnull + public static FunctionEditDialogFragment create(@Nonnull Input input) { + final FunctionEditDialogFragment fragment = new FunctionEditDialogFragment(); + fragment.input = input; + final Bundle args = new Bundle(); + args.putParcelable("input", input); + fragment.setArguments(args); + return fragment; + } - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); + public static void showDialog(@Nonnull Input input, @Nonnull Context context) { + if (context instanceof ActionBarActivity) { + FunctionEditDialogFragment.showDialog(input, ((ActionBarActivity) 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); + } + } - if (input == null) { - input = getArguments().getParcelable("input"); - if (input == null) throw new AssertionError(); - } - } + public static void showDialog(@Nonnull Input input, @Nonnull FragmentManager fm) { + App.showDialog(create(input), "function-editor", fm); + } - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - final View result = inflater.inflate(R.layout.function_edit, container, false); + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); - if (savedInstanceState != null) { - final Parcelable input = savedInstanceState.getParcelable(INPUT); - if (input instanceof Input) { - this.input = (Input) input; - } - } + if (input == null) { + input = getArguments().getParcelable("input"); + if (input == null) throw new AssertionError(); + } + } - return result; - } + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + final View result = inflater.inflate(R.layout.function_edit, container, false); - @Override - public void onViewCreated(@Nonnull View root, Bundle savedInstanceState) { - super.onViewCreated(root, savedInstanceState); + if (savedInstanceState != null) { + final Parcelable input = savedInstanceState.getParcelable(INPUT); + if (input instanceof Input) { + this.input = (Input) input; + } + } - final FunctionParamsView paramsView = (FunctionParamsView) root.findViewById(R.id.function_params_layout); + return result; + } - final AFunction.Builder builder; - final AFunction function = input.getFunction(); - if (function != null) { - builder = new AFunction.Builder(function); - } else { - builder = new AFunction.Builder(); - } + @Override + public void onViewCreated(@Nonnull View root, Bundle savedInstanceState) { + super.onViewCreated(root, savedInstanceState); - final List parameterNames = input.getParameterNames(); - if (parameterNames != null) { - paramsView.init(parameterNames); - } else { - paramsView.init(); - } + final FunctionParamsView paramsView = (FunctionParamsView) root.findViewById(R.id.function_params_layout); - final EditText editName = (EditText) root.findViewById(R.id.function_edit_name); - // show soft keyboard automatically - editName.requestFocus(); - editName.setText(input.getName()); + final AFunction.Builder builder; + final AFunction function = input.getFunction(); + if (function != null) { + builder = new AFunction.Builder(function); + } else { + builder = new AFunction.Builder(); + } - final EditText editDescription = (EditText) root.findViewById(R.id.function_edit_description); - editDescription.setText(input.getDescription()); + final List parameterNames = input.getParameterNames(); + if (parameterNames != null) { + paramsView.init(parameterNames); + } else { + paramsView.init(); + } - final EditText editContent = (EditText) root.findViewById(R.id.function_edit_value); - editContent.setText(input.getContent()); + final EditText editName = (EditText) root.findViewById(R.id.function_edit_name); + // show soft keyboard automatically + editName.requestFocus(); + editName.setText(input.getName()); - root.findViewById(R.id.cancel_button).setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - dismiss(); - } - }); + final EditText editDescription = (EditText) root.findViewById(R.id.function_edit_description); + editDescription.setText(input.getDescription()); - root.findViewById(R.id.save_button).setOnClickListener(new FunctionEditorSaver(builder, function, root, Locator.getInstance().getEngine().getFunctionsRegistry(), this)); + final EditText editContent = (EditText) root.findViewById(R.id.function_edit_value); + editContent.setText(input.getContent()); - if (function == null) { - // CREATE MODE - getDialog().setTitle(R.string.function_create_function); + root.findViewById(R.id.cancel_button).setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + dismiss(); + } + }); - root.findViewById(R.id.remove_button).setVisibility(View.GONE); - } else { - // EDIT MODE - getDialog().setTitle(R.string.function_edit_function); + root.findViewById(R.id.save_button).setOnClickListener(new FunctionEditorSaver(builder, function, root, Locator.getInstance().getEngine().getFunctionsRegistry(), this)); - final Function customFunction = new CustomFunction.Builder(function).create(); - root.findViewById(R.id.remove_button).setOnClickListener(MathEntityRemover.newFunctionRemover(customFunction, null, this.getActivity(), FunctionEditDialogFragment.this)); - } - } + if (function == null) { + // CREATE MODE + getDialog().setTitle(R.string.function_create_function); - @Override - public void onSaveInstanceState(@Nonnull Bundle out) { - super.onSaveInstanceState(out); + root.findViewById(R.id.remove_button).setVisibility(View.GONE); + } else { + // EDIT MODE + getDialog().setTitle(R.string.function_edit_function); - out.putParcelable(INPUT, FunctionEditorSaver.readInput(input.getFunction(), getView())); - } + final Function customFunction = new CustomFunction.Builder(function).create(); + root.findViewById(R.id.remove_button).setOnClickListener(MathEntityRemover.newFunctionRemover(customFunction, null, this.getActivity(), FunctionEditDialogFragment.this)); + } + } - @Override - public void onResume() { - super.onResume(); + @Override + public void onSaveInstanceState(@Nonnull Bundle out) { + super.onSaveInstanceState(out); - Locator.getInstance().getCalculator().addCalculatorEventListener(this); - } + out.putParcelable(INPUT, FunctionEditorSaver.readInput(input.getFunction(), getView())); + } - @Override - public void onPause() { - Locator.getInstance().getCalculator().removeCalculatorEventListener(this); + @Override + public void onResume() { + super.onResume(); - super.onPause(); - } - - @Override - public void onCalculatorEvent(@Nonnull CalculatorEventData calculatorEventData, @Nonnull CalculatorEventType calculatorEventType, @Nullable Object data) { - switch (calculatorEventType) { - case function_removed: - case function_added: - case function_changed: - if (calculatorEventData.getSource() == FunctionEditDialogFragment.this) { - dismiss(); - } - break; - - } - } + Locator.getInstance().getCalculator().addCalculatorEventListener(this); + } /* - ********************************************************************** + ********************************************************************** * * STATIC * ********************************************************************** */ - public static void showDialog(@Nonnull Input input, @Nonnull Context context) { - if (context instanceof ActionBarActivity) { - FunctionEditDialogFragment.showDialog(input, ((ActionBarActivity) 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); - } - } + @Override + public void onPause() { + Locator.getInstance().getCalculator().removeCalculatorEventListener(this); - public static void showDialog(@Nonnull Input input, @Nonnull FragmentManager fm) { - App.showDialog(create(input), "function-editor", fm); - } + super.onPause(); + } - public static class Input implements Parcelable { + @Override + public void onCalculatorEvent(@Nonnull CalculatorEventData calculatorEventData, @Nonnull CalculatorEventType calculatorEventType, @Nullable Object data) { + switch (calculatorEventType) { + case function_removed: + case function_added: + case function_changed: + if (calculatorEventData.getSource() == FunctionEditDialogFragment.this) { + dismiss(); + } + break; - public static final Parcelable.Creator CREATOR = new Creator() { - @Override - public Input createFromParcel(@Nonnull Parcel in) { - return Input.fromParcel(in); - } + } + } - @Override - public Input[] newArray(int size) { - return new Input[size]; - } - }; + public static class Input implements Parcelable { - private static final Parcelable.Creator STRING_CREATOR = new Creator() { - @Override - public String createFromParcel(@Nonnull Parcel in) { - return in.readString(); - } + private static final Parcelable.Creator STRING_CREATOR = new Creator() { + @Override + public String createFromParcel(@Nonnull Parcel in) { + return in.readString(); + } - @Override - public String[] newArray(int size) { - return new String[size]; - } - }; + @Override + public String[] newArray(int size) { + return new String[size]; + } + }; + @Nullable + private AFunction function; + @Nullable + private String name; + @Nullable + private String content; + @Nullable + private String description; + @Nullable + private List parameterNames; + public static final Parcelable.Creator CREATOR = new Creator() { + @Override + public Input createFromParcel(@Nonnull Parcel in) { + return Input.fromParcel(in); + } - @Nonnull - private static Input fromParcel(@Nonnull Parcel in) { - final Input result = new Input(); - result.name = in.readString(); - result.content = in.readString(); - result.description = in.readString(); + @Override + public Input[] newArray(int size) { + return new Input[size]; + } + }; - final List parameterNames = new ArrayList(); - in.readTypedList(parameterNames, STRING_CREATOR); - result.parameterNames = parameterNames; + private Input() { + } - result.function = (AFunction) in.readSerializable(); + @Nonnull + private static Input fromParcel(@Nonnull Parcel in) { + final Input result = new Input(); + result.name = in.readString(); + result.content = in.readString(); + result.description = in.readString(); - return result; - } + final List parameterNames = new ArrayList(); + in.readTypedList(parameterNames, STRING_CREATOR); + result.parameterNames = parameterNames; - @Nullable - private AFunction function; + result.function = (AFunction) in.readSerializable(); - @Nullable - private String name; + return result; + } - @Nullable - private String content; + @Nonnull + public static Input newInstance() { + return new Input(); + } - @Nullable - private String description; + @Nonnull + public static Input newFromFunction(@Nonnull IFunction function) { + final Input result = new Input(); + result.function = AFunction.fromIFunction(function); + return result; + } - @Nullable - private List parameterNames; + @Nonnull + public static Input newInstance(@Nullable IFunction function, + @Nullable String name, + @Nullable String value, + @Nullable String description, + @Nonnull List parameterNames) { - private 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(parameterNames); - @Nonnull - public static Input newInstance() { - return new Input(); - } + return result; + } - @Nonnull - public static Input newFromFunction(@Nonnull IFunction function) { - final Input result = new Input(); - result.function = AFunction.fromIFunction(function); - return result; - } + @Nonnull + public static Input newFromDisplay(@Nonnull CalculatorDisplayViewState viewState) { + final Input result = new Input(); - @Nonnull - public static Input newInstance(@Nullable IFunction function, - @Nullable String name, - @Nullable String value, - @Nullable String description, - @Nonnull List parameterNames) { + result.content = viewState.getText(); + final Generic generic = viewState.getResult(); + if (generic != null) { + final Set constants = CalculatorUtils.getNotSystemConstants(generic); + final List parameterNames = new ArrayList(constants.size()); + for (Constant constant : constants) { + parameterNames.add(constant.getName()); + } + result.parameterNames = parameterNames; + } - 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(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 getParameterNames() { + return parameterNames == null ? (function == null ? null : function.getParameterNames()) : parameterNames; + } - @Nullable - public List getParameterNames() { - return parameterNames == null ? (function == null ? null : function.getParameterNames()) : parameterNames; - } + @Override + public int describeContents() { + return 0; + } - @Override - public int describeContents() { - return 0; - } - - @Override - public void writeToParcel(@Nonnull Parcel out, int flags) { - out.writeString(name); - out.writeString(content); - out.writeString(description); - out.writeList(parameterNames); - out.writeSerializable(function); - } - - @Nonnull - public static Input newFromDisplay(@Nonnull CalculatorDisplayViewState viewState) { - final Input result = new Input(); - - result.content = viewState.getText(); - final Generic generic = viewState.getResult(); - if (generic != null) { - final Set constants = CalculatorUtils.getNotSystemConstants(generic); - final List parameterNames = new ArrayList(constants.size()); - for (Constant constant : constants) { - parameterNames.add(constant.getName()); - } - result.parameterNames = parameterNames; - } - - return result; - } - } + @Override + public void writeToParcel(@Nonnull Parcel out, int flags) { + out.writeString(name); + out.writeString(content); + out.writeString(description); + out.writeList(parameterNames); + out.writeSerializable(function); + } + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/function/FunctionEditorSaver.java b/android-app/src/main/java/org/solovyev/android/calculator/function/FunctionEditorSaver.java index 1e0464cf..d2ce3e78 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/function/FunctionEditorSaver.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/function/FunctionEditorSaver.java @@ -24,12 +24,6 @@ package org.solovyev.android.calculator.function; import android.view.View; import android.widget.EditText; -import jscl.CustomFunctionCalculationException; -import jscl.math.function.Function; -import jscl.math.function.IFunction; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import org.solovyev.android.calculator.CalculatorFunctionsMathRegistry; import org.solovyev.android.calculator.CalculatorMathRegistry; @@ -43,123 +37,130 @@ import org.solovyev.common.text.Strings; import java.util.Collections; import java.util.List; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +import jscl.CustomFunctionCalculationException; +import jscl.math.function.Function; +import jscl.math.function.IFunction; + public class FunctionEditorSaver implements View.OnClickListener { - @Nonnull - private final Object source; + @Nonnull + private final Object source; - @Nonnull - private final AFunction.Builder builder; + @Nonnull + private final AFunction.Builder builder; - @Nullable - private final IFunction editedInstance; + @Nullable + private final IFunction editedInstance; - @Nonnull - private final View view; + @Nonnull + private final View view; - @Nonnull - private final CalculatorMathRegistry mathRegistry; + @Nonnull + private final CalculatorMathRegistry mathRegistry; - public FunctionEditorSaver(@Nonnull AFunction.Builder builder, - @Nullable IFunction editedInstance, - @Nonnull View view, - @Nonnull CalculatorMathRegistry registry, - @Nonnull Object source) { + public FunctionEditorSaver(@Nonnull AFunction.Builder builder, + @Nullable IFunction editedInstance, + @Nonnull View view, + @Nonnull CalculatorMathRegistry registry, + @Nonnull Object source) { - this.builder = builder; - this.editedInstance = editedInstance; - this.view = view; - this.mathRegistry = registry; - this.source = source; - } + this.builder = builder; + this.editedInstance = editedInstance; + this.view = view; + this.mathRegistry = registry; + this.source = source; + } - @Override - public void onClick(View v) { - final Integer error; + @Nonnull + public static FunctionEditDialogFragment.Input readInput(@Nullable IFunction function, @Nonnull View root) { + final EditText editName = (EditText) root.findViewById(R.id.function_edit_name); + String name = editName.getText().toString(); - final FunctionEditDialogFragment.Input input = readInput(null, view); + final EditText editValue = (EditText) root.findViewById(R.id.function_edit_value); + String content = editValue.getText().toString(); - final String name = input.getName(); - final String content = input.getContent(); - final String description = input.getDescription(); + final EditText editDescription = (EditText) root.findViewById(R.id.function_edit_description); + String description = editDescription.getText().toString(); - List parameterNames = input.getParameterNames(); - if (parameterNames == null) { - parameterNames = Collections.emptyList(); - } + final FunctionParamsView editParams = (FunctionParamsView) root.findViewById(R.id.function_params_layout); + List parameterNames = editParams.getParameterNames(); - if (VarEditorSaver.isValidName(name)) { + return FunctionEditDialogFragment.Input.newInstance(function, name, content, description, parameterNames); + } - boolean canBeSaved = false; + @Override + public void onClick(View v) { + final Integer error; - final Function entityFromRegistry = mathRegistry.get(name); - if (entityFromRegistry == null) { - canBeSaved = true; - } else if (editedInstance != null && entityFromRegistry.getId().equals(editedInstance.getId())) { - canBeSaved = true; - } + final FunctionEditDialogFragment.Input input = readInput(null, view); - if (canBeSaved) { - if (validateParameters(parameterNames)) { + final String name = input.getName(); + final String content = input.getContent(); + final String description = input.getDescription(); - 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 { - error = R.string.function_already_exists; - } - } else { - error = R.string.function_name_is_not_valid; - } + List parameterNames = input.getParameterNames(); + if (parameterNames == null) { + parameterNames = Collections.emptyList(); + } - 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) { - Locator.getInstance().getNotifier().showMessage(e); - } - } - } + if (VarEditorSaver.isValidName(name)) { - @Nonnull - public static FunctionEditDialogFragment.Input readInput(@Nullable IFunction function, @Nonnull View root) { - final EditText editName = (EditText) root.findViewById(R.id.function_edit_name); - String name = editName.getText().toString(); + boolean canBeSaved = false; - final EditText editValue = (EditText) root.findViewById(R.id.function_edit_value); - String content = editValue.getText().toString(); + final Function entityFromRegistry = mathRegistry.get(name); + if (entityFromRegistry == null) { + canBeSaved = true; + } else if (editedInstance != null && entityFromRegistry.getId().equals(editedInstance.getId())) { + canBeSaved = true; + } - final EditText editDescription = (EditText) root.findViewById(R.id.function_edit_description); - String description = editDescription.getText().toString(); + if (canBeSaved) { + if (validateParameters(parameterNames)) { - final FunctionParamsView editParams = (FunctionParamsView) root.findViewById(R.id.function_params_layout); - List parameterNames = editParams.getParameterNames(); + 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 { + error = R.string.function_already_exists; + } + } else { + error = R.string.function_name_is_not_valid; + } - return FunctionEditDialogFragment.Input.newInstance(function, name, content, description, parameterNames); - } + 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) { + Locator.getInstance().getNotifier().showMessage(e); + } + } + } - private boolean validateParameters(@Nonnull List parameterNames) { - for (String parameterName : parameterNames) { - if (!VarEditorSaver.isValidName(parameterName)) { - return false; - } - } + private boolean validateParameters(@Nonnull List parameterNames) { + for (String parameterName : parameterNames) { + if (!VarEditorSaver.isValidName(parameterName)) { + return false; + } + } - return true; - } + return true; + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/function/FunctionParamEditText.java b/android-app/src/main/java/org/solovyev/android/calculator/function/FunctionParamEditText.java index 7e27222c..067f435a 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/function/FunctionParamEditText.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/function/FunctionParamEditText.java @@ -30,27 +30,27 @@ import android.widget.EditText; public class FunctionParamEditText extends EditText { - public FunctionParamEditText(Context context) { - super(context); - } + public FunctionParamEditText(Context context) { + super(context); + } - public FunctionParamEditText(Context context, AttributeSet attrs) { - super(context, attrs); - } + public FunctionParamEditText(Context context, AttributeSet attrs) { + super(context, attrs); + } - public FunctionParamEditText(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - } + public FunctionParamEditText(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + } - // we restore state manually outside - @Override - public Parcelable onSaveInstanceState() { - super.onSaveInstanceState(); - return AbsSavedState.EMPTY_STATE; - } + // we restore state manually outside + @Override + public Parcelable onSaveInstanceState() { + super.onSaveInstanceState(); + return AbsSavedState.EMPTY_STATE; + } - @Override - public void onRestoreInstanceState(Parcelable state) { - super.onRestoreInstanceState(null); - } + @Override + public void onRestoreInstanceState(Parcelable state) { + super.onRestoreInstanceState(null); + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/function/FunctionParamsView.java b/android-app/src/main/java/org/solovyev/android/calculator/function/FunctionParamsView.java index 7d564b6c..91ae7881 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/function/FunctionParamsView.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/function/FunctionParamsView.java @@ -32,183 +32,184 @@ import android.view.ViewGroup; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; -import jscl.text.MutableInt; + import org.solovyev.android.calculator.R; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.List; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +import jscl.text.MutableInt; + public class FunctionParamsView extends LinearLayout { - @Nonnull - private final MutableInt paramsCount = new MutableInt(0); + private static final String PARAM_TAG_PREFIX = "function_param_"; + @Nonnull + private final MutableInt paramsCount = new MutableInt(0); + @Nonnull + private final List paramIds = new ArrayList(10); - @Nonnull - private final List paramIds = new ArrayList(10); + public FunctionParamsView(Context context) { + super(context); + } - private static final String PARAM_TAG_PREFIX = "function_param_"; + public FunctionParamsView(Context context, AttributeSet attrs) { + super(context, attrs); + } - public FunctionParamsView(Context context) { - super(context); - } + @TargetApi(Build.VERSION_CODES.HONEYCOMB) + public FunctionParamsView(Context context, AttributeSet attrs, int defStyle) { + super(context, attrs, defStyle); + } - public FunctionParamsView(Context context, AttributeSet attrs) { - super(context, attrs); - } + public void init() { + init(Collections.emptyList()); + } - @TargetApi(Build.VERSION_CODES.HONEYCOMB) - public FunctionParamsView(Context context, AttributeSet attrs, int defStyle) { - super(context, attrs, defStyle); - } + public void init(@Nonnull List parameters) { + this.setOrientation(VERTICAL); - public void init() { - init(Collections.emptyList()); - } + final LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); - public void init(@Nonnull List parameters) { - this.setOrientation(VERTICAL); + final View addParamView = inflater.inflate(R.layout.function_add_param, null); - final LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); + final View addParamButton = addParamView.findViewById(R.id.function_add_param_button); - final View addParamView = inflater.inflate(R.layout.function_add_param, null); + addParamButton.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + addParam(null); + } + }); - final View addParamButton = addParamView.findViewById(R.id.function_add_param_button); + this.addView(addParamView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); - addParamButton.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - addParam(null); - } - }); + for (String parameter : parameters) { + addParam(parameter); + } + } - this.addView(addParamView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); + public void addParam(@Nullable String name) { + synchronized (paramsCount) { + final LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); - for (String parameter : parameters) { - addParam(parameter); - } - } + final Integer id = paramsCount.intValue(); - public void addParam(@Nullable String name) { - synchronized (paramsCount) { - final LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); + final View editParamView = inflater.inflate(R.layout.function_edit_param, null); - final Integer id = paramsCount.intValue(); + editParamView.setTag(getParamTag(id)); - final View editParamView = inflater.inflate(R.layout.function_edit_param, null); + final EditText paramNameEditText = (EditText) editParamView.findViewById(R.id.function_param_edit_text); + paramNameEditText.setText(name); - editParamView.setTag(getParamTag(id)); + final View removeParamButton = editParamView.findViewById(R.id.function_remove_param_button); + removeParamButton.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + removeParam(id); + } + }); - final EditText paramNameEditText = (EditText) editParamView.findViewById(R.id.function_param_edit_text); - paramNameEditText.setText(name); + final View upParamButton = editParamView.findViewById(R.id.function_up_param_button); + upParamButton.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + upParam(id); + } + }); - final View removeParamButton = editParamView.findViewById(R.id.function_remove_param_button); - removeParamButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - removeParam(id); - } - }); + final View downParamButton = editParamView.findViewById(R.id.function_down_param_button); + downParamButton.setOnClickListener(new OnClickListener() { + @Override + public void onClick(View v) { + downParam(id); + } + }); - final View upParamButton = editParamView.findViewById(R.id.function_up_param_button); - upParamButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - upParam(id); - } - }); + this.addView(editParamView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); - final View downParamButton = editParamView.findViewById(R.id.function_down_param_button); - downParamButton.setOnClickListener(new OnClickListener() { - @Override - public void onClick(View v) { - downParam(id); - } - }); + paramIds.add(id); + paramsCount.increment(); + } + } - this.addView(editParamView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); + private void downParam(@Nonnull Integer id) { + synchronized (paramsCount) { + int index = paramIds.indexOf(id); + if (index < paramIds.size() - 1) { + swap(index, index + 1); + } + } + } - paramIds.add(id); - paramsCount.increment(); - } - } + private void upParam(@Nonnull Integer id) { + synchronized (paramsCount) { + int index = paramIds.indexOf(id); + if (index > 0) { + swap(index, index - 1); + } + } + } - private void downParam(@Nonnull Integer id) { - synchronized (paramsCount) { - int index = paramIds.indexOf(id); - if (index < paramIds.size() - 1) { - swap(index, index + 1); - } - } - } + private void swap(int index1, int index2) { + final View editParamView1 = getParamView(paramIds.get(index1)); + final View editParamView2 = getParamView(paramIds.get(index2)); - private void upParam(@Nonnull Integer id) { - synchronized (paramsCount) { - int index = paramIds.indexOf(id); - if (index > 0) { - swap(index, index - 1); - } - } - } + if (editParamView1 != null && editParamView2 != null) { + final EditText paramNameEditText1 = (EditText) editParamView1.findViewById(R.id.function_param_edit_text); + final EditText paramNameEditText2 = (EditText) editParamView2.findViewById(R.id.function_param_edit_text); + swap(paramNameEditText1, paramNameEditText2); + } + } - private void swap(int index1, int index2) { - final View editParamView1 = getParamView(paramIds.get(index1)); - final View editParamView2 = getParamView(paramIds.get(index2)); + private void swap(@Nonnull TextView first, + @Nonnull TextView second) { + final CharSequence tmp = first.getText(); + first.setText(second.getText()); + second.setText(tmp); + } - if (editParamView1 != null && editParamView2 != null) { - final EditText paramNameEditText1 = (EditText) editParamView1.findViewById(R.id.function_param_edit_text); - final EditText paramNameEditText2 = (EditText) editParamView2.findViewById(R.id.function_param_edit_text); - swap(paramNameEditText1, paramNameEditText2); - } - } + @Nullable + private View getParamView(@Nonnull Integer id) { + final String tag = getParamTag(id); + return this.findViewWithTag(tag); + } - private void swap(@Nonnull TextView first, - @Nonnull TextView second) { - final CharSequence tmp = first.getText(); - first.setText(second.getText()); - second.setText(tmp); - } + @Nonnull + private String getParamTag(@Nonnull Integer index) { + return PARAM_TAG_PREFIX + index; + } - @Nullable - private View getParamView(@Nonnull Integer id) { - final String tag = getParamTag(id); - return this.findViewWithTag(tag); - } + public void removeParam(@Nonnull Integer id) { + synchronized (paramsCount) { + if (paramIds.contains(id)) { + final View editParamView = getParamView(id); + if (editParamView != null) { + this.removeView(editParamView); + paramIds.remove(id); + } + } + } + } - @Nonnull - private String getParamTag(@Nonnull Integer index) { - return PARAM_TAG_PREFIX + index; - } + @Nonnull + public List getParameterNames() { + synchronized (paramsCount) { + final List result = new ArrayList(paramsCount.intValue()); - public void removeParam(@Nonnull Integer id) { - synchronized (paramsCount) { - if (paramIds.contains(id)) { - final View editParamView = getParamView(id); - if (editParamView != null) { - this.removeView(editParamView); - paramIds.remove(id); - } - } - } - } + for (Integer id : paramIds) { + final View paramView = getParamView(id); + if (paramView != null) { + final EditText paramNameEditText = (EditText) paramView.findViewById(R.id.function_param_edit_text); + result.add(paramNameEditText.getText().toString()); + } + } - @Nonnull - public List getParameterNames() { - synchronized (paramsCount) { - final List result = new ArrayList(paramsCount.intValue()); - - for (Integer id : paramIds) { - final View paramView = getParamView(id); - if (paramView != null) { - final EditText paramNameEditText = (EditText) paramView.findViewById(R.id.function_param_edit_text); - result.add(paramNameEditText.getText().toString()); - } - } - - return result; - } - } + return result; + } + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/ga/Ga.java b/android-app/src/main/java/org/solovyev/android/calculator/ga/Ga.java index 54f45fbc..33dd36f3 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/ga/Ga.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/ga/Ga.java @@ -4,105 +4,108 @@ import android.content.Context; import android.content.SharedPreferences; import android.text.TextUtils; import android.util.Log; + import com.google.android.gms.analytics.GoogleAnalytics; import com.google.android.gms.analytics.HitBuilders; import com.google.android.gms.analytics.Tracker; + import org.solovyev.android.calculator.Preferences; import org.solovyev.android.calculator.R; import org.solovyev.common.listeners.JEvent; import org.solovyev.common.listeners.JEventListener; import org.solovyev.common.listeners.JEventListeners; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.io.ByteArrayOutputStream; import java.io.PrintStream; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + public final class Ga implements SharedPreferences.OnSharedPreferenceChangeListener { - private static final int LAYOUT = 1; - private static final int THEME = 2; + private static final int LAYOUT = 1; + private static final int THEME = 2; - @Nonnull - private final GoogleAnalytics analytics; + @Nonnull + private final GoogleAnalytics analytics; - @Nonnull - private final Tracker tracker; + @Nonnull + private final Tracker tracker; - public Ga(@Nonnull Context context, @Nonnull SharedPreferences preferences, @Nonnull JEventListeners, JEvent> bus) { - analytics = GoogleAnalytics.getInstance(context); - tracker = analytics.newTracker(R.xml.ga); - preferences.registerOnSharedPreferenceChangeListener(this); - } + public Ga(@Nonnull Context context, @Nonnull SharedPreferences preferences, @Nonnull JEventListeners, JEvent> bus) { + analytics = GoogleAnalytics.getInstance(context); + tracker = analytics.newTracker(R.xml.ga); + preferences.registerOnSharedPreferenceChangeListener(this); + } - @Nonnull - private String getStackTrace(@Nonnull Exception e) { - try { - final ByteArrayOutputStream out = new ByteArrayOutputStream(); - e.printStackTrace(new PrintStream(out)); - return new String(out.toByteArray()); - } catch (Exception e1) { - Log.e("Ga", e1.getMessage(), e1); - } - return ""; - } + @Nonnull + private String getStackTrace(@Nonnull Exception e) { + try { + final ByteArrayOutputStream out = new ByteArrayOutputStream(); + e.printStackTrace(new PrintStream(out)); + return new String(out.toByteArray()); + } catch (Exception e1) { + Log.e("Ga", e1.getMessage(), e1); + } + return ""; + } - private void reportLayout(@Nonnull Preferences.Gui.Layout layout) { - tracker.send(new HitBuilders.EventBuilder().setCustomDimension(LAYOUT, layout.name()).build()); - } + private void reportLayout(@Nonnull Preferences.Gui.Layout layout) { + tracker.send(new HitBuilders.EventBuilder().setCustomDimension(LAYOUT, layout.name()).build()); + } - private void reportTheme(@Nonnull Preferences.Gui.Theme theme) { - tracker.send(new HitBuilders.EventBuilder().setCustomDimension(THEME, theme.name()).build()); - } + private void reportTheme(@Nonnull Preferences.Gui.Theme theme) { + tracker.send(new HitBuilders.EventBuilder().setCustomDimension(THEME, theme.name()).build()); + } - @Nonnull - public GoogleAnalytics getAnalytics() { - return analytics; - } + @Nonnull + public GoogleAnalytics getAnalytics() { + return analytics; + } - @Nonnull - public Tracker getTracker() { - return tracker; - } + @Nonnull + public Tracker getTracker() { + return tracker; + } - public void onButtonPressed(@Nullable String text) { - if (TextUtils.isEmpty(text)) { - return; - } + public void onButtonPressed(@Nullable String text) { + if (TextUtils.isEmpty(text)) { + return; + } - final HitBuilders.EventBuilder b = new HitBuilders.EventBuilder(); - b.setCategory("ui"); - b.setAction("click"); - b.setLabel(text); - tracker.send(b.build()); - } + final HitBuilders.EventBuilder b = new HitBuilders.EventBuilder(); + b.setCategory("ui"); + b.setAction("click"); + b.setLabel(text); + tracker.send(b.build()); + } - @Override - public void onSharedPreferenceChanged(SharedPreferences preferences, String key) { - if (TextUtils.equals(key, Preferences.Gui.layout.getKey())) { - reportLayout(Preferences.Gui.layout.getPreferenceNoError(preferences)); - } else if (TextUtils.equals(key, Preferences.Gui.theme.getKey())) { - reportTheme(Preferences.Gui.theme.getPreferenceNoError(preferences)); - } - } + @Override + public void onSharedPreferenceChanged(SharedPreferences preferences, String key) { + if (TextUtils.equals(key, Preferences.Gui.layout.getKey())) { + reportLayout(Preferences.Gui.layout.getPreferenceNoError(preferences)); + } else if (TextUtils.equals(key, Preferences.Gui.theme.getKey())) { + reportTheme(Preferences.Gui.theme.getPreferenceNoError(preferences)); + } + } - public void reportInitially(@Nonnull SharedPreferences preferences) { - reportLayout(Preferences.Gui.layout.getPreferenceNoError(preferences)); - reportTheme(Preferences.Gui.theme.getPreferenceNoError(preferences)); - } + public void reportInitially(@Nonnull SharedPreferences preferences) { + reportLayout(Preferences.Gui.layout.getPreferenceNoError(preferences)); + reportTheme(Preferences.Gui.theme.getPreferenceNoError(preferences)); + } - public void onBootStart() { - final HitBuilders.EventBuilder b = new HitBuilders.EventBuilder(); - b.setCategory("lifecycle"); - b.setAction("boot"); - tracker.send(b.build()); - } + public void onBootStart() { + final HitBuilders.EventBuilder b = new HitBuilders.EventBuilder(); + b.setCategory("lifecycle"); + b.setAction("boot"); + tracker.send(b.build()); + } - public void onFloatingCalculatorOpened() { - final HitBuilders.EventBuilder b = new HitBuilders.EventBuilder(); - b.setCategory("lifecycle"); - b.setAction("floating_calculator"); - b.setLabel("start"); - tracker.send(b.build()); - } + public void onFloatingCalculatorOpened() { + final HitBuilders.EventBuilder b = new HitBuilders.EventBuilder(); + b.setCategory("lifecycle"); + b.setAction("floating_calculator"); + b.setLabel("start"); + tracker.send(b.build()); + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/history/AndroidCalculatorHistory.java b/android-app/src/main/java/org/solovyev/android/calculator/history/AndroidCalculatorHistory.java index e9df8a6b..a4e3fdf1 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/history/AndroidCalculatorHistory.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/history/AndroidCalculatorHistory.java @@ -26,14 +26,16 @@ import android.app.Application; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; + import org.solovyev.android.calculator.Calculator; import org.solovyev.android.calculator.CalculatorEventData; import org.solovyev.android.calculator.CalculatorEventType; import org.solovyev.common.history.HistoryAction; +import java.util.List; + import javax.annotation.Nonnull; import javax.annotation.Nullable; -import java.util.List; /** * User: serso @@ -42,132 +44,132 @@ import java.util.List; */ public class AndroidCalculatorHistory implements CalculatorHistory { - @Nonnull - private final CalculatorHistoryImpl calculatorHistory; + @Nonnull + private final CalculatorHistoryImpl calculatorHistory; - @Nonnull - private final Context context; + @Nonnull + private final Context context; - public AndroidCalculatorHistory(@Nonnull Application application, @Nonnull Calculator calculator) { - this.context = application; - calculatorHistory = new CalculatorHistoryImpl(calculator); - } + public AndroidCalculatorHistory(@Nonnull Application application, @Nonnull Calculator calculator) { + this.context = application; + calculatorHistory = new CalculatorHistoryImpl(calculator); + } - @Override - public void load() { - final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); - if (preferences != null) { - final String value = preferences.getString("org.solovyev.android.calculator.CalculatorModel_history", null); - if (value != null) { - calculatorHistory.fromXml(value); - } - } - } + @Override + public void load() { + final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); + if (preferences != null) { + final String value = preferences.getString("org.solovyev.android.calculator.CalculatorModel_history", null); + if (value != null) { + calculatorHistory.fromXml(value); + } + } + } - public void save() { - final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context); - final SharedPreferences.Editor editor = settings.edit(); + public void save() { + final SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context); + final SharedPreferences.Editor editor = settings.edit(); - editor.putString("org.solovyev.android.calculator.CalculatorModel_history", calculatorHistory.toXml()); + editor.putString("org.solovyev.android.calculator.CalculatorModel_history", calculatorHistory.toXml()); - editor.apply(); - } + editor.apply(); + } - public void clearSavedHistory() { - calculatorHistory.clearSavedHistory(); - save(); - } + public void clearSavedHistory() { + calculatorHistory.clearSavedHistory(); + save(); + } - public void removeSavedHistory(@Nonnull CalculatorHistoryState historyState) { - historyState.setSaved(false); - calculatorHistory.removeSavedHistory(historyState); - save(); - } + public void removeSavedHistory(@Nonnull 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(@Nonnull HistoryAction historyAction) { - return calculatorHistory.isActionAvailable(historyAction); - } + @Override + public boolean isActionAvailable(@Nonnull HistoryAction historyAction) { + return calculatorHistory.isActionAvailable(historyAction); + } - @Override - public CalculatorHistoryState doAction(@Nonnull HistoryAction historyAction, @Nullable CalculatorHistoryState currentState) { - return calculatorHistory.doAction(historyAction, currentState); - } + @Override + public CalculatorHistoryState doAction(@Nonnull 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); + } - @Nonnull - @Override - public List getStates() { - return calculatorHistory.getStates(); - } + @Nonnull + @Override + public List getStates() { + return calculatorHistory.getStates(); + } - @Nonnull - @Override - public List getStates(boolean includeIntermediateStates) { - return calculatorHistory.getStates(includeIntermediateStates); - } + @Nonnull + @Override + public List getStates(boolean includeIntermediateStates) { + return calculatorHistory.getStates(includeIntermediateStates); + } - @Override - public void clear() { - calculatorHistory.clear(); - } + @Override + public void clear() { + calculatorHistory.clear(); + } - @Nonnull - public List getSavedHistory() { - return calculatorHistory.getSavedHistory(); - } + @Nonnull + public List getSavedHistory() { + return calculatorHistory.getSavedHistory(); + } - @Nonnull - public CalculatorHistoryState addSavedState(@Nonnull CalculatorHistoryState historyState) { - return calculatorHistory.addSavedState(historyState); - } + @Nonnull + public CalculatorHistoryState addSavedState(@Nonnull CalculatorHistoryState historyState) { + return calculatorHistory.addSavedState(historyState); + } - @Override - public void fromXml(@Nonnull String xml) { - calculatorHistory.fromXml(xml); - } + @Override + public void fromXml(@Nonnull String xml) { + calculatorHistory.fromXml(xml); + } - @Override - public String toXml() { - return calculatorHistory.toXml(); - } + @Override + public String toXml() { + return calculatorHistory.toXml(); + } - @Override - public void onCalculatorEvent(@Nonnull CalculatorEventData calculatorEventData, @Nonnull CalculatorEventType calculatorEventType, @Nullable Object data) { - calculatorHistory.onCalculatorEvent(calculatorEventData, calculatorEventType, data); - } + @Override + public void onCalculatorEvent(@Nonnull CalculatorEventData calculatorEventData, @Nonnull CalculatorEventType calculatorEventType, @Nullable Object data) { + calculatorHistory.onCalculatorEvent(calculatorEventData, calculatorEventType, data); + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/history/BaseHistoryFragment.java b/android-app/src/main/java/org/solovyev/android/calculator/history/BaseHistoryFragment.java index 6e1fb990..a208a5c0 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/history/BaseHistoryFragment.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/history/BaseHistoryFragment.java @@ -81,30 +81,29 @@ import static org.solovyev.android.calculator.CalculatorEventType.clear_history_ public abstract class BaseHistoryFragment extends ListFragment implements CalculatorEventListener { /* - ********************************************************************** + ********************************************************************** * * CONSTANTS * ********************************************************************** */ - @Nonnull - private static final String TAG = "CalculatorHistoryFragment"; - - public static final Comparator COMPARATOR = new Comparator() { - @Override - public int compare(CalculatorHistoryState state1, CalculatorHistoryState state2) { - if (state1.isSaved() == state2.isSaved()) { - long l = state2.getTime() - state1.getTime(); - return l > 0l ? 1 : (l < 0l ? -1 : 0); - } else if (state1.isSaved()) { - return -1; - } else if (state2.isSaved()) { - return 1; - } - return 0; - } - }; + public static final Comparator COMPARATOR = new Comparator() { + @Override + public int compare(CalculatorHistoryState state1, CalculatorHistoryState state2) { + if (state1.isSaved() == state2.isSaved()) { + long l = state2.getTime() - state1.getTime(); + return l > 0l ? 1 : (l < 0l ? -1 : 0); + } else if (state1.isSaved()) { + return -1; + } else if (state2.isSaved()) { + return 1; + } + return 0; + } + }; + @Nonnull + private static final String TAG = "CalculatorHistoryFragment"; /* ********************************************************************** @@ -113,282 +112,276 @@ public abstract class BaseHistoryFragment extends ListFragment implements Calcul * ********************************************************************** */ + private final ActivityMenu menu = ListActivityMenu.fromResource(R.menu.history_menu, HistoryMenu.class, AndroidMenuHelper.getInstance(), new HistoryMenuFilter()); + @Nonnull + private final SharedPreferences.OnSharedPreferenceChangeListener preferencesListener = new HistoryOnPreferenceChangeListener(); + @Nonnull + private final DialogInterface.OnClickListener clearDialogListener = new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + switch (which) { + case DialogInterface.BUTTON_POSITIVE: + clearHistory(); + break; + } + } + }; + @Nonnull + private HistoryArrayAdapter adapter; + @Nonnull + private FragmentUi ui; + @Nullable + private AlertDialog clearDialog; + protected BaseHistoryFragment(@Nonnull CalculatorFragmentType fragmentType) { + ui = CalculatorApplication.getInstance().createFragmentHelper(fragmentType.getDefaultLayoutId(), fragmentType.getDefaultTitleResId(), false); + } - @Nonnull - private HistoryArrayAdapter adapter; + public static boolean isAlreadySaved(@Nonnull CalculatorHistoryState historyState) { + if (historyState.isSaved()) throw new AssertionError(); - @Nonnull - private FragmentUi ui; + boolean result = false; + try { + historyState.setSaved(true); + if (Collections.contains(historyState, Locator.getInstance().getHistory().getSavedHistory(), new Equalizer() { + @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()); + } + })) { + result = true; + } + } finally { + historyState.setSaved(false); + } + return result; + } - private final ActivityMenu menu = ListActivityMenu.fromResource(R.menu.history_menu, HistoryMenu.class, AndroidMenuHelper.getInstance(), new HistoryMenuFilter()); + public static void useHistoryItem(@Nonnull final CalculatorHistoryState historyState) { + App.getVibrator().vibrate(); + Locator.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.use_history_state, historyState); + } - @Nonnull - private final SharedPreferences.OnSharedPreferenceChangeListener preferencesListener = new HistoryOnPreferenceChangeListener(); + @Nonnull + public static String getHistoryText(@Nonnull CalculatorHistoryState state) { + final StringBuilder result = new StringBuilder(); + result.append(state.getEditorState().getText()); + result.append(getIdentitySign(state.getDisplayState().getJsclOperation())); + final String expressionResult = state.getDisplayState().getEditorState().getText(); + if (expressionResult != null) { + result.append(expressionResult); + } + return result.toString(); + } - @Nonnull - private final DialogInterface.OnClickListener clearDialogListener = new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - switch (which) { - case DialogInterface.BUTTON_POSITIVE: - clearHistory(); - break; - } - } - }; - @Nullable - private AlertDialog clearDialog; + @Nonnull + private static String getIdentitySign(@Nonnull JsclOperation jsclOperation) { + return jsclOperation == JsclOperation.simplify ? "≡" : "="; + } - protected BaseHistoryFragment(@Nonnull CalculatorFragmentType fragmentType) { - ui = 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); + ui.onCreate(this); - ui.onCreate(this); + setHasOptionsMenu(true); - setHasOptionsMenu(true); + logDebug("onCreate"); + } - logDebug("onCreate"); - } + private int logDebug(@Nonnull String msg) { + return Log.d(TAG + ": " + getTag(), msg); + } - private int logDebug(@Nonnull String msg) { - return Log.d(TAG + ": " + getTag(), msg); - } + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + return ui.onCreateView(this, inflater, container); + } - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - return ui.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); + final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); + final Boolean showDatetime = Preferences.History.showDatetime.getPreference(preferences); - final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); - final Boolean showDatetime = Preferences.History.showDatetime.getPreference(preferences); + ui.onViewCreated(this, root); - ui.onViewCreated(this, root); + adapter = new HistoryArrayAdapter(this.getActivity(), getItemLayoutId(), org.solovyev.android.calculator.R.id.history_item, new ArrayList(), showDatetime); + setListAdapter(adapter); - adapter = new HistoryArrayAdapter(this.getActivity(), getItemLayoutId(), org.solovyev.android.calculator.R.id.history_item, new ArrayList(), showDatetime); - setListAdapter(adapter); + final ListView lv = getListView(); + lv.setTextFilterEnabled(true); - final ListView lv = getListView(); - lv.setTextFilterEnabled(true); + final FloatingActionButton fab = (FloatingActionButton) root.findViewById(R.id.fab); + fab.attachToListView(lv); + fab.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + Locator.getInstance().getCalculator().fireCalculatorEvent(clear_history_requested, null); + } + }); - final FloatingActionButton fab = (FloatingActionButton) root.findViewById(R.id.fab); - fab.attachToListView(lv); - fab.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - Locator.getInstance().getCalculator().fireCalculatorEvent(clear_history_requested, null); - } - }); + 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 menuItems = Collections.asList(HistoryItemMenuItem.values()); - final List 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 menuBuilder = ContextMenuBuilder.newInstance(activity, "history-menu", ListContextMenu.newInstance(menuItems)); + menuBuilder.build(data).show(); - final ContextMenuBuilder 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.ui.onResume(this); - this.ui.onResume(this); + updateAdapter(); + PreferenceManager.getDefaultSharedPreferences(getActivity()).registerOnSharedPreferenceChangeListener(preferencesListener); + } - updateAdapter(); - PreferenceManager.getDefaultSharedPreferences(getActivity()).registerOnSharedPreferenceChangeListener(preferencesListener); - } + @Override + public void onPause() { + PreferenceManager.getDefaultSharedPreferences(getActivity()).unregisterOnSharedPreferenceChangeListener(preferencesListener); - @Override - public void onPause() { - PreferenceManager.getDefaultSharedPreferences(getActivity()).unregisterOnSharedPreferenceChangeListener(preferencesListener); + this.ui.onPause(this); - this.ui.onPause(this); + super.onPause(); + } - super.onPause(); - } + @Override + public void onDestroyView() { + ui.onDestroyView(this); + super.onDestroyView(); + } - @Override - public void onDestroyView() { - ui.onDestroyView(this); - super.onDestroyView(); - } + @Override + public void onDestroy() { + logDebug("onDestroy"); + if (clearDialog != null) { + clearDialog.dismiss(); + clearDialog = null; + } + ui.onDestroy(this); - @Override - public void onDestroy() { - logDebug("onDestroy"); - if (clearDialog != null) { - clearDialog.dismiss(); - clearDialog = null; - } - ui.onDestroy(this); + super.onDestroy(); + } - super.onDestroy(); - } + protected abstract int getItemLayoutId(); - protected abstract int getItemLayoutId(); + private void updateAdapter() { + final List historyList = getHistoryList(); - private void updateAdapter() { - final List historyList = getHistoryList(); + final ArrayAdapter adapter = getAdapter(); + try { + adapter.setNotifyOnChange(false); + adapter.clear(); + for (CalculatorHistoryState historyState : historyList) { + adapter.add(historyState); + } + } finally { + adapter.setNotifyOnChange(true); + } - final ArrayAdapter adapter = getAdapter(); - try { - adapter.setNotifyOnChange(false); - adapter.clear(); - for (CalculatorHistoryState historyState : historyList) { - adapter.add(historyState); - } - } finally { - adapter.setNotifyOnChange(true); - } + adapter.notifyDataSetChanged(); + } - adapter.notifyDataSetChanged(); - } + @Nonnull + private List getHistoryList() { + final List calculatorHistoryStates = getHistoryItems(); - public static boolean isAlreadySaved(@Nonnull CalculatorHistoryState historyState) { - if (historyState.isSaved()) throw new AssertionError(); + java.util.Collections.sort(calculatorHistoryStates, COMPARATOR); - boolean result = false; - try { - historyState.setSaved(true); - if (Collections.contains(historyState, Locator.getInstance().getHistory().getSavedHistory(), new Equalizer() { - @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()); - } - })) { - result = true; - } - } finally { - historyState.setSaved(false); - } - return result; - } + final FilterRulesChain filterRulesChain = new FilterRulesChain<>(); + filterRulesChain.addFilterRule(new JPredicate() { + @Override + public boolean apply(CalculatorHistoryState object) { + return object == null || Strings.isEmpty(object.getEditorState().getText()); + } + }); - public static void useHistoryItem(@Nonnull final CalculatorHistoryState historyState) { - App.getVibrator().vibrate(); - Locator.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.use_history_state, historyState); - } + new Filter<>(filterRulesChain).filter(calculatorHistoryStates.iterator()); - @Nonnull - private List getHistoryList() { - final List calculatorHistoryStates = getHistoryItems(); + return calculatorHistoryStates; + } - java.util.Collections.sort(calculatorHistoryStates, COMPARATOR); + @Nonnull + protected abstract List getHistoryItems(); - final FilterRulesChain filterRulesChain = new FilterRulesChain<>(); - filterRulesChain.addFilterRule(new JPredicate() { - @Override - public boolean apply(CalculatorHistoryState object) { - return object == null || Strings.isEmpty(object.getEditorState().getText()); - } - }); + protected abstract void clearHistory(); - new Filter<>(filterRulesChain).filter(calculatorHistoryStates.iterator()); + @Nonnull + protected HistoryArrayAdapter getAdapter() { + return adapter; + } - return calculatorHistoryStates; - } + @Override + public void onCalculatorEvent(@Nonnull CalculatorEventData calculatorEventData, @Nonnull 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() { + clearDialog = new AlertDialog.Builder(getActivity()).setTitle(R.string.cpp_clear_history_title) + .setMessage(R.string.cpp_clear_history_message) + .setPositiveButton(R.string.cpp_clear_history, clearDialogListener) + .setNegativeButton(R.string.c_cancel, clearDialogListener) + .create(); + clearDialog.show(); + } + }); + break; + } - @Nonnull - protected abstract List getHistoryItems(); - - @Nonnull - public static String getHistoryText(@Nonnull CalculatorHistoryState state) { - final StringBuilder result = new StringBuilder(); - result.append(state.getEditorState().getText()); - result.append(getIdentitySign(state.getDisplayState().getJsclOperation())); - final String expressionResult = state.getDisplayState().getEditorState().getText(); - if (expressionResult != null) { - result.append(expressionResult); - } - return result.toString(); - } - - @Nonnull - private static String getIdentitySign(@Nonnull JsclOperation jsclOperation) { - return jsclOperation == JsclOperation.simplify ? "≡" : "="; - } - - protected abstract void clearHistory(); - - @Nonnull - protected HistoryArrayAdapter getAdapter() { - return adapter; - } - - @Override - public void onCalculatorEvent(@Nonnull CalculatorEventData calculatorEventData, @Nonnull 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() { - clearDialog = new AlertDialog.Builder(getActivity()).setTitle(R.string.cpp_clear_history_title) - .setMessage(R.string.cpp_clear_history_message) - .setPositiveButton(R.string.cpp_clear_history, clearDialogListener) - .setNegativeButton(R.string.c_cancel, clearDialogListener) - .create(); - clearDialog.show(); - } - }); - break; - } - - } + } /* ********************************************************************** @@ -398,69 +391,69 @@ public abstract class BaseHistoryFragment extends ListFragment implements Calcul ********************************************************************** */ - @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 { + private static enum HistoryMenu implements IdentifiableMenuItem { - toggle_datetime(R.id.menu_history_toggle_datetime) { - @Override - public void onClick(@Nonnull MenuItem data, @Nonnull Context context) { - final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(CalculatorApplication.getInstance()); - final Boolean showDatetime = Preferences.History.showDatetime.getPreference(preferences); - Preferences.History.showDatetime.putPreference(preferences, !showDatetime); - } - }, + toggle_datetime(R.id.menu_history_toggle_datetime) { + @Override + public void onClick(@Nonnull MenuItem data, @Nonnull Context context) { + final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(CalculatorApplication.getInstance()); + final Boolean showDatetime = Preferences.History.showDatetime.getPreference(preferences); + Preferences.History.showDatetime.putPreference(preferences, !showDatetime); + } + }, - fullscreen(R.id.menu_history_fullscreen) { - @Override - public void onClick(@Nonnull MenuItem data, @Nonnull Context context) { - context.startActivity(new Intent(context, CalculatorHistoryActivity.class)); - } - }; + fullscreen(R.id.menu_history_fullscreen) { + @Override + public void onClick(@Nonnull MenuItem data, @Nonnull Context context) { + context.startActivity(new Intent(context, CalculatorHistoryActivity.class)); + } + }; - private final int itemId; + private final int itemId; - HistoryMenu(int itemId) { - this.itemId = itemId; - } + HistoryMenu(int itemId) { + this.itemId = itemId; + } - @Nonnull - @Override - public Integer getItemId() { - return this.itemId; - } - } + @Nonnull + @Override + public Integer getItemId() { + return this.itemId; + } + } - private class HistoryMenuFilter implements JPredicate> { + private class HistoryMenuFilter implements JPredicate> { - @Override - public boolean apply(@Nullable AMenuItem menuItem) { - boolean result = false; + @Override + public boolean apply(@Nullable AMenuItem menuItem) { + boolean result = false; - if (menuItem instanceof IdentifiableMenuItem) { - switch (((IdentifiableMenuItem) menuItem).getItemId()) { - case R.id.menu_history_fullscreen: - result = !ui.isPane(BaseHistoryFragment.this); - break; - } - } + if (menuItem instanceof IdentifiableMenuItem) { + switch (((IdentifiableMenuItem) menuItem).getItemId()) { + case R.id.menu_history_fullscreen: + result = !ui.isPane(BaseHistoryFragment.this); + break; + } + } - return result; - } - } + return result; + } + } /* ********************************************************************** @@ -470,13 +463,13 @@ public abstract class BaseHistoryFragment extends ListFragment implements Calcul ********************************************************************** */ - private final class HistoryOnPreferenceChangeListener implements SharedPreferences.OnSharedPreferenceChangeListener { + private final class HistoryOnPreferenceChangeListener implements SharedPreferences.OnSharedPreferenceChangeListener { - @Override - public void onSharedPreferenceChanged(SharedPreferences preferences, String key) { - if (Preferences.History.showDatetime.isSameKey(key)) { - getAdapter().setShowDatetime(Preferences.History.showDatetime.getPreference(preferences)); - } - } - } + @Override + public void onSharedPreferenceChanged(SharedPreferences preferences, String key) { + if (Preferences.History.showDatetime.isSameKey(key)) { + getAdapter().setShowDatetime(Preferences.History.showDatetime.getPreference(preferences)); + } + } + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/history/CalculatorHistoryActivity.java b/android-app/src/main/java/org/solovyev/android/calculator/history/CalculatorHistoryActivity.java index 491a475c..eac25d72 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/history/CalculatorHistoryActivity.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/history/CalculatorHistoryActivity.java @@ -23,7 +23,12 @@ package org.solovyev.android.calculator.history; import android.os.Bundle; -import org.solovyev.android.calculator.*; + +import org.solovyev.android.calculator.BaseActivity; +import org.solovyev.android.calculator.CalculatorEventData; +import org.solovyev.android.calculator.CalculatorEventListener; +import org.solovyev.android.calculator.CalculatorEventType; +import org.solovyev.android.calculator.R; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -33,22 +38,22 @@ import static org.solovyev.android.calculator.CalculatorFragmentType.saved_histo public class CalculatorHistoryActivity extends BaseActivity implements CalculatorEventListener { - public CalculatorHistoryActivity() { - super(R.layout.main_empty, CalculatorHistoryActivity.class.getSimpleName()); - } + public CalculatorHistoryActivity() { + super(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); - ui.addTab(this, history, null, R.id.main_layout); - ui.addTab(this, saved_history, null, R.id.main_layout); - } + ui.addTab(this, history, null, R.id.main_layout); + ui.addTab(this, saved_history, null, R.id.main_layout); + } - @Override - public void onCalculatorEvent(@Nonnull CalculatorEventData calculatorEventData, @Nonnull CalculatorEventType calculatorEventType, @Nullable Object data) { - if (calculatorEventType == CalculatorEventType.use_history_state) { - this.finish(); - } - } + @Override + public void onCalculatorEvent(@Nonnull CalculatorEventData calculatorEventData, @Nonnull CalculatorEventType calculatorEventType, @Nullable Object data) { + if (calculatorEventType == CalculatorEventType.use_history_state) { + this.finish(); + } + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/history/HistoryArrayAdapter.java b/android-app/src/main/java/org/solovyev/android/calculator/history/HistoryArrayAdapter.java index a1e49237..284a4b95 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/history/HistoryArrayAdapter.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/history/HistoryArrayAdapter.java @@ -29,13 +29,16 @@ import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; + import org.solovyev.android.calculator.R; import org.solovyev.common.text.Strings; -import javax.annotation.Nonnull; import java.util.List; -import static android.view.View.*; +import javax.annotation.Nonnull; + +import static android.view.View.GONE; +import static android.view.View.VISIBLE; import static org.solovyev.android.calculator.CalculatorFragmentType.saved_history; import static org.solovyev.android.calculator.history.BaseHistoryFragment.isAlreadySaved; @@ -46,79 +49,79 @@ import static org.solovyev.android.calculator.history.BaseHistoryFragment.isAlre */ public class HistoryArrayAdapter extends ArrayAdapter { - private static final int DATETIME_FORMAT = DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_MONTH | DateUtils.FORMAT_ABBREV_TIME; - private boolean showDatetime; + private static final int DATETIME_FORMAT = DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_MONTH | DateUtils.FORMAT_ABBREV_TIME; + private boolean showDatetime; - HistoryArrayAdapter(Context context, int resource, int textViewResourceId, @Nonnull List historyList, boolean showDatetime) { - super(context, resource, textViewResourceId, historyList); - this.showDatetime = showDatetime; - } + HistoryArrayAdapter(Context context, int resource, int textViewResourceId, @Nonnull List historyList, boolean showDatetime) { + super(context, resource, textViewResourceId, historyList); + this.showDatetime = showDatetime; + } - @Override - public View getView(int position, View convertView, ViewGroup parent) { - final ViewGroup result = (ViewGroup) super.getView(position, convertView, parent); + @Override + public View getView(int position, View convertView, ViewGroup parent) { + final ViewGroup result = (ViewGroup) super.getView(position, convertView, parent); - final CalculatorHistoryState state = getItem(position); + final CalculatorHistoryState state = getItem(position); - final TextView time = (TextView) result.findViewById(R.id.history_time); - if (showDatetime) { - time.setVisibility(VISIBLE); - time.setText(DateUtils.formatDateTime(getContext(), state.getTime(), DATETIME_FORMAT)); - } else { - time.setVisibility(GONE); - time.setText(null); - } + final TextView time = (TextView) result.findViewById(R.id.history_time); + if (showDatetime) { + time.setVisibility(VISIBLE); + time.setText(DateUtils.formatDateTime(getContext(), state.getTime(), DATETIME_FORMAT)); + } else { + time.setVisibility(GONE); + time.setText(null); + } - final TextView editor = (TextView) result.findViewById(R.id.history_item); - editor.setText(BaseHistoryFragment.getHistoryText(state)); + final TextView editor = (TextView) result.findViewById(R.id.history_item); + editor.setText(BaseHistoryFragment.getHistoryText(state)); - final TextView commentView = (TextView) result.findViewById(R.id.history_item_comment); - if (commentView != null) { - final String comment = state.getComment(); - if (!Strings.isEmpty(comment)) { - commentView.setText(comment); - commentView.setVisibility(VISIBLE); - } else { - commentView.setText(null); - commentView.setVisibility(GONE); - } - } + final TextView commentView = (TextView) result.findViewById(R.id.history_item_comment); + if (commentView != null) { + final String comment = state.getComment(); + if (!Strings.isEmpty(comment)) { + commentView.setText(comment); + commentView.setVisibility(VISIBLE); + } else { + commentView.setText(null); + commentView.setVisibility(GONE); + } + } - final ImageView status = (ImageView) result.findViewById(R.id.history_item_status_icon); - if (status != null) { - if (state.isSaved() || isAlreadySaved(state)) { - status.setVisibility(VISIBLE); - status.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - final Context context = getContext(); - if (context instanceof CalculatorHistoryActivity) { - final CalculatorHistoryActivity activity = (CalculatorHistoryActivity) context; - activity.getUi().selectTab(activity, saved_history); - } - } - }); - } else { - status.setVisibility(GONE); - status.setOnClickListener(null); - } - } + final ImageView status = (ImageView) result.findViewById(R.id.history_item_status_icon); + if (status != null) { + if (state.isSaved() || isAlreadySaved(state)) { + status.setVisibility(VISIBLE); + status.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + final Context context = getContext(); + if (context instanceof CalculatorHistoryActivity) { + final CalculatorHistoryActivity activity = (CalculatorHistoryActivity) context; + activity.getUi().selectTab(activity, saved_history); + } + } + }); + } else { + status.setVisibility(GONE); + status.setOnClickListener(null); + } + } - return result; - } + return result; + } - @Override - public void notifyDataSetChanged() { - this.setNotifyOnChange(false); - this.sort(BaseHistoryFragment.COMPARATOR); - this.setNotifyOnChange(true); - super.notifyDataSetChanged(); - } + @Override + public void notifyDataSetChanged() { + this.setNotifyOnChange(false); + this.sort(BaseHistoryFragment.COMPARATOR); + this.setNotifyOnChange(true); + super.notifyDataSetChanged(); + } - public void setShowDatetime(boolean showDatetime) { - if (this.showDatetime != showDatetime) { - this.showDatetime = showDatetime; - notifyDataSetChanged(); - } - } + public void setShowDatetime(boolean showDatetime) { + if (this.showDatetime != showDatetime) { + this.showDatetime = showDatetime; + notifyDataSetChanged(); + } + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/history/HistoryDragProcessor.java b/android-app/src/main/java/org/solovyev/android/calculator/history/HistoryDragProcessor.java index 267a32b1..de3abb4f 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/history/HistoryDragProcessor.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/history/HistoryDragProcessor.java @@ -42,34 +42,34 @@ import javax.annotation.Nonnull; */ public class HistoryDragProcessor implements SimpleDragListener.DragProcessor { - @Nonnull - private final HistoryControl historyControl; + @Nonnull + private final HistoryControl historyControl; - public HistoryDragProcessor(@Nonnull HistoryControl historyControl) { - this.historyControl = historyControl; - } + public HistoryDragProcessor(@Nonnull HistoryControl historyControl) { + this.historyControl = historyControl; + } - @Override - public boolean processDragEvent(@Nonnull DragDirection dragDirection, @Nonnull DragButton dragButton, @Nonnull Point2d startPoint2d, @Nonnull MotionEvent motionEvent) { - boolean result = false; + @Override + public boolean processDragEvent(@Nonnull DragDirection dragDirection, @Nonnull DragButton dragButton, @Nonnull Point2d startPoint2d, @Nonnull MotionEvent motionEvent) { + boolean result = false; - Log.d(String.valueOf(dragButton.getId()), "History on drag event start: " + dragDirection); + Log.d(String.valueOf(dragButton.getId()), "History on drag event start: " + dragDirection); - final HistoryAction historyAction; - if (dragDirection == DragDirection.up) { - historyAction = HistoryAction.undo; - } else if (dragDirection == DragDirection.down) { - historyAction = HistoryAction.redo; - } else { - historyAction = null; - } + final HistoryAction historyAction; + if (dragDirection == DragDirection.up) { + historyAction = HistoryAction.undo; + } else if (dragDirection == DragDirection.down) { + historyAction = HistoryAction.redo; + } else { + historyAction = null; + } - if (historyAction != null) { - App.getVibrator().vibrate(); - result = true; - historyControl.doHistoryAction(historyAction); - } + if (historyAction != null) { + App.getVibrator().vibrate(); + result = true; + historyControl.doHistoryAction(historyAction); + } - return result; - } + return result; + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/history/HistoryFragment.java b/android-app/src/main/java/org/solovyev/android/calculator/history/HistoryFragment.java index 485ebd09..b5b55496 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/history/HistoryFragment.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/history/HistoryFragment.java @@ -26,38 +26,38 @@ import android.content.SharedPreferences; import android.preference.PreferenceManager; import org.solovyev.android.calculator.CalculatorFragmentType; -import org.solovyev.android.calculator.Preferences; import org.solovyev.android.calculator.Locator; +import org.solovyev.android.calculator.Preferences; import org.solovyev.android.calculator.R; -import javax.annotation.Nonnull; - import java.util.ArrayList; import java.util.List; +import javax.annotation.Nonnull; + public class HistoryFragment extends BaseHistoryFragment { - public HistoryFragment() { - super(CalculatorFragmentType.history); - } + public HistoryFragment() { + super(CalculatorFragmentType.history); + } - @Override - protected int getItemLayoutId() { - return R.layout.history_item; - } + @Override + protected int getItemLayoutId() { + return R.layout.history_item; + } - @Nonnull - @Override - protected List getHistoryItems() { - final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); - final boolean showIntermediateCalculations = Preferences.History.showIntermediateCalculations.getPreference(preferences); - final List historyStates = Locator.getInstance().getHistory().getStates(showIntermediateCalculations); - return new ArrayList(historyStates); - } + @Nonnull + @Override + protected List getHistoryItems() { + final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); + final boolean showIntermediateCalculations = Preferences.History.showIntermediateCalculations.getPreference(preferences); + final List historyStates = Locator.getInstance().getHistory().getStates(showIntermediateCalculations); + return new ArrayList(historyStates); + } - @Override - protected void clearHistory() { - Locator.getInstance().getHistory().clear(); - getAdapter().clear(); - } + @Override + protected void clearHistory() { + Locator.getInstance().getHistory().clear(); + getAdapter().clear(); + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/history/HistoryItemMenuData.java b/android-app/src/main/java/org/solovyev/android/calculator/history/HistoryItemMenuData.java index a17d9972..2bda1acc 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/history/HistoryItemMenuData.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/history/HistoryItemMenuData.java @@ -33,24 +33,24 @@ import javax.annotation.Nonnull; */ public class HistoryItemMenuData { - @Nonnull - private final ArrayAdapter adapter; + @Nonnull + private final ArrayAdapter adapter; - @Nonnull - private final CalculatorHistoryState historyState; + @Nonnull + private final CalculatorHistoryState historyState; - public HistoryItemMenuData(@Nonnull CalculatorHistoryState historyState, ArrayAdapter adapter) { - this.historyState = historyState; - this.adapter = adapter; - } + public HistoryItemMenuData(@Nonnull CalculatorHistoryState historyState, ArrayAdapter adapter) { + this.historyState = historyState; + this.adapter = adapter; + } - @Nonnull - public CalculatorHistoryState getHistoryState() { - return historyState; - } + @Nonnull + public CalculatorHistoryState getHistoryState() { + return historyState; + } - @Nonnull - public ArrayAdapter getAdapter() { - return adapter; - } + @Nonnull + public ArrayAdapter getAdapter() { + return adapter; + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/history/HistoryItemMenuItem.java b/android-app/src/main/java/org/solovyev/android/calculator/history/HistoryItemMenuItem.java index b3817255..f098b8cc 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/history/HistoryItemMenuItem.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/history/HistoryItemMenuItem.java @@ -33,13 +33,13 @@ import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; -import javax.annotation.Nonnull; - import org.solovyev.android.calculator.Locator; import org.solovyev.android.calculator.R; import org.solovyev.android.menu.LabeledMenuItem; import org.solovyev.common.text.Strings; +import javax.annotation.Nonnull; + /** * User: serso * Date: 12/18/11 @@ -47,122 +47,122 @@ import org.solovyev.common.text.Strings; */ public enum HistoryItemMenuItem implements LabeledMenuItem { - use(R.string.c_use) { - @Override - public void onClick(@Nonnull HistoryItemMenuData data, @Nonnull Context context) { - BaseHistoryFragment.useHistoryItem(data.getHistoryState()); - } - }, + use(R.string.c_use) { + @Override + public void onClick(@Nonnull HistoryItemMenuData data, @Nonnull Context context) { + BaseHistoryFragment.useHistoryItem(data.getHistoryState()); + } + }, - copy_expression(R.string.c_copy_expression) { - @Override - public void onClick(@Nonnull HistoryItemMenuData data, @Nonnull Context context) { - final CalculatorHistoryState calculatorHistoryState = data.getHistoryState(); - final String text = calculatorHistoryState.getEditorState().getText(); - if (!Strings.isEmpty(text)) { - final ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Activity.CLIPBOARD_SERVICE); - clipboard.setText(text); - Toast.makeText(context, context.getText(R.string.c_expression_copied), Toast.LENGTH_SHORT).show(); - } - } - }, + copy_expression(R.string.c_copy_expression) { + @Override + public void onClick(@Nonnull HistoryItemMenuData data, @Nonnull Context context) { + final CalculatorHistoryState calculatorHistoryState = data.getHistoryState(); + final String text = calculatorHistoryState.getEditorState().getText(); + if (!Strings.isEmpty(text)) { + final ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Activity.CLIPBOARD_SERVICE); + clipboard.setText(text); + Toast.makeText(context, context.getText(R.string.c_expression_copied), Toast.LENGTH_SHORT).show(); + } + } + }, - copy_result(R.string.c_copy_result) { - @Override - public void onClick(@Nonnull HistoryItemMenuData data, @Nonnull Context context) { - final CalculatorHistoryState calculatorHistoryState = data.getHistoryState(); - final String text = calculatorHistoryState.getDisplayState().getEditorState().getText(); - if (!Strings.isEmpty(text)) { - final ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Activity.CLIPBOARD_SERVICE); - clipboard.setText(text); - Toast.makeText(context, context.getText(R.string.c_result_copied), Toast.LENGTH_SHORT).show(); - } - } - }, + copy_result(R.string.c_copy_result) { + @Override + public void onClick(@Nonnull HistoryItemMenuData data, @Nonnull Context context) { + final CalculatorHistoryState calculatorHistoryState = data.getHistoryState(); + final String text = calculatorHistoryState.getDisplayState().getEditorState().getText(); + if (!Strings.isEmpty(text)) { + final ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Activity.CLIPBOARD_SERVICE); + clipboard.setText(text); + Toast.makeText(context, context.getText(R.string.c_result_copied), Toast.LENGTH_SHORT).show(); + } + } + }, - save(R.string.c_save) { - @Override - public void onClick(@Nonnull final HistoryItemMenuData data, @Nonnull final Context context) { - final CalculatorHistoryState historyState = data.getHistoryState(); - if (!historyState.isSaved()) { - createEditHistoryDialog(data, context, true); - } else { - Toast.makeText(context, context.getText(R.string.c_history_already_saved), Toast.LENGTH_LONG).show(); - } - } - }, + save(R.string.c_save) { + @Override + public void onClick(@Nonnull final HistoryItemMenuData data, @Nonnull final Context context) { + final CalculatorHistoryState historyState = data.getHistoryState(); + if (!historyState.isSaved()) { + createEditHistoryDialog(data, context, true); + } else { + Toast.makeText(context, context.getText(R.string.c_history_already_saved), Toast.LENGTH_LONG).show(); + } + } + }, - edit(R.string.c_edit) { - @Override - public void onClick(@Nonnull final HistoryItemMenuData data, @Nonnull final Context context) { - final CalculatorHistoryState historyState = data.getHistoryState(); - if (historyState.isSaved()) { - createEditHistoryDialog(data, context, false); - } else { - Toast.makeText(context, context.getText(R.string.c_history_must_be_saved), Toast.LENGTH_LONG).show(); - } - } - }, + edit(R.string.c_edit) { + @Override + public void onClick(@Nonnull final HistoryItemMenuData data, @Nonnull final Context context) { + final CalculatorHistoryState historyState = data.getHistoryState(); + if (historyState.isSaved()) { + createEditHistoryDialog(data, context, false); + } else { + Toast.makeText(context, context.getText(R.string.c_history_must_be_saved), Toast.LENGTH_LONG).show(); + } + } + }, - remove(R.string.c_remove) { - @Override - public void onClick(@Nonnull HistoryItemMenuData data, @Nonnull Context context) { - final CalculatorHistoryState historyState = data.getHistoryState(); - if (historyState.isSaved()) { - data.getAdapter().remove(historyState); - Locator.getInstance().getHistory().removeSavedHistory(historyState); - Toast.makeText(context, context.getText(R.string.c_history_was_removed), Toast.LENGTH_LONG).show(); - data.getAdapter().notifyDataSetChanged(); - } - } - }; + remove(R.string.c_remove) { + @Override + public void onClick(@Nonnull HistoryItemMenuData data, @Nonnull Context context) { + final CalculatorHistoryState historyState = data.getHistoryState(); + if (historyState.isSaved()) { + data.getAdapter().remove(historyState); + Locator.getInstance().getHistory().removeSavedHistory(historyState); + Toast.makeText(context, context.getText(R.string.c_history_was_removed), Toast.LENGTH_LONG).show(); + data.getAdapter().notifyDataSetChanged(); + } + } + }; - private static void createEditHistoryDialog(@Nonnull final HistoryItemMenuData data, @Nonnull final Context context, final boolean save) { - final CalculatorHistoryState historyState = data.getHistoryState(); + private final int captionId; - final LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); - final View editView = layoutInflater.inflate(R.layout.history_edit, null); - final TextView historyExpression = (TextView) editView.findViewById(R.id.history_edit_expression); - historyExpression.setText(BaseHistoryFragment.getHistoryText(historyState)); + private HistoryItemMenuItem(int captionId) { + this.captionId = captionId; + } - final EditText comment = (EditText) editView.findViewById(R.id.history_edit_comment); - comment.setText(historyState.getComment()); + private static void createEditHistoryDialog(@Nonnull final HistoryItemMenuData data, @Nonnull final Context context, final boolean save) { + final CalculatorHistoryState historyState = data.getHistoryState(); - final AlertDialog.Builder builder = new AlertDialog.Builder(context) - .setTitle(save ? R.string.c_save_history : R.string.c_edit_history) - .setCancelable(true) - .setNegativeButton(R.string.c_cancel, null) - .setPositiveButton(R.string.c_save, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - if (save) { - final CalculatorHistoryState savedHistoryItem = Locator.getInstance().getHistory().addSavedState(historyState); - savedHistoryItem.setComment(comment.getText().toString()); - 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(); - } - data.getAdapter().notifyDataSetChanged(); - Toast.makeText(context, context.getText(R.string.c_history_saved), Toast.LENGTH_LONG).show(); - } - }) - .setView(editView); + final LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + final View editView = layoutInflater.inflate(R.layout.history_edit, null); + final TextView historyExpression = (TextView) editView.findViewById(R.id.history_edit_expression); + historyExpression.setText(BaseHistoryFragment.getHistoryText(historyState)); - builder.create().show(); - } + final EditText comment = (EditText) editView.findViewById(R.id.history_edit_comment); + comment.setText(historyState.getComment()); - private final int captionId; + final AlertDialog.Builder builder = new AlertDialog.Builder(context) + .setTitle(save ? R.string.c_save_history : R.string.c_edit_history) + .setCancelable(true) + .setNegativeButton(R.string.c_cancel, null) + .setPositiveButton(R.string.c_save, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + if (save) { + final CalculatorHistoryState savedHistoryItem = Locator.getInstance().getHistory().addSavedState(historyState); + savedHistoryItem.setComment(comment.getText().toString()); + 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(); + } + data.getAdapter().notifyDataSetChanged(); + Toast.makeText(context, context.getText(R.string.c_history_saved), Toast.LENGTH_LONG).show(); + } + }) + .setView(editView); - private HistoryItemMenuItem(int captionId) { - this.captionId = captionId; - } + builder.create().show(); + } - @Nonnull - @Override - public String getCaption(@Nonnull Context context) { - return context.getString(captionId); - } + @Nonnull + @Override + public String getCaption(@Nonnull Context context) { + return context.getString(captionId); + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/history/SavedHistoryFragment.java b/android-app/src/main/java/org/solovyev/android/calculator/history/SavedHistoryFragment.java index 852cfb1c..73a1b7a4 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/history/SavedHistoryFragment.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/history/SavedHistoryFragment.java @@ -26,30 +26,31 @@ import org.solovyev.android.calculator.CalculatorFragmentType; import org.solovyev.android.calculator.Locator; import org.solovyev.android.calculator.R; -import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; +import javax.annotation.Nonnull; + public class SavedHistoryFragment extends BaseHistoryFragment { - public SavedHistoryFragment() { - super(CalculatorFragmentType.saved_history); - } + public SavedHistoryFragment() { + super(CalculatorFragmentType.saved_history); + } - @Override - protected int getItemLayoutId() { - return R.layout.saved_history_item; - } + @Override + protected int getItemLayoutId() { + return R.layout.saved_history_item; + } - @Nonnull - @Override - protected List getHistoryItems() { - return new ArrayList(Locator.getInstance().getHistory().getSavedHistory()); - } + @Nonnull + @Override + protected List getHistoryItems() { + return new ArrayList(Locator.getInstance().getHistory().getSavedHistory()); + } - @Override - protected void clearHistory() { - Locator.getInstance().getHistory().clearSavedHistory(); - getAdapter().clear(); - } + @Override + protected void clearHistory() { + Locator.getInstance().getHistory().clearSavedHistory(); + getAdapter().clear(); + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/history/TextViewEditorAdapter.java b/android-app/src/main/java/org/solovyev/android/calculator/history/TextViewEditorAdapter.java index 7317aee7..4e812694 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/history/TextViewEditorAdapter.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/history/TextViewEditorAdapter.java @@ -25,11 +25,11 @@ package org.solovyev.android.calculator.history; import android.widget.EditText; import android.widget.TextView; +import org.solovyev.android.calculator.Editor; + import javax.annotation.Nonnull; import javax.annotation.Nullable; -import org.solovyev.android.calculator.Editor; - /** * User: serso * Date: 12/17/11 @@ -37,32 +37,32 @@ import org.solovyev.android.calculator.Editor; */ public class TextViewEditorAdapter implements Editor { - @Nonnull - private final TextView textView; + @Nonnull + private final TextView textView; - public TextViewEditorAdapter(@Nonnull TextView textView) { - this.textView = textView; - } + public TextViewEditorAdapter(@Nonnull TextView textView) { + this.textView = textView; + } - @Override - public CharSequence getText() { - return textView.getText().toString(); - } + @Override + public CharSequence getText() { + return textView.getText().toString(); + } - @Override - public void setText(@Nullable CharSequence text) { - textView.setText(text); - } + @Override + public void setText(@Nullable CharSequence text) { + textView.setText(text); + } - @Override - public int getSelection() { - return textView.getSelectionStart(); - } + @Override + public int getSelection() { + return textView.getSelectionStart(); + } - @Override - public void setSelection(int selection) { - if (textView instanceof EditText) { - ((EditText) textView).setSelection(selection); - } - } + @Override + public void setSelection(int selection) { + if (textView instanceof EditText) { + ((EditText) textView).setSelection(selection); + } + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/language/Language.java b/android-app/src/main/java/org/solovyev/android/calculator/language/Language.java index 2431d459..dab1dfb9 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/language/Language.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/language/Language.java @@ -10,60 +10,60 @@ import java.util.Locale; import javax.annotation.Nonnull; public final class Language { - @Nonnull - public final String code; + @Nonnull + public final String code; - @Nonnull - public final Locale locale; + @Nonnull + public final Locale locale; - @Nonnull - final String name; + @Nonnull + final String name; - public Language(@Nonnull String code, @Nonnull Locale locale) { - this.code = code; - this.locale = locale; - this.name = makeName(code, locale); - } + public Language(@Nonnull String code, @Nonnull Locale locale) { + this.code = code; + this.locale = locale; + this.name = makeName(code, locale); + } - @Nonnull - public String getName(@Nonnull Context context) { - if (!isSystem()) { - return name; - } else { - return context.getString(R.string.cpp_system_language) + " (" + locale.getDisplayLanguage(locale) + ")"; - } - } + @Nonnull + private static String makeName(@Nonnull String code, @Nonnull Locale locale) { + if (code.equals(Languages.SYSTEM_LANGUAGE_CODE)) { + return ""; + } - @Nonnull - private static String makeName(@Nonnull String code, @Nonnull Locale locale) { - if (code.equals(Languages.SYSTEM_LANGUAGE_CODE)) { - return ""; - } + final int underscore = code.indexOf("_"); + if (underscore >= 0 && TextUtils.isEmpty(locale.getDisplayCountry(locale))) { + return locale.getDisplayName(locale) + " (" + code.substring(underscore + 1) + ")"; + } - final int underscore = code.indexOf("_"); - if (underscore >= 0 && TextUtils.isEmpty(locale.getDisplayCountry(locale))) { - return locale.getDisplayName(locale) + " (" + code.substring(underscore + 1) + ")"; - } + return locale.getDisplayName(locale); + } - return locale.getDisplayName(locale); - } + @Nonnull + public String getName(@Nonnull Context context) { + if (!isSystem()) { + return name; + } else { + return context.getString(R.string.cpp_system_language) + " (" + locale.getDisplayLanguage(locale) + ")"; + } + } - public boolean isSystem() { - return code.equals(Languages.SYSTEM_LANGUAGE_CODE); - } + public boolean isSystem() { + return code.equals(Languages.SYSTEM_LANGUAGE_CODE); + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; - final Language language = (Language) o; - return code.equals(language.code); + final Language language = (Language) o; + return code.equals(language.code); - } + } - @Override - public int hashCode() { - return code.hashCode(); - } + @Override + public int hashCode() { + return code.hashCode(); + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/language/Languages.java b/android-app/src/main/java/org/solovyev/android/calculator/language/Languages.java index 9761e498..a0042c96 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/language/Languages.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/language/Languages.java @@ -23,147 +23,147 @@ import javax.annotation.Nullable; public final class Languages implements SharedPreferences.OnSharedPreferenceChangeListener { - @Nonnull - private static final Locale[] locales = Locale.getAvailableLocales(); - @Nonnull - public static final String SYSTEM_LANGUAGE_CODE = "00"; - @Nonnull - public static final Language SYSTEM_LANGUAGE = new Language(SYSTEM_LANGUAGE_CODE, Locale.getDefault()); - @Nonnull - private final List list = new ArrayList<>(); + @Nonnull + public static final String SYSTEM_LANGUAGE_CODE = "00"; + @Nonnull + public static final Language SYSTEM_LANGUAGE = new Language(SYSTEM_LANGUAGE_CODE, Locale.getDefault()); + @Nonnull + private static final Locale[] locales = Locale.getAvailableLocales(); + @Nonnull + private final List list = new ArrayList<>(); - public void init(@Nonnull SharedPreferences preferences) { - preferences.registerOnSharedPreferenceChangeListener(this); - } + @Nullable + private static Language makeLanguage(@Nonnull String localeId) { + final Locale locale = findLocaleById(localeId); + if (locale == null) { + return null; + } + return new Language(localeId, locale); + } - @Nonnull - public List getList() { - Check.isMainThread(); - if (list.isEmpty()) { - loadList(); - } - return list; - } + @Nullable + private static Locale findLocaleById(@Nonnull String id) { + for (Locale locale : locales) { + if (TextUtils.equals(locale.toString(), id)) { + return locale; + } + } - private void loadList() { - Check.isMainThread(); - Check.isEmpty(list); - tryAddLanguage("ar"); - tryAddLanguage("cs"); - tryAddLanguage("en"); - tryAddLanguage("es_ES"); - tryAddLanguage("de"); - tryAddLanguage("fi"); - tryAddLanguage("fr"); - tryAddLanguage("it"); - tryAddLanguage("it"); - tryAddLanguage("pl"); - tryAddLanguage("pt_BR"); - tryAddLanguage("pt_PT"); - tryAddLanguage("ru"); - tryAddLanguage("tr"); - tryAddLanguage("vi"); - tryAddLanguage("uk"); - tryAddLanguage("ja"); - tryAddLanguage("zh_CN"); - tryAddLanguage("zh_TW"); - Collections.sort(list, new Comparator() { - @Override - public int compare(Language lhs, Language rhs) { - return lhs.name.compareTo(rhs.name); - } - }); - list.add(0, SYSTEM_LANGUAGE); - } + final String language; + final int underscore = id.indexOf("_"); + if (underscore >= 0) { + language = id.substring(0, underscore); + } else { + language = id; + } - private void tryAddLanguage(@Nonnull String locale) { - final Language language = makeLanguage(locale); - if (language != null) { - list.add(language); - } - } + for (Locale locale : locales) { + if (TextUtils.equals(locale.getLanguage(), language)) { + return locale; + } + } - @Nullable - private static Language makeLanguage(@Nonnull String localeId) { - final Locale locale = findLocaleById(localeId); - if (locale == null) { - return null; - } - return new Language(localeId, locale); - } + Log.d("Languages", "No locale found for " + id); + return null; + } - @Nullable - private static Locale findLocaleById(@Nonnull String id) { - for (Locale locale : locales) { - if (TextUtils.equals(locale.toString(), id)) { - return locale; - } - } + public void init(@Nonnull SharedPreferences preferences) { + preferences.registerOnSharedPreferenceChangeListener(this); + } - final String language; - final int underscore = id.indexOf("_"); - if (underscore >= 0) { - language = id.substring(0, underscore); - } else { - language = id; - } + @Nonnull + public List getList() { + Check.isMainThread(); + if (list.isEmpty()) { + loadList(); + } + return list; + } - for (Locale locale : locales) { - if (TextUtils.equals(locale.getLanguage(), language)) { - return locale; - } - } + private void loadList() { + Check.isMainThread(); + Check.isEmpty(list); + tryAddLanguage("ar"); + tryAddLanguage("cs"); + tryAddLanguage("en"); + tryAddLanguage("es_ES"); + tryAddLanguage("de"); + tryAddLanguage("fi"); + tryAddLanguage("fr"); + tryAddLanguage("it"); + tryAddLanguage("it"); + tryAddLanguage("pl"); + tryAddLanguage("pt_BR"); + tryAddLanguage("pt_PT"); + tryAddLanguage("ru"); + tryAddLanguage("tr"); + tryAddLanguage("vi"); + tryAddLanguage("uk"); + tryAddLanguage("ja"); + tryAddLanguage("zh_CN"); + tryAddLanguage("zh_TW"); + Collections.sort(list, new Comparator() { + @Override + public int compare(Language lhs, Language rhs) { + return lhs.name.compareTo(rhs.name); + } + }); + list.add(0, SYSTEM_LANGUAGE); + } - Log.d("Languages", "No locale found for " + id); - return null; - } + private void tryAddLanguage(@Nonnull String locale) { + final Language language = makeLanguage(locale); + if (language != null) { + list.add(language); + } + } - @Nonnull - public Language getCurrent() { - return get(Preferences.Gui.language.getPreference(App.getPreferences())); - } + @Nonnull + public Language getCurrent() { + return get(Preferences.Gui.language.getPreference(App.getPreferences())); + } - @Nonnull - public Language get(@Nonnull String code) { - Language language = findLanguageByCode(code); - if (language != null) { - return language; - } - return SYSTEM_LANGUAGE; - } + @Nonnull + public Language get(@Nonnull String code) { + Language language = findLanguageByCode(code); + if (language != null) { + return language; + } + return SYSTEM_LANGUAGE; + } - @Nullable - private Language findLanguageByCode(@Nonnull String code) { - for (Language language : getList()) { - if (TextUtils.equals(language.code, code)) { - return language; - } - } - return null; - } + @Nullable + private Language findLanguageByCode(@Nonnull String code) { + for (Language language : getList()) { + if (TextUtils.equals(language.code, code)) { + return language; + } + } + return null; + } - @Override - public void onSharedPreferenceChanged(@Nonnull SharedPreferences p, String key) { - if (Preferences.Gui.language.isSameKey(key)) { - updateLanguage(App.getApplication(), false); - } - } + @Override + public void onSharedPreferenceChanged(@Nonnull SharedPreferences p, String key) { + if (Preferences.Gui.language.isSameKey(key)) { + updateLanguage(App.getApplication(), false); + } + } - public void updateLanguage(@Nonnull Context context, boolean initial) { - final Language language = getCurrent(); - // we don't need to set system language while starting up the app - if (!initial || !language.isSystem()) { - if (!Locale.getDefault().equals(language.locale)) { - Locale.setDefault(language.locale); - } + public void updateLanguage(@Nonnull Context context, boolean initial) { + final Language language = getCurrent(); + // we don't need to set system language while starting up the app + if (!initial || !language.isSystem()) { + if (!Locale.getDefault().equals(language.locale)) { + Locale.setDefault(language.locale); + } - final Resources r = context.getResources(); - final DisplayMetrics dm = r.getDisplayMetrics(); - final Configuration c = r.getConfiguration(); - if (c.locale == null || !c.locale.equals(language.locale)) { - c.locale = language.locale; - r.updateConfiguration(c, dm); - } - } - } + final Resources r = context.getResources(); + final DisplayMetrics dm = r.getDisplayMetrics(); + final Configuration c = r.getConfiguration(); + if (c.locale == null || !c.locale.equals(language.locale)) { + c.locale = language.locale; + r.updateConfiguration(c, dm); + } + } + } } \ No newline at end of file diff --git a/android-app/src/main/java/org/solovyev/android/calculator/math/edit/AbstractMathEntityListFragment.java b/android-app/src/main/java/org/solovyev/android/calculator/math/edit/AbstractMathEntityListFragment.java index 1b09a9d9..3c054127 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/math/edit/AbstractMathEntityListFragment.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/math/edit/AbstractMathEntityListFragment.java @@ -67,14 +67,14 @@ import javax.annotation.Nullable; public abstract class AbstractMathEntityListFragment extends ListFragment implements CalculatorEventListener { /* - ********************************************************************** + ********************************************************************** * * 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"; /* @@ -84,251 +84,195 @@ public abstract class AbstractMathEntityListFragment exten * ********************************************************************** */ + @Nonnull + private final FragmentUi ui; + @Nonnull + private final Handler uiHandler = new Handler(); + @Nullable + private MathEntityArrayAdapter adapter; + @Nullable + private String category; - @Nullable - private MathEntityArrayAdapter adapter; + protected AbstractMathEntityListFragment(@Nonnull CalculatorFragmentType fragmentType) { + ui = CalculatorApplication.getInstance().createFragmentHelper(fragmentType.getDefaultLayoutId(), fragmentType.getDefaultTitleResId()); + } - @Nullable - private String category; + @Nonnull + public static Bundle createBundleFor(@Nonnull String categoryId) { + final Bundle result = new Bundle(1); + putCategory(result, categoryId); + return result; + } - @Nonnull - private final FragmentUi ui; + static void putCategory(@Nonnull Bundle bundle, @Nonnull String categoryId) { + bundle.putString(MATH_ENTITY_CATEGORY_EXTRA_STRING, categoryId); + } - @Nonnull - private final Handler uiHandler = new Handler(); + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); - protected AbstractMathEntityListFragment(@Nonnull CalculatorFragmentType fragmentType) { - ui = CalculatorApplication.getInstance().createFragmentHelper(fragmentType.getDefaultLayoutId(), fragmentType.getDefaultTitleResId()); - } + final Bundle bundle = getArguments(); + if (bundle != null) { + category = bundle.getString(MATH_ENTITY_CATEGORY_EXTRA_STRING); + } - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); + ui.onCreate(this); + } - final Bundle bundle = getArguments(); - if (bundle != null) { - category = bundle.getString(MATH_ENTITY_CATEGORY_EXTRA_STRING); - } + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + return ui.onCreateView(this, inflater, container); + } - ui.onCreate(this); - } + @Override + public void onViewCreated(View root, Bundle savedInstanceState) { + super.onViewCreated(root, savedInstanceState); - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - return ui.onCreateView(this, inflater, container); - } + ui.onViewCreated(this, root); - @Override - public void onViewCreated(View root, Bundle savedInstanceState) { - super.onViewCreated(root, savedInstanceState); + final ListView lv = getListView(); + lv.setTextFilterEnabled(true); - ui.onViewCreated(this, root); + lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { + public void onItemClick(final AdapterView parent, + final View view, + final int position, + final long id) { + final AMenuItem onClick = getOnClickAction(); + if (onClick != null) { + onClick.onClick(((T) parent.getItemAtPosition(position)), getActivity()); + } + } + }); - final ListView lv = getListView(); - lv.setTextFilterEnabled(true); + getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { + @Override + public boolean onItemLongClick(AdapterView parent, View view, int position, long id) { + final T item = (T) parent.getItemAtPosition(position); - lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { - public void onItemClick(final AdapterView parent, - final View view, - final int position, - final long id) { - final AMenuItem onClick = getOnClickAction(); - if (onClick != null) { - onClick.onClick(((T) parent.getItemAtPosition(position)), getActivity()); - } - } - }); + final List> menuItems = getMenuItemsOnLongClick(item); - getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { - @Override - public boolean onItemLongClick(AdapterView parent, View view, int position, long id) { - final T item = (T) parent.getItemAtPosition(position); + if (!menuItems.isEmpty()) { + final ContextMenuBuilder, T> menuBuilder = ContextMenuBuilder.newInstance(AbstractMathEntityListFragment.this.getActivity(), "math-entity-menu", ListContextMenu.newInstance(menuItems)); + menuBuilder.build(item).show(); + } - final List> menuItems = getMenuItemsOnLongClick(item); + return true; + } + }); + } - if (!menuItems.isEmpty()) { - final ContextMenuBuilder, T> menuBuilder = ContextMenuBuilder.newInstance(AbstractMathEntityListFragment.this.getActivity(), "math-entity-menu", ListContextMenu.newInstance(menuItems)); - menuBuilder.build(item).show(); - } + @Nullable + protected abstract AMenuItem getOnClickAction(); - return true; - } - }); - } + @Override + public void onDestroyView() { + ui.onDestroyView(this); + super.onDestroyView(); + } - @Nullable - protected abstract AMenuItem getOnClickAction(); + @Override + public void onDestroy() { + ui.onDestroy(this); - @Override - public void onDestroyView() { - ui.onDestroyView(this); - super.onDestroyView(); - } + super.onDestroy(); + } - @Override - public void onDestroy() { - ui.onDestroy(this); + @Nonnull + protected abstract List> getMenuItemsOnLongClick(@Nonnull T item); - super.onDestroy(); - } + @Override + public void onPause() { + this.ui.onPause(this); - @Nonnull - protected abstract List> getMenuItemsOnLongClick(@Nonnull T item); + super.onPause(); + } - @Override - public void onPause() { - this.ui.onPause(this); + @Override + public void onResume() { + super.onResume(); - super.onPause(); - } + this.ui.onResume(this); - @Override - public void onResume() { - super.onResume(); + adapter = new MathEntityArrayAdapter(getDescriptionGetter(), this.getActivity(), getMathEntitiesByCategory()); + setListAdapter(adapter); - this.ui.onResume(this); + sort(); + } - adapter = new MathEntityArrayAdapter(getDescriptionGetter(), this.getActivity(), getMathEntitiesByCategory()); - setListAdapter(adapter); + @Nonnull + private List getMathEntitiesByCategory() { + final List result = getMathEntities(); - sort(); - } + new Filter(new JPredicate() { + @Override + public boolean apply(T t) { + return !isInCategory(t); + } + }).filter(result.iterator()); - @Nonnull - private List getMathEntitiesByCategory() { - final List result = getMathEntities(); + return result; + } - new Filter(new JPredicate() { - @Override - public boolean apply(T t) { - return !isInCategory(t); - } - }).filter(result.iterator()); + protected boolean isInCategory(@Nullable T t) { + return t != null && (category == null || Objects.areEqual(getMathEntityCategory(t), category)); + } - return result; - } + @Nonnull + protected abstract MathEntityDescriptionGetter getDescriptionGetter(); - protected boolean isInCategory(@Nullable T t) { - return t != null && (category == null || Objects.areEqual(getMathEntityCategory(t), category)); - } + @Nonnull + protected abstract List getMathEntities(); - @Nonnull - protected abstract MathEntityDescriptionGetter getDescriptionGetter(); + @Nullable + abstract String getMathEntityCategory(@Nonnull T t); - @Nonnull - protected abstract List getMathEntities(); + protected void sort() { + final MathEntityArrayAdapter localAdapter = adapter; + if (localAdapter != null) { + localAdapter.sort(new Comparator() { + @Override + public int compare(T function1, T function2) { + return function1.getName().compareTo(function2.getName()); + } + }); - @Nullable - abstract String getMathEntityCategory(@Nonnull T t); + localAdapter.notifyDataSetChanged(); + } + } - protected void sort() { - final MathEntityArrayAdapter localAdapter = adapter; - if (localAdapter != null) { - localAdapter.sort(new Comparator() { - @Override - public int compare(T function1, T function2) { - return function1.getName().compareTo(function2.getName()); - } - }); + public void addToAdapter(@Nonnull T mathEntity) { + if (this.adapter != null) { + this.adapter.add(mathEntity); + } + } - localAdapter.notifyDataSetChanged(); - } - } + public void removeFromAdapter(@Nonnull T mathEntity) { + if (this.adapter != null) { + this.adapter.remove(mathEntity); + } + } - protected static class MathEntityArrayAdapter extends ArrayAdapter { + public void notifyAdapter() { + if (this.adapter != null) { + this.adapter.notifyDataSetChanged(); + } + } - @Nonnull - private final MathEntityDescriptionGetter descriptionGetter; + @Nullable + protected MathEntityArrayAdapter getAdapter() { + return adapter; + } - private MathEntityArrayAdapter(@Nonnull MathEntityDescriptionGetter descriptionGetter, - @Nonnull Context context, - @Nonnull List objects) { - super(context, R.layout.math_entity, R.id.math_entity_text, objects); - this.descriptionGetter = descriptionGetter; - } + @Nonnull + protected Handler getUiHandler() { + return uiHandler; + } - @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); - } - - - return result; - } - - private void fillView(int position, @Nonnull ViewGroup result) { - final T mathEntity = getItem(position); - - 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 TextView description = (TextView) result.findViewById(R.id.math_entity_short_description); - if (!Strings.isEmpty(mathEntityDescription)) { - description.setVisibility(View.VISIBLE); - description.setText(mathEntityDescription); - } else { - description.setVisibility(View.GONE); - } - } - } - - protected static class MathEntityDescriptionGetterImpl implements MathEntityDescriptionGetter { - - @Nonnull - private final CalculatorMathRegistry mathRegistry; - - public MathEntityDescriptionGetterImpl(@Nonnull CalculatorMathRegistry mathRegistry) { - this.mathRegistry = mathRegistry; - } - - @Override - public String getDescription(@Nonnull Context context, @Nonnull String mathEntityName) { - return this.mathRegistry.getDescription(mathEntityName); - } - } - - protected static interface MathEntityDescriptionGetter { - - @Nullable - String getDescription(@Nonnull Context context, @Nonnull String mathEntityName); - } - - public void addToAdapter(@Nonnull T mathEntity) { - if (this.adapter != null) { - this.adapter.add(mathEntity); - } - } - - public void removeFromAdapter(@Nonnull T mathEntity) { - if (this.adapter != null) { - this.adapter.remove(mathEntity); - } - } - - public void notifyAdapter() { - if (this.adapter != null) { - this.adapter.notifyDataSetChanged(); - } - } - - @Nullable - protected MathEntityArrayAdapter getAdapter() { - return adapter; - } - - @Nonnull - protected Handler getUiHandler() { - return uiHandler; - } + @Override + public void onCalculatorEvent(@Nonnull CalculatorEventData calculatorEventData, @Nonnull CalculatorEventType calculatorEventType, @Nullable Object data) { + } /* ********************************************************************** @@ -338,18 +282,70 @@ public abstract class AbstractMathEntityListFragment exten ********************************************************************** */ - @Nonnull - public static Bundle createBundleFor(@Nonnull String categoryId) { - final Bundle result = new Bundle(1); - putCategory(result, categoryId); - return result; - } + protected static interface MathEntityDescriptionGetter { - static void putCategory(@Nonnull Bundle bundle, @Nonnull String categoryId) { - bundle.putString(MATH_ENTITY_CATEGORY_EXTRA_STRING, categoryId); - } + @Nullable + String getDescription(@Nonnull Context context, @Nonnull String mathEntityName); + } - @Override - public void onCalculatorEvent(@Nonnull CalculatorEventData calculatorEventData, @Nonnull CalculatorEventType calculatorEventType, @Nullable Object data) { - } + protected static class MathEntityArrayAdapter extends ArrayAdapter { + + @Nonnull + private final MathEntityDescriptionGetter descriptionGetter; + + private MathEntityArrayAdapter(@Nonnull MathEntityDescriptionGetter descriptionGetter, + @Nonnull Context context, + @Nonnull List objects) { + super(context, R.layout.math_entity, R.id.math_entity_text, objects); + this.descriptionGetter = descriptionGetter; + } + + @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); + } + + + return result; + } + + private void fillView(int position, @Nonnull ViewGroup result) { + final T mathEntity = getItem(position); + + 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 TextView description = (TextView) result.findViewById(R.id.math_entity_short_description); + if (!Strings.isEmpty(mathEntityDescription)) { + description.setVisibility(View.VISIBLE); + description.setText(mathEntityDescription); + } else { + description.setVisibility(View.GONE); + } + } + } + + protected static class MathEntityDescriptionGetterImpl implements MathEntityDescriptionGetter { + + @Nonnull + private final CalculatorMathRegistry mathRegistry; + + public MathEntityDescriptionGetterImpl(@Nonnull CalculatorMathRegistry mathRegistry) { + this.mathRegistry = mathRegistry; + } + + @Override + public String getDescription(@Nonnull Context context, @Nonnull String mathEntityName) { + return this.mathRegistry.getDescription(mathEntityName); + } + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/math/edit/CalculatorFunctionsActivity.java b/android-app/src/main/java/org/solovyev/android/calculator/math/edit/CalculatorFunctionsActivity.java index 3f6123a1..1593722f 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/math/edit/CalculatorFunctionsActivity.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/math/edit/CalculatorFunctionsActivity.java @@ -25,58 +25,66 @@ package org.solovyev.android.calculator.math.edit; import android.content.Intent; import android.os.Bundle; import android.util.Log; -import org.solovyev.android.calculator.*; + +import org.solovyev.android.calculator.AndroidFunctionCategory; +import org.solovyev.android.calculator.BaseActivity; +import org.solovyev.android.calculator.CalculatorEventData; +import org.solovyev.android.calculator.CalculatorEventListener; +import org.solovyev.android.calculator.CalculatorEventType; +import org.solovyev.android.calculator.CalculatorFragmentType; +import org.solovyev.android.calculator.FunctionCategory; +import org.solovyev.android.calculator.R; import javax.annotation.Nonnull; import javax.annotation.Nullable; public class CalculatorFunctionsActivity extends BaseActivity implements CalculatorEventListener { - public CalculatorFunctionsActivity() { - super(R.layout.main_empty, CalculatorFunctionsActivity.class.getSimpleName()); - } + public CalculatorFunctionsActivity() { + super(R.layout.main_empty, CalculatorFunctionsActivity.class.getSimpleName()); + } - @Override - public void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); + @Override + public void onCreate(@Nullable Bundle savedInstanceState) { + super.onCreate(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()); + } - ui.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); - } - } - } + ui.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 - public void onCalculatorEvent(@Nonnull CalculatorEventData calculatorEventData, @Nonnull CalculatorEventType calculatorEventType, @Nullable Object data) { - switch (calculatorEventType) { - case use_function: - this.finish(); - break; - } - } + @Override + public void onCalculatorEvent(@Nonnull CalculatorEventData calculatorEventData, @Nonnull CalculatorEventType calculatorEventType, @Nullable Object data) { + switch (calculatorEventType) { + case use_function: + this.finish(); + break; + } + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/math/edit/CalculatorFunctionsFragment.java b/android-app/src/main/java/org/solovyev/android/calculator/math/edit/CalculatorFunctionsFragment.java index 1c38c4a8..eac0912b 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/math/edit/CalculatorFunctionsFragment.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/math/edit/CalculatorFunctionsFragment.java @@ -30,21 +30,31 @@ import android.support.v7.app.ActionBarActivity; import android.text.ClipboardManager; import android.view.View; import android.widget.ListView; + import com.melnykov.fab.FloatingActionButton; -import jscl.math.function.Function; -import jscl.math.function.IFunction; -import org.solovyev.android.calculator.*; + +import org.solovyev.android.calculator.CalculatorEventData; +import org.solovyev.android.calculator.CalculatorEventType; +import org.solovyev.android.calculator.CalculatorFragmentType; +import org.solovyev.android.calculator.CalculatorMathRegistry; +import org.solovyev.android.calculator.Change; +import org.solovyev.android.calculator.Locator; +import org.solovyev.android.calculator.R; import org.solovyev.android.calculator.function.FunctionEditDialogFragment; import org.solovyev.android.menu.AMenuItem; import org.solovyev.android.menu.LabeledMenuItem; import org.solovyev.common.text.Strings; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +import jscl.math.function.Function; +import jscl.math.function.IFunction; + /** * User: serso * Date: 10/29/11 @@ -52,219 +62,219 @@ import java.util.List; */ public class CalculatorFunctionsFragment extends AbstractMathEntityListFragment { - public static final String CREATE_FUNCTION_EXTRA = "create_function"; + 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) { - super.onCreate(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, getFragmentManager()); + 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, getFragmentManager()); - // 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 - public void onViewCreated(View root, Bundle savedInstanceState) { - super.onViewCreated(root, savedInstanceState); + @Override + public void onViewCreated(View root, Bundle savedInstanceState) { + super.onViewCreated(root, savedInstanceState); - final ListView lv = getListView(); - final FloatingActionButton fab = (FloatingActionButton) root.findViewById(R.id.fab); - fab.setVisibility(View.VISIBLE); - fab.attachToListView(lv); - fab.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - FunctionEditDialogFragment.showDialog(FunctionEditDialogFragment.Input.newInstance(), getFragmentManager()); - } - }); - } + final ListView lv = getListView(); + final FloatingActionButton fab = (FloatingActionButton) root.findViewById(R.id.fab); + fab.setVisibility(View.VISIBLE); + fab.attachToListView(lv); + fab.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + FunctionEditDialogFragment.showDialog(FunctionEditDialogFragment.Input.newInstance(), getFragmentManager()); + } + }); + } - @Override - protected AMenuItem getOnClickAction() { - return LongClickMenuItem.use; - } + @Override + protected AMenuItem getOnClickAction() { + return LongClickMenuItem.use; + } - @Nonnull - @Override - protected List> getMenuItemsOnLongClick(@Nonnull Function item) { - List> result = new ArrayList>(Arrays.asList(LongClickMenuItem.values())); + @Nonnull + @Override + protected List> getMenuItemsOnLongClick(@Nonnull Function item) { + List> result = new ArrayList>(Arrays.asList(LongClickMenuItem.values())); - final CalculatorMathRegistry functionsRegistry = Locator.getInstance().getEngine().getFunctionsRegistry(); - if (Strings.isEmpty(functionsRegistry.getDescription(item.getName()))) { - result.remove(LongClickMenuItem.copy_description); - } + final CalculatorMathRegistry 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; - } + return result; + } - @Nonnull - @Override - protected MathEntityDescriptionGetter getDescriptionGetter() { - return new MathEntityDescriptionGetterImpl(Locator.getInstance().getEngine().getFunctionsRegistry()); - } + @Nonnull + @Override + protected MathEntityDescriptionGetter getDescriptionGetter() { + return new MathEntityDescriptionGetterImpl(Locator.getInstance().getEngine().getFunctionsRegistry()); + } - @Nonnull - @Override - protected List getMathEntities() { - return new ArrayList(Locator.getInstance().getEngine().getFunctionsRegistry().getEntities()); - } + @Nonnull + @Override + protected List getMathEntities() { + return new ArrayList(Locator.getInstance().getEngine().getFunctionsRegistry().getEntities()); + } - @Override - protected String getMathEntityCategory(@Nonnull Function function) { - return Locator.getInstance().getEngine().getFunctionsRegistry().getCategory(function); - } + @Override + protected String getMathEntityCategory(@Nonnull Function function) { + return Locator.getInstance().getEngine().getFunctionsRegistry().getCategory(function); + } - @Override - public void onCalculatorEvent(@Nonnull CalculatorEventData calculatorEventData, @Nonnull CalculatorEventType calculatorEventType, @Nullable Object data) { - super.onCalculatorEvent(calculatorEventData, calculatorEventType, data); + @Override + public void onCalculatorEvent(@Nonnull CalculatorEventData calculatorEventData, @Nonnull 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) data); - break; + case function_changed: + processFunctionChanged((Change) data); + break; - case function_removed: - processFunctionRemoved((Function) data); - break; - } - } + case function_removed: + processFunctionRemoved((Function) data); + break; + } + } - private void processFunctionRemoved(@Nonnull final Function function) { - if (this.isInCategory(function)) { - getUiHandler().post(new Runnable() { - @Override - public void run() { - removeFromAdapter(function); - notifyAdapter(); - } - }); - } - } + private void processFunctionRemoved(@Nonnull final Function function) { + if (this.isInCategory(function)) { + getUiHandler().post(new Runnable() { + @Override + public void run() { + removeFromAdapter(function); + notifyAdapter(); + } + }); + } + } - private void processFunctionChanged(@Nonnull final Change change) { - final IFunction newFunction = change.getNewValue(); + private void processFunctionChanged(@Nonnull final Change change) { + final IFunction newFunction = change.getNewValue(); - if (newFunction instanceof Function) { + if (newFunction instanceof Function) { - if (this.isInCategory((Function) newFunction)) { + if (this.isInCategory((Function) newFunction)) { - getUiHandler().post(new Runnable() { - @Override - public void run() { - IFunction oldValue = change.getOldValue(); + getUiHandler().post(new Runnable() { + @Override + public void run() { + IFunction oldValue = change.getOldValue(); - if (oldValue.isIdDefined()) { - final MathEntityArrayAdapter adapter = getAdapter(); - 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())) { - adapter.remove(functionFromAdapter); - break; - } - } - } - } + if (oldValue.isIdDefined()) { + final MathEntityArrayAdapter adapter = getAdapter(); + 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())) { + adapter.remove(functionFromAdapter); + break; + } + } + } + } - addToAdapter((Function) newFunction); - sort(); - } - }); - } - } else { - throw new IllegalArgumentException("Function must be instance of jscl.math.function.Function class!"); - } - } + addToAdapter((Function) newFunction); + sort(); + } + }); + } + } else { + throw new IllegalArgumentException("Function must be instance of jscl.math.function.Function class!"); + } + } - private void processFunctionAdded(@Nonnull final Function function) { - if (this.isInCategory(function)) { - getUiHandler().post(new Runnable() { - @Override - public void run() { - addToAdapter(function); - sort(); - } - }); - } - } + private void processFunctionAdded(@Nonnull final Function function) { + if (this.isInCategory(function)) { + getUiHandler().post(new Runnable() { + @Override + public void run() { + addToAdapter(function); + sort(); + } + }); + } + } /* - ********************************************************************** + ********************************************************************** * * STATIC * ********************************************************************** */ - private static enum LongClickMenuItem implements LabeledMenuItem { - use(R.string.c_use) { - @Override - public void onClick(@Nonnull Function function, @Nonnull Context context) { - Locator.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.use_function, function); - } - }, + private static enum LongClickMenuItem implements LabeledMenuItem { + use(R.string.c_use) { + @Override + public void onClick(@Nonnull Function function, @Nonnull Context context) { + Locator.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.use_function, function); + } + }, - edit(R.string.c_edit) { - @Override - public void onClick(@Nonnull Function function, @Nonnull Context context) { - if (function instanceof IFunction) { - FunctionEditDialogFragment.showDialog(FunctionEditDialogFragment.Input.newFromFunction((IFunction) function), ((ActionBarActivity) context).getSupportFragmentManager()); - } - } - }, + edit(R.string.c_edit) { + @Override + public void onClick(@Nonnull Function function, @Nonnull Context context) { + if (function instanceof IFunction) { + FunctionEditDialogFragment.showDialog(FunctionEditDialogFragment.Input.newFromFunction((IFunction) function), ((ActionBarActivity) context).getSupportFragmentManager()); + } + } + }, - remove(R.string.c_remove) { - @Override - public void onClick(@Nonnull Function function, @Nonnull Context context) { - MathEntityRemover.newFunctionRemover(function, null, context, context).showConfirmationDialog(); - } - }, + remove(R.string.c_remove) { + @Override + public void onClick(@Nonnull Function function, @Nonnull Context context) { + MathEntityRemover.newFunctionRemover(function, null, context, context).showConfirmationDialog(); + } + }, - copy_description(R.string.c_copy_description) { - @Override - public void onClick(@Nonnull Function function, @Nonnull 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(@Nonnull Function function, @Nonnull 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; + } - @Nonnull - @Override - public String getCaption(@Nonnull Context context) { - return context.getString(captionId); - } - } + @Nonnull + @Override + public String getCaption(@Nonnull Context context) { + return context.getString(captionId); + } + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/math/edit/CalculatorOperatorsActivity.java b/android-app/src/main/java/org/solovyev/android/calculator/math/edit/CalculatorOperatorsActivity.java index 1924d81a..60338ec7 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/math/edit/CalculatorOperatorsActivity.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/math/edit/CalculatorOperatorsActivity.java @@ -23,39 +23,47 @@ package org.solovyev.android.calculator.math.edit; import android.os.Bundle; -import org.solovyev.android.calculator.*; + +import org.solovyev.android.calculator.AndroidOperatorCategory; +import org.solovyev.android.calculator.BaseActivity; +import org.solovyev.android.calculator.CalculatorEventData; +import org.solovyev.android.calculator.CalculatorEventListener; +import org.solovyev.android.calculator.CalculatorEventType; +import org.solovyev.android.calculator.CalculatorFragmentType; +import org.solovyev.android.calculator.OperatorCategory; +import org.solovyev.android.calculator.R; import javax.annotation.Nonnull; import javax.annotation.Nullable; public class CalculatorOperatorsActivity extends BaseActivity implements CalculatorEventListener { - public CalculatorOperatorsActivity() { - super(R.layout.main_empty, CalculatorOperatorsActivity.class.getSimpleName()); - } + public CalculatorOperatorsActivity() { + super(R.layout.main_empty, CalculatorOperatorsActivity.class.getSimpleName()); + } - @Override - public void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); + @Override + public void onCreate(@Nullable Bundle savedInstanceState) { + super.onCreate(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) { - ui.addTab(this, fragmentType.createSubFragmentTag(category.name()), fragmentType.getFragmentClass(), AbstractMathEntityListFragment.createBundleFor(category.name()), androidCategory.getCaptionId(), R.id.main_layout); - } else { - ui.logError("Unable to find android operator category for " + category); - } - } - } + for (OperatorCategory category : OperatorCategory.getCategoriesByTabOrder()) { + final AndroidOperatorCategory androidCategory = AndroidOperatorCategory.valueOf(category); + if (androidCategory != null) { + ui.addTab(this, fragmentType.createSubFragmentTag(category.name()), fragmentType.getFragmentClass(), AbstractMathEntityListFragment.createBundleFor(category.name()), androidCategory.getCaptionId(), R.id.main_layout); + } else { + ui.logError("Unable to find android operator category for " + category); + } + } + } - @Override - public void onCalculatorEvent(@Nonnull CalculatorEventData calculatorEventData, @Nonnull CalculatorEventType calculatorEventType, @Nullable Object data) { - switch (calculatorEventType) { - case use_operator: - this.finish(); - break; - } - } + @Override + public void onCalculatorEvent(@Nonnull CalculatorEventData calculatorEventData, @Nonnull CalculatorEventType calculatorEventType, @Nullable Object data) { + switch (calculatorEventType) { + case use_operator: + this.finish(); + break; + } + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/math/edit/CalculatorOperatorsFragment.java b/android-app/src/main/java/org/solovyev/android/calculator/math/edit/CalculatorOperatorsFragment.java index b8a76fe1..71e57a19 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/math/edit/CalculatorOperatorsFragment.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/math/edit/CalculatorOperatorsFragment.java @@ -25,9 +25,6 @@ package org.solovyev.android.calculator.math.edit; import android.app.Activity; import android.content.Context; import android.text.ClipboardManager; -import jscl.math.operator.Operator; - -import javax.annotation.Nonnull; import org.solovyev.android.calculator.CalculatorEventType; import org.solovyev.android.calculator.CalculatorFragmentType; @@ -41,6 +38,10 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import javax.annotation.Nonnull; + +import jscl.math.operator.Operator; + /** * User: serso * Date: 11/17/11 @@ -49,109 +50,109 @@ import java.util.List; public class CalculatorOperatorsFragment extends AbstractMathEntityListFragment { - public CalculatorOperatorsFragment() { - super(CalculatorFragmentType.operators); - } + public CalculatorOperatorsFragment() { + super(CalculatorFragmentType.operators); + } - @Override - protected AMenuItem getOnClickAction() { - return LongClickMenuItem.use; - } + @Override + protected AMenuItem getOnClickAction() { + return LongClickMenuItem.use; + } - @Nonnull - @Override - protected List> getMenuItemsOnLongClick(@Nonnull Operator item) { - final List> result = new ArrayList>(Arrays.asList(LongClickMenuItem.values())); + @Nonnull + @Override + protected List> getMenuItemsOnLongClick(@Nonnull Operator item) { + final List> result = new ArrayList>(Arrays.asList(LongClickMenuItem.values())); - if (Strings.isEmpty(OperatorDescriptionGetter.instance.getDescription(this.getActivity(), item.getName()))) { - result.remove(LongClickMenuItem.copy_description); - } + if (Strings.isEmpty(OperatorDescriptionGetter.instance.getDescription(this.getActivity(), item.getName()))) { + result.remove(LongClickMenuItem.copy_description); + } - return result; - } + return result; + } - @Nonnull - @Override - protected MathEntityDescriptionGetter getDescriptionGetter() { - return OperatorDescriptionGetter.instance; - } + @Nonnull + @Override + protected MathEntityDescriptionGetter getDescriptionGetter() { + return OperatorDescriptionGetter.instance; + } - @Nonnull - @Override - protected List getMathEntities() { - final List result = new ArrayList(); + @Nonnull + @Override + protected List getMathEntities() { + final List result = new ArrayList(); - 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(@Nonnull Operator operator) { - String result = Locator.getInstance().getEngine().getOperatorsRegistry().getCategory(operator); - if (result == null) { - result = Locator.getInstance().getEngine().getPostfixFunctionsRegistry().getCategory(operator); - } + @Override + protected String getMathEntityCategory(@Nonnull 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; + instance; - @Override - public String getDescription(@Nonnull Context context, @Nonnull 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(@Nonnull Context context, @Nonnull 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 * ********************************************************************** */ - private static enum LongClickMenuItem implements LabeledMenuItem { + private static enum LongClickMenuItem implements LabeledMenuItem { - use(R.string.c_use) { - @Override - public void onClick(@Nonnull Operator data, @Nonnull Context context) { - Locator.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.use_operator, data); - } - }, + use(R.string.c_use) { + @Override + public void onClick(@Nonnull Operator data, @Nonnull Context context) { + Locator.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.use_operator, data); + } + }, - copy_description(R.string.c_copy_description) { - @Override - public void onClick(@Nonnull Operator data, @Nonnull 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(@Nonnull Operator data, @Nonnull 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; + } - @Nonnull - @Override - public String getCaption(@Nonnull Context context) { - return context.getString(captionId); - } - } + @Nonnull + @Override + public String getCaption(@Nonnull Context context) { + return context.getString(captionId); + } + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/math/edit/CalculatorVarsActivity.java b/android-app/src/main/java/org/solovyev/android/calculator/math/edit/CalculatorVarsActivity.java index 08be5def..ac031744 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/math/edit/CalculatorVarsActivity.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/math/edit/CalculatorVarsActivity.java @@ -24,60 +24,68 @@ package org.solovyev.android.calculator.math.edit; import android.content.Intent; import android.os.Bundle; -import org.solovyev.android.calculator.*; + +import org.solovyev.android.calculator.AndroidVarCategory; +import org.solovyev.android.calculator.BaseActivity; +import org.solovyev.android.calculator.CalculatorEventData; +import org.solovyev.android.calculator.CalculatorEventListener; +import org.solovyev.android.calculator.CalculatorEventType; +import org.solovyev.android.calculator.CalculatorFragmentType; +import org.solovyev.android.calculator.R; +import org.solovyev.android.calculator.VarCategory; import javax.annotation.Nonnull; import javax.annotation.Nullable; public class CalculatorVarsActivity extends BaseActivity implements CalculatorEventListener { - public CalculatorVarsActivity() { - super(R.layout.main_empty, CalculatorVarsActivity.class.getSimpleName()); - } + public CalculatorVarsActivity() { + super(R.layout.main_empty, CalculatorVarsActivity.class.getSimpleName()); + } - @Override - public void onCreate(@Nullable Bundle savedInstanceState) { - super.onCreate(savedInstanceState); + @Override + public void onCreate(@Nullable Bundle savedInstanceState) { + super.onCreate(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) { - ui.addTab(this, fragmentType.createSubFragmentTag(category.name()), fragmentType.getFragmentClass(), fragmentParameters, androidVarCategory.getCaptionId(), R.id.main_layout); - } else { - ui.logError("Unable to find android var category for " + category); - } - } - } + if (androidVarCategory != null) { + ui.addTab(this, fragmentType.createSubFragmentTag(category.name()), fragmentType.getFragmentClass(), fragmentParameters, androidVarCategory.getCaptionId(), R.id.main_layout); + } else { + ui.logError("Unable to find android var category for " + category); + } + } + } - @Override - public void onCalculatorEvent(@Nonnull CalculatorEventData calculatorEventData, @Nonnull CalculatorEventType calculatorEventType, @Nullable Object data) { - switch (calculatorEventType) { - case use_constant: - this.finish(); - break; - } - } + @Override + public void onCalculatorEvent(@Nonnull CalculatorEventData calculatorEventData, @Nonnull CalculatorEventType calculatorEventType, @Nullable Object data) { + switch (calculatorEventType) { + case use_constant: + this.finish(); + break; + } + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/math/edit/CalculatorVarsFragment.java b/android-app/src/main/java/org/solovyev/android/calculator/math/edit/CalculatorVarsFragment.java index 15e75026..01ec409c 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/math/edit/CalculatorVarsFragment.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/math/edit/CalculatorVarsFragment.java @@ -27,9 +27,18 @@ import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.ListView; + import com.melnykov.fab.FloatingActionButton; -import jscl.math.function.IConstant; -import org.solovyev.android.calculator.*; + +import org.solovyev.android.calculator.CalculatorEventData; +import org.solovyev.android.calculator.CalculatorEventType; +import org.solovyev.android.calculator.CalculatorFragmentType; +import org.solovyev.android.calculator.CalculatorParseException; +import org.solovyev.android.calculator.Change; +import org.solovyev.android.calculator.Locator; +import org.solovyev.android.calculator.PreparedExpression; +import org.solovyev.android.calculator.R; +import org.solovyev.android.calculator.ToJsclTextProcessor; import org.solovyev.android.calculator.math.MathType; import org.solovyev.android.menu.AMenuItem; import org.solovyev.android.menu.LabeledMenuItem; @@ -37,12 +46,15 @@ import org.solovyev.common.JPredicate; import org.solovyev.common.collections.Collections; import org.solovyev.common.text.Strings; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +import jscl.math.function.IConstant; + /** * User: serso * Date: 9/28/11 @@ -50,233 +62,233 @@ import java.util.List; */ public class CalculatorVarsFragment extends AbstractMathEntityListFragment { - 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); + public static boolean isValidValue(@Nonnull String value) { + try { + final PreparedExpression expression = ToJsclTextProcessor.getInstance().process(value); + final List constants = expression.getUndefinedVars(); + return constants.isEmpty(); + } catch (RuntimeException e) { + return true; + } catch (CalculatorParseException e) { + return true; + } + } - 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), getFragmentManager()); + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); - // in order to stop intent for other tabs - bundle.remove(CREATE_VAR_EXTRA_STRING); - } - } + 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), getFragmentManager()); - setHasOptionsMenu(true); - } + // in order to stop intent for other tabs + bundle.remove(CREATE_VAR_EXTRA_STRING); + } + } - @Override - public void onViewCreated(View root, Bundle savedInstanceState) { - super.onViewCreated(root, savedInstanceState); + setHasOptionsMenu(true); + } - final ListView lv = getListView(); - final FloatingActionButton fab = (FloatingActionButton) root.findViewById(R.id.fab); - fab.setVisibility(View.VISIBLE); - fab.attachToListView(lv); - fab.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - VarEditDialogFragment.showDialog(VarEditDialogFragment.Input.newInstance(), getFragmentManager()); - } - }); - } + @Override + public void onViewCreated(View root, Bundle savedInstanceState) { + super.onViewCreated(root, savedInstanceState); - @Override - protected AMenuItem getOnClickAction() { - return LongClickMenuItem.use; - } + final ListView lv = getListView(); + final FloatingActionButton fab = (FloatingActionButton) root.findViewById(R.id.fab); + fab.setVisibility(View.VISIBLE); + fab.attachToListView(lv); + fab.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + VarEditDialogFragment.showDialog(VarEditDialogFragment.Input.newInstance(), getFragmentManager()); + } + }); + } - @Nonnull - @Override - protected List> getMenuItemsOnLongClick(@Nonnull IConstant item) { - final List> result = new ArrayList>(Arrays.asList(LongClickMenuItem.values())); + @Override + protected AMenuItem getOnClickAction() { + return LongClickMenuItem.use; + } - if (item.isSystem()) { - result.remove(LongClickMenuItem.edit); - result.remove(LongClickMenuItem.remove); - } + @Nonnull + @Override + protected List> getMenuItemsOnLongClick(@Nonnull IConstant item) { + final List> result = new ArrayList>(Arrays.asList(LongClickMenuItem.values())); - if (Strings.isEmpty(Locator.getInstance().getEngine().getVarsRegistry().getDescription(item.getName()))) { - result.remove(LongClickMenuItem.copy_description); - } + if (item.isSystem()) { + result.remove(LongClickMenuItem.edit); + result.remove(LongClickMenuItem.remove); + } - if (Strings.isEmpty(item.getValue())) { - result.remove(LongClickMenuItem.copy_value); - } + if (Strings.isEmpty(Locator.getInstance().getEngine().getVarsRegistry().getDescription(item.getName()))) { + result.remove(LongClickMenuItem.copy_description); + } - return result; - } + if (Strings.isEmpty(item.getValue())) { + result.remove(LongClickMenuItem.copy_value); + } - @Nonnull - @Override - protected MathEntityDescriptionGetter getDescriptionGetter() { - return new MathEntityDescriptionGetterImpl(Locator.getInstance().getEngine().getVarsRegistry()); - } + return result; + } - @SuppressWarnings({"UnusedDeclaration"}) - public void addVarButtonClickHandler(@Nonnull View v) { - VarEditDialogFragment.showDialog(VarEditDialogFragment.Input.newInstance(), this.getActivity().getSupportFragmentManager()); - } + @Nonnull + @Override + protected MathEntityDescriptionGetter getDescriptionGetter() { + return new MathEntityDescriptionGetterImpl(Locator.getInstance().getEngine().getVarsRegistry()); + } - @Nonnull - @Override - protected List getMathEntities() { - final List result = new ArrayList(Locator.getInstance().getEngine().getVarsRegistry().getEntities()); + @SuppressWarnings({"UnusedDeclaration"}) + public void addVarButtonClickHandler(@Nonnull View v) { + VarEditDialogFragment.showDialog(VarEditDialogFragment.Input.newInstance(), this.getActivity().getSupportFragmentManager()); + } - Collections.removeAll(result, new JPredicate() { - @Override - public boolean apply(@Nullable IConstant var) { - return var != null && Collections.contains(var.getName(), MathType.INFINITY_JSCL, MathType.NAN); - } - }); + @Nonnull + @Override + protected List getMathEntities() { + final List result = new ArrayList(Locator.getInstance().getEngine().getVarsRegistry().getEntities()); - return result; - } + Collections.removeAll(result, new JPredicate() { + @Override + public boolean apply(@Nullable IConstant var) { + return var != null && Collections.contains(var.getName(), MathType.INFINITY_JSCL, MathType.NAN); + } + }); - @Override - protected String getMathEntityCategory(@Nonnull IConstant var) { - return Locator.getInstance().getEngine().getVarsRegistry().getCategory(var); - } + return result; + } - public static boolean isValidValue(@Nonnull String value) { - try { - final PreparedExpression expression = ToJsclTextProcessor.getInstance().process(value); - final List constants = expression.getUndefinedVars(); - return constants.isEmpty(); - } catch (RuntimeException e) { - return true; - } catch (CalculatorParseException e) { - return true; - } - } + @Override + protected String getMathEntityCategory(@Nonnull IConstant var) { + return Locator.getInstance().getEngine().getVarsRegistry().getCategory(var); + } - @Override - public void onCalculatorEvent(@Nonnull CalculatorEventData calculatorEventData, @Nonnull CalculatorEventType calculatorEventType, @Nullable Object data) { - super.onCalculatorEvent(calculatorEventData, calculatorEventType, data); + @Override + public void onCalculatorEvent(@Nonnull CalculatorEventData calculatorEventData, @Nonnull 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) data); - break; + case constant_changed: + processConstantChanged((Change) data); + break; - case constant_removed: - processConstantRemoved((IConstant) data); - break; - } - } + case constant_removed: + processConstantRemoved((IConstant) data); + break; + } + } - private void processConstantRemoved(@Nonnull final IConstant constant) { - if (this.isInCategory(constant)) { - getUiHandler().post(new Runnable() { - @Override - public void run() { - removeFromAdapter(constant); - notifyAdapter(); - } - }); - } - } + private void processConstantRemoved(@Nonnull final IConstant constant) { + if (this.isInCategory(constant)) { + getUiHandler().post(new Runnable() { + @Override + public void run() { + removeFromAdapter(constant); + notifyAdapter(); + } + }); + } + } - private void processConstantChanged(@Nonnull final Change 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(@Nonnull final Change 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(@Nonnull final IConstant constant) { - if (this.isInCategory(constant)) { - getUiHandler().post(new Runnable() { - @Override - public void run() { - addToAdapter(constant); - sort(); - } - }); - } - } + private void processConstantAdded(@Nonnull final IConstant constant) { + if (this.isInCategory(constant)) { + getUiHandler().post(new Runnable() { + @Override + public void run() { + addToAdapter(constant); + sort(); + } + }); + } + } /* - ********************************************************************** + ********************************************************************** * * STATIC * ********************************************************************** */ - private static enum LongClickMenuItem implements LabeledMenuItem { - use(R.string.c_use) { - @Override - public void onClick(@Nonnull IConstant data, @Nonnull Context context) { - Locator.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.use_constant, data); - } - }, + private static enum LongClickMenuItem implements LabeledMenuItem { + use(R.string.c_use) { + @Override + public void onClick(@Nonnull IConstant data, @Nonnull Context context) { + Locator.getInstance().getCalculator().fireCalculatorEvent(CalculatorEventType.use_constant, data); + } + }, - edit(R.string.c_edit) { - @Override - public void onClick(@Nonnull IConstant constant, @Nonnull Context context) { - VarEditDialogFragment.showDialog(VarEditDialogFragment.Input.newFromConstant(constant), ((ActionBarActivity) context).getSupportFragmentManager()); - } - }, + edit(R.string.c_edit) { + @Override + public void onClick(@Nonnull IConstant constant, @Nonnull Context context) { + VarEditDialogFragment.showDialog(VarEditDialogFragment.Input.newFromConstant(constant), ((ActionBarActivity) context).getSupportFragmentManager()); + } + }, - remove(R.string.c_remove) { - @Override - public void onClick(@Nonnull IConstant constant, @Nonnull Context context) { - MathEntityRemover.newConstantRemover(constant, null, context, context).showConfirmationDialog(); - } - }, + remove(R.string.c_remove) { + @Override + public void onClick(@Nonnull IConstant constant, @Nonnull Context context) { + MathEntityRemover.newConstantRemover(constant, null, context, context).showConfirmationDialog(); + } + }, - copy_value(R.string.c_copy_value) { - @Override - public void onClick(@Nonnull IConstant data, @Nonnull Context context) { - final String text = data.getValue(); - if (!Strings.isEmpty(text)) { - if (text == null) throw new AssertionError(); - Locator.getInstance().getClipboard().setText(text); - } - } - }, + copy_value(R.string.c_copy_value) { + @Override + public void onClick(@Nonnull IConstant data, @Nonnull Context context) { + final String text = data.getValue(); + if (!Strings.isEmpty(text)) { + if (text == null) throw new AssertionError(); + Locator.getInstance().getClipboard().setText(text); + } + } + }, - copy_description(R.string.c_copy_description) { - @Override - public void onClick(@Nonnull IConstant data, @Nonnull Context context) { - final String text = Locator.getInstance().getEngine().getVarsRegistry().getDescription(data.getName()); - if (!Strings.isEmpty(text)) { - if (text == null) throw new AssertionError(); - Locator.getInstance().getClipboard().setText(text); - } - } - }; - private final int captionId; + copy_description(R.string.c_copy_description) { + @Override + public void onClick(@Nonnull IConstant data, @Nonnull Context context) { + final String text = Locator.getInstance().getEngine().getVarsRegistry().getDescription(data.getName()); + if (!Strings.isEmpty(text)) { + if (text == null) throw new AssertionError(); + Locator.getInstance().getClipboard().setText(text); + } + } + }; + private final int captionId; - LongClickMenuItem(int captionId) { - this.captionId = captionId; - } + LongClickMenuItem(int captionId) { + this.captionId = captionId; + } - @Nonnull - @Override - public String getCaption(@Nonnull Context context) { - return context.getString(captionId); - } - } + @Nonnull + @Override + public String getCaption(@Nonnull Context context) { + return context.getString(captionId); + } + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/math/edit/MathEntityRemover.java b/android-app/src/main/java/org/solovyev/android/calculator/math/edit/MathEntityRemover.java index 2d71ec8c..919f5c3d 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/math/edit/MathEntityRemover.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/math/edit/MathEntityRemover.java @@ -27,11 +27,6 @@ import android.content.Context; import android.content.DialogInterface; import android.view.View; import android.widget.TextView; -import jscl.math.function.Function; -import jscl.math.function.IConstant; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import org.solovyev.android.calculator.CalculatorEventType; import org.solovyev.android.calculator.CalculatorMathRegistry; @@ -39,6 +34,12 @@ import org.solovyev.android.calculator.Locator; import org.solovyev.android.calculator.R; import org.solovyev.common.math.MathEntity; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +import jscl.math.function.Function; +import jscl.math.function.IConstant; + /** * User: serso * Date: 12/22/11 @@ -46,63 +47,60 @@ import org.solovyev.common.math.MathEntity; */ public class MathEntityRemover implements View.OnClickListener, DialogInterface.OnClickListener { - @Nonnull - private final T mathEntity; + @Nonnull + private final T mathEntity; - @Nullable - private final DialogInterface.OnClickListener callbackOnCancel; + @Nullable + private final DialogInterface.OnClickListener callbackOnCancel; - private final boolean confirmed; + private final boolean confirmed; - @Nonnull - private final CalculatorMathRegistry varsRegistry; - - @Nonnull - private Context context; - - @Nonnull - private final Object source; - - @Nonnull - private final Params params; + @Nonnull + private final CalculatorMathRegistry varsRegistry; + @Nonnull + private final Object source; + @Nonnull + private final Params params; + @Nonnull + private Context context; /* - ********************************************************************** + ********************************************************************** * * CONSTRUCTORS * ********************************************************************** */ - private MathEntityRemover(@Nonnull T mathEntity, - @Nullable DialogInterface.OnClickListener callbackOnCancel, - boolean confirmed, - @Nonnull CalculatorMathRegistry varsRegistry, - @Nonnull Context context, - @Nonnull Object source, - @Nonnull Params params) { - this.mathEntity = mathEntity; - this.callbackOnCancel = callbackOnCancel; - this.confirmed = confirmed; - this.varsRegistry = varsRegistry; - this.context = context; - this.source = source; - this.params = params; - } + private MathEntityRemover(@Nonnull T mathEntity, + @Nullable DialogInterface.OnClickListener callbackOnCancel, + boolean confirmed, + @Nonnull CalculatorMathRegistry varsRegistry, + @Nonnull Context context, + @Nonnull Object source, + @Nonnull Params params) { + this.mathEntity = mathEntity; + this.callbackOnCancel = callbackOnCancel; + this.confirmed = confirmed; + this.varsRegistry = varsRegistry; + this.context = context; + this.source = source; + this.params = params; + } - public static MathEntityRemover newConstantRemover(@Nonnull IConstant constant, - @Nullable DialogInterface.OnClickListener callbackOnCancel, - @Nonnull Context context, - @Nonnull Object source) { - return new MathEntityRemover(constant, callbackOnCancel, false, Locator.getInstance().getEngine().getVarsRegistry(), context, source, Params.newConstantInstance()); - } + public static MathEntityRemover newConstantRemover(@Nonnull IConstant constant, + @Nullable DialogInterface.OnClickListener callbackOnCancel, + @Nonnull Context context, + @Nonnull Object source) { + return new MathEntityRemover(constant, callbackOnCancel, false, Locator.getInstance().getEngine().getVarsRegistry(), context, source, Params.newConstantInstance()); + } - public static MathEntityRemover newFunctionRemover(@Nonnull Function function, - @Nullable DialogInterface.OnClickListener callbackOnCancel, - @Nonnull Context context, - @Nonnull Object source) { - return new MathEntityRemover(function, callbackOnCancel, false, Locator.getInstance().getEngine().getFunctionsRegistry(), context, source, Params.newFunctionInstance()); - } + public static MathEntityRemover newFunctionRemover(@Nonnull Function function, + @Nullable DialogInterface.OnClickListener callbackOnCancel, + @Nonnull Context context, + @Nonnull Object source) { + return new MathEntityRemover(function, callbackOnCancel, false, Locator.getInstance().getEngine().getFunctionsRegistry(), context, source, Params.newFunctionInstance()); + } /* ********************************************************************** @@ -113,36 +111,36 @@ public class MathEntityRemover implements View.OnClickList */ - 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(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(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); + } /* ********************************************************************** @@ -152,43 +150,43 @@ public class MathEntityRemover implements View.OnClickList ********************************************************************** */ - 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; - } + private static 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; + } - public int getRemovalConfirmationQuestionResId() { - return removalConfirmationQuestionResId; - } + private static 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; + } - public CalculatorEventType getCalculatorEventType() { - return calculatorEventType; - } + public int getRemovalConfirmationTitleResId() { + return removalConfirmationTitleResId; + } - private static 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; - } + public int getRemovalConfirmationQuestionResId() { + return removalConfirmationQuestionResId; + } - private static 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; - } - } + public CalculatorEventType getCalculatorEventType() { + return calculatorEventType; + } + } } diff --git a/android-app/src/main/java/org/solovyev/android/calculator/math/edit/VarEditDialogFragment.java b/android-app/src/main/java/org/solovyev/android/calculator/math/edit/VarEditDialogFragment.java index f6bbf1d2..6d019752 100644 --- a/android-app/src/main/java/org/solovyev/android/calculator/math/edit/VarEditDialogFragment.java +++ b/android-app/src/main/java/org/solovyev/android/calculator/math/edit/VarEditDialogFragment.java @@ -32,19 +32,31 @@ import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; -import android.widget.*; -import jscl.math.function.IConstant; +import android.widget.Button; +import android.widget.EditText; +import android.widget.LinearLayout; +import android.widget.TextView; +import android.widget.Toast; + import org.solovyev.android.Views; -import org.solovyev.android.calculator.*; +import org.solovyev.android.calculator.App; +import org.solovyev.android.calculator.CalculatorEventData; +import org.solovyev.android.calculator.CalculatorEventListener; +import org.solovyev.android.calculator.CalculatorEventType; +import org.solovyev.android.calculator.Locator; +import org.solovyev.android.calculator.R; import org.solovyev.android.calculator.model.Var; import org.solovyev.common.text.Strings; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; import java.util.Arrays; import java.util.List; import java.util.Locale; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +import jscl.math.function.IConstant; + import static android.graphics.Paint.UNDERLINE_TEXT_FLAG; import static android.view.View.GONE; import static android.view.View.VISIBLE; @@ -55,274 +67,274 @@ import static android.widget.LinearLayout.HORIZONTAL; public class VarEditDialogFragment extends DialogFragment implements CalculatorEventListener { - private final static String greekAlphabet = "αβγδεζηθικλμνξοπρστυφχψω"; - private final static List acceptableChars = Arrays.asList(Strings.toObjects(("1234567890abcdefghijklmnopqrstuvwxyzйцукенгшщзхъфывапролджэячсмитьбюё_" + greekAlphabet).toCharArray())); + private final static String greekAlphabet = "αβγδεζηθικλμνξοπρστυφχψω"; + private final static List acceptableChars = Arrays.asList(Strings.toObjects(("1234567890abcdefghijklmnopqrstuvwxyzйцукенгшщзхъфывапролджэячсмитьбюё_" + greekAlphabet).toCharArray())); - private Input input; + private Input input; - public VarEditDialogFragment() { - input = Input.newInstance(); - } + public VarEditDialogFragment() { + input = Input.newInstance(); + } - @Nonnull - public static VarEditDialogFragment create(@Nonnull Input input) { - final VarEditDialogFragment fragment = new VarEditDialogFragment(); - fragment.input = input; - return fragment; - } + @Nonnull + public static VarEditDialogFragment create(@Nonnull Input input) { + final VarEditDialogFragment fragment = new VarEditDialogFragment(); + fragment.input = input; + return fragment; + } - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - return inflater.inflate(R.layout.var_edit, container, false); - } + public static void showDialog(@Nonnull Input input, @Nonnull FragmentManager fm) { + App.showDialog(create(input), "constant-editor", fm); + } - @Override - public void onResume() { - super.onResume(); + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + return inflater.inflate(R.layout.var_edit, container, false); + } - Locator.getInstance().getCalculator().addCalculatorEventListener(this); - } + @Override + public void onResume() { + super.onResume(); - @Override - public void onPause() { - Locator.getInstance().getCalculator().removeCalculatorEventListener(this); + Locator.getInstance().getCalculator().addCalculatorEventListener(this); + } - super.onPause(); - } + @Override + public void onPause() { + Locator.getInstance().getCalculator().removeCalculatorEventListener(this); - @Override - public void onViewCreated(@Nonnull View root, Bundle savedInstanceState) { - super.onViewCreated(root, savedInstanceState); + super.onPause(); + } - final String errorMsg = this.getString(R.string.c_char_is_not_accepted); + @Override + public void onViewCreated(@Nonnull View root, Bundle savedInstanceState) { + super.onViewCreated(root, savedInstanceState); - final EditText editName = (EditText) root.findViewById(R.id.var_edit_name); - editName.setText(input.getName()); - editName.addTextChangedListener(new TextWatcher() { + final String errorMsg = this.getString(R.string.c_char_is_not_accepted); - @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - } + final EditText editName = (EditText) root.findViewById(R.id.var_edit_name); + editName.setText(input.getName()); + editName.addTextChangedListener(new TextWatcher() { - @Override - public void onTextChanged(CharSequence s, int start, int before, int count) { - } + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) { + } - @Override - public void afterTextChanged(Editable s) { - for (int i = 0; i < s.length(); i++) { - char c = s.charAt(i); - if (!acceptableChars.contains(Character.toLowerCase(c))) { - s.delete(i, i + 1); - Toast.makeText(getActivity(), String.format(errorMsg, c), Toast.LENGTH_SHORT).show(); - } - } - } - }); + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + } - fillGreekKeyboard(root, editName); + @Override + public void afterTextChanged(Editable s) { + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if (!acceptableChars.contains(Character.toLowerCase(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(SOFT_INPUT_STATE_VISIBLE); + fillGreekKeyboard(root, editName); - final EditText editValue = (EditText) root.findViewById(R.id.var_edit_value); - editValue.setText(input.getValue()); + // show soft keyboard automatically + editName.requestFocus(); + getDialog().getWindow().setSoftInputMode(SOFT_INPUT_STATE_VISIBLE); - final EditText editDescription = (EditText) root.findViewById(R.id.var_edit_description); - editDescription.setText(input.getDescription()); + final EditText editValue = (EditText) root.findViewById(R.id.var_edit_value); + editValue.setText(input.getValue()); - final Var.Builder varBuilder; - final IConstant constant = input.getConstant(); - if (constant != null) { - varBuilder = new Var.Builder(constant); - } else { - varBuilder = new Var.Builder(); - } + final EditText editDescription = (EditText) root.findViewById(R.id.var_edit_description); + editDescription.setText(input.getDescription()); - root.findViewById(R.id.cancel_button).setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - dismiss(); - } - }); + 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.save_button).setOnClickListener(new VarEditorSaver(varBuilder, constant, root, Locator.getInstance().getEngine().getVarsRegistry(), this)); + root.findViewById(R.id.cancel_button).setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + dismiss(); + } + }); - if (constant == null) { - // CREATE MODE - getDialog().setTitle(R.string.c_var_create_var); + root.findViewById(R.id.save_button).setOnClickListener(new VarEditorSaver(varBuilder, constant, root, Locator.getInstance().getEngine().getVarsRegistry(), this)); - root.findViewById(R.id.remove_button).setVisibility(View.GONE); - } else { - // EDIT MODE - getDialog().setTitle(R.string.c_var_edit_var); + if (constant == null) { + // CREATE MODE + getDialog().setTitle(R.string.c_var_create_var); - root.findViewById(R.id.remove_button).setOnClickListener(MathEntityRemover.newConstantRemover(constant, null, getActivity(), VarEditDialogFragment.this)); - } - } + root.findViewById(R.id.remove_button).setVisibility(View.GONE); + } else { + // EDIT MODE + getDialog().setTitle(R.string.c_var_edit_var); - private void fillGreekKeyboard(View root, final EditText editName) { - final TextView greekKeyboardToggle = (TextView) root.findViewById(R.id.var_toggle_greek_keyboard); - final ViewGroup greekKeyboard = (ViewGroup) root.findViewById(R.id.var_greek_keyboard); - greekKeyboardToggle.setPaintFlags(greekKeyboardToggle.getPaintFlags() | UNDERLINE_TEXT_FLAG); - greekKeyboardToggle.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - if (greekKeyboard.getVisibility() == VISIBLE) { - greekKeyboard.setVisibility(GONE); - greekKeyboardToggle.setText(R.string.cpp_var_show_greek_keyboard); - } else { - greekKeyboard.setVisibility(VISIBLE); - greekKeyboardToggle.setText(R.string.cpp_var_hide_greek_keyboard); - } - } - }); - LinearLayout keyboardRow = null; - final View.OnClickListener buttonOnClickListener = new View.OnClickListener() { - @Override - public void onClick(View view) { - if (!(view instanceof Button)) throw new AssertionError(); - editName.append(((Button) view).getText()); - } - }; - for (int i = 0; i < greekAlphabet.length(); i++) { - if (i % 5 == 0) { - keyboardRow = new LinearLayout(getActivity()); - keyboardRow.setOrientation(HORIZONTAL); - greekKeyboard.addView(keyboardRow, new ViewGroup.LayoutParams(MATCH_PARENT, WRAP_CONTENT)); - } - final Button button = new Button(getActivity()); - button.setText(String.valueOf(greekAlphabet.charAt(i))); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { - fixCapitalization(button); - } - button.setOnClickListener(buttonOnClickListener); - assert keyboardRow != null; - keyboardRow.addView(button, new LinearLayout.LayoutParams(0, WRAP_CONTENT, 1F)); - } - final Button button = new Button(getActivity()); - button.setText("↑"); - button.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - final boolean upperCase = button.getText().equals("↑"); - Views.processViewsOfType(greekKeyboard, Button.class, new Views.ViewProcessor