diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..6b5038b --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,29 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + branches: [main] + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + + - name: Set up JDK 21 + uses: actions/setup-java@v4 + with: + java-version: 21 + distribution: temurin + + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v3 + + - name: Grant execute permission for gradlew + run: chmod +x gradlew + + - name: Build and run unit tests + run: ./gradlew assembleDebug test diff --git a/README.md b/README.md index 5f36ee5..a525b1c 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,9 @@ A fully functional calculator app built with Jetpack Compose, following modern A - Clean, Material Design 3 UI built entirely with Jetpack Compose - State managed via ViewModel — survives configuration changes - Supports chained operations and decimal inputs +- Trigonometry function, factorial, square and square root (updated) +- Light and Dark theme is available now! +- Able to keep the expression after calculation and prepare for the upcomming calculation ## 🛠 Tech Stack @@ -29,9 +32,13 @@ A fully functional calculator app built with Jetpack Compose, following modern A ```bash git clone https://github.com/santhoshj001/Jetpack-Compose-Calculator.git ``` -2. Open in **Android Studio Hedgehog** or later -3. Let Gradle sync -4. Run on an emulator or physical device (API 21+) +2. Install JDK 21 +3. Open in **Android Studio Hedgehog** or later +4. Change AGP to 8.2.2 and Gradle to 8.5 +5. ![Uploading image.png…]() + +6. Let Gradle sync +7. Run on an emulator or physical device (API 21+) ## 📄 License diff --git a/app/build.gradle b/app/build.gradle index 7035e9a..0413ded 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -4,12 +4,13 @@ plugins { } android { - compileSdk 32 + namespace 'com.teamb.calculator' + compileSdk 34 defaultConfig { applicationId "com.teamb.calculator" minSdk 31 - targetSdk 32 + targetSdk 34 versionCode 1 versionName "1.0" @@ -36,7 +37,7 @@ android { compose true } composeOptions { - kotlinCompilerExtensionVersion compose_version + kotlinCompilerExtensionVersion "1.5.8" } packagingOptions { resources { @@ -46,19 +47,18 @@ android { } dependencies { - - implementation 'androidx.core:core-ktx:1.7.0' - implementation "androidx.compose.ui:ui:$compose_version" - implementation 'androidx.compose.material3:material3:1.0.0-alpha01' - implementation "androidx.compose.ui:ui-tooling-preview:$compose_version" - implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.3.1' - implementation 'androidx.activity:activity-compose:1.3.1' - implementation 'androidx.lifecycle:lifecycle-viewmodel-compose:2.4.1' - implementation 'androidx.core:core-splashscreen:1.0.0-rc01' + implementation 'androidx.core:core-ktx:1.12.0' + implementation "androidx.compose.ui:ui:1.5.4" + implementation 'androidx.compose.material3:material3:1.1.2' + implementation "androidx.compose.ui:ui-tooling-preview:1.5.4" + implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.6.2' + implementation 'androidx.activity:activity-compose:1.8.2' + implementation 'androidx.lifecycle:lifecycle-viewmodel-compose:2.6.2' + implementation 'androidx.core:core-splashscreen:1.0.1' testImplementation 'junit:junit:4.13.2' - androidTestImplementation 'androidx.test.ext:junit:1.1.3' - androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' - androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version" - debugImplementation "androidx.compose.ui:ui-tooling:$compose_version" - debugImplementation "androidx.compose.ui:ui-test-manifest:$compose_version" -} \ No newline at end of file + androidTestImplementation 'androidx.test.ext:junit:1.1.5' + androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1' + androidTestImplementation "androidx.compose.ui:ui-test-junit4:1.5.4" + debugImplementation "androidx.compose.ui:ui-tooling:1.5.4" + debugImplementation "androidx.compose.ui:ui-test-manifest:1.5.4" +} diff --git a/app/src/androidTest/java/com/teamb/calculator/CalculatorIntegrationTest.kt b/app/src/androidTest/java/com/teamb/calculator/CalculatorIntegrationTest.kt new file mode 100644 index 0000000..347005f --- /dev/null +++ b/app/src/androidTest/java/com/teamb/calculator/CalculatorIntegrationTest.kt @@ -0,0 +1,157 @@ +package com.teamb.calculator + +import androidx.compose.ui.test.* +import androidx.compose.ui.test.junit4.createAndroidComposeRule +import androidx.test.ext.junit.runners.AndroidJUnit4 +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +@RunWith(AndroidJUnit4::class) +class CalculatorIntegrationTest { + + @get:Rule + val composeTestRule = createAndroidComposeRule() + + private fun assertDisplay(expected: String) { + composeTestRule.onNode( + hasText(expected, substring = false), + useUnmergedTree = true + ).assertExists() + } + + @Test + fun basicAddition() { + composeTestRule.onNodeWithText("7").performClick() + composeTestRule.onNodeWithText("+").performClick() + composeTestRule.onNodeWithText("3").performClick() + composeTestRule.onNodeWithText("=").performClick() + assertDisplay("10.0") + } + + @Test + fun pemdas() { + composeTestRule.onNodeWithText("3").performClick() + composeTestRule.onNodeWithText("+").performClick() + composeTestRule.onNodeWithText("4").performClick() + composeTestRule.onNodeWithText("*").performClick() + composeTestRule.onNodeWithText("2").performClick() + composeTestRule.onNodeWithText("-").performClick() + composeTestRule.onNodeWithText("6").performClick() + composeTestRule.onNodeWithText("/").performClick() + composeTestRule.onNodeWithText("3").performClick() + composeTestRule.onNodeWithText("=").performClick() + assertDisplay("9.0") + } + + @Test + fun decimal() { + composeTestRule.onNodeWithText("2").performClick() + composeTestRule.onNodeWithText(".").performClick() + composeTestRule.onNodeWithText("5").performClick() + composeTestRule.onNodeWithText("+").performClick() + composeTestRule.onNodeWithText("3").performClick() + composeTestRule.onNodeWithText("=").performClick() + assertDisplay("5.5") + } + + @Test + fun chainingAfterResult() { + composeTestRule.onNodeWithText("3").performClick() + composeTestRule.onNodeWithText("+").performClick() + composeTestRule.onNodeWithText("4").performClick() + composeTestRule.onNodeWithText("=").performClick() + composeTestRule.onNodeWithText("+").performClick() + composeTestRule.onNodeWithText("5").performClick() + composeTestRule.onNodeWithText("=").performClick() + assertDisplay("12.0") + } + + @Test + fun factorial() { + composeTestRule.onNodeWithContentDescription("Expand", substring = true).performClick() + composeTestRule.onNodeWithText("5").performClick() + composeTestRule.onNodeWithText("!").performClick() + composeTestRule.onNodeWithText("=").performClick() + assertDisplay("120.0") + } + + @Test + fun square() { + composeTestRule.onNodeWithContentDescription("Expand", substring = true).performClick() + composeTestRule.onNodeWithText("5").performClick() + composeTestRule.onNodeWithText("x²").performClick() + composeTestRule.onNodeWithText("=").performClick() + assertDisplay("25.0") + } + + @Test + fun pi() { + composeTestRule.onNodeWithContentDescription("Expand", substring = true).performClick() + composeTestRule.onNodeWithText("π").performClick() + composeTestRule.onNodeWithText("=").performClick() + assertDisplay("3.14159265") + } + + @Test + fun sin() { + composeTestRule.onNodeWithContentDescription("Expand", substring = true).performClick() + composeTestRule.onNodeWithText("sin").performClick() + composeTestRule.onNodeWithText("3").performClick() + composeTestRule.onNodeWithText("0").performClick() + composeTestRule.onNodeWithText(")").performClick() + composeTestRule.onNodeWithText("=").performClick() + assertDisplay("0.5") + } + @Test + fun cos() { + composeTestRule.onNodeWithContentDescription("Expand").performClick() + composeTestRule.onNodeWithText("cos").performClick() + composeTestRule.onNodeWithText("9").performClick() + composeTestRule.onNodeWithText("0").performClick() + composeTestRule.onNodeWithText(")").performClick() + composeTestRule.onNodeWithText("=").performClick() +// composeTestRule.onNodeWithTag("Result").assertTextEquals("0.0") + assertDisplay("0.0") + } + + @Test + fun tan() { + composeTestRule.onNodeWithContentDescription("Expand").performClick() + composeTestRule.onNodeWithText("tan").performClick() + composeTestRule.onNodeWithText("4").performClick() + composeTestRule.onNodeWithText("5").performClick() + composeTestRule.onNodeWithText(")").performClick() + composeTestRule.onNodeWithText("=").performClick() + assertDisplay("1.0") + } + @Test + fun sqrt() { + composeTestRule.onNodeWithContentDescription("Expand", substring = true).performClick() + composeTestRule.onNodeWithText("√").performClick() + composeTestRule.onNodeWithText("9").performClick() + composeTestRule.onNodeWithText(")").performClick() + composeTestRule.onNodeWithText("=").performClick() + assertDisplay("3.0") + } + + @Test + fun factorialInExpression() { + composeTestRule.onNodeWithContentDescription("Expand", substring = true).performClick() + composeTestRule.onNodeWithText("3").performClick() + composeTestRule.onNodeWithText("+").performClick() + composeTestRule.onNodeWithText("4").performClick() + composeTestRule.onNodeWithText("!").performClick() + composeTestRule.onNodeWithText("=").performClick() + assertDisplay("27.0") + } + @Test + fun clear() { + composeTestRule.onNodeWithText("7").performClick() + composeTestRule.onNodeWithText("+").performClick() + composeTestRule.onNodeWithText("3").performClick() + composeTestRule.onNodeWithText("AC").performClick() + assertDisplay("") + } + +} diff --git a/app/src/androidTest/java/com/teamb/calculator/ExampleInstrumentedTest.kt b/app/src/androidTest/java/com/teamb/calculator/ExampleInstrumentedTest.kt deleted file mode 100644 index c5c756e..0000000 --- a/app/src/androidTest/java/com/teamb/calculator/ExampleInstrumentedTest.kt +++ /dev/null @@ -1,24 +0,0 @@ -package com.teamb.calculator - -import androidx.test.platform.app.InstrumentationRegistry -import androidx.test.ext.junit.runners.AndroidJUnit4 - -import org.junit.Test -import org.junit.runner.RunWith - -import org.junit.Assert.* - -/** - * Instrumented test, which will execute on an Android device. - * - * See [testing documentation](http://d.android.com/tools/testing). - */ -@RunWith(AndroidJUnit4::class) -class ExampleInstrumentedTest { - @Test - fun useAppContext() { - // Context of the app under test. - val appContext = InstrumentationRegistry.getInstrumentation().targetContext - assertEquals("com.teamb.calculator", appContext.packageName) - } -} \ No newline at end of file diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 6db9fd7..f85041c 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -1,7 +1,6 @@ + xmlns:tools="http://schemas.android.com/tools"> { + val tokens = mutableListOf() + var i = 0 + while (i < expr.length) { + val c = expr[i] + when { + c.isDigit() || c == '.' -> { + val start = i + while (i < expr.length && (expr[i].isDigit() || expr[i] == '.')) i++ + tokens.add(expr.substring(start, i)) + } + c.isLetter() -> { + val start = i + while (i < expr.length && expr[i].isLetter()) i++ + tokens.add(expr.substring(start, i)) + } + else -> { + tokens.add(c.toString()) + i++ + } + } + } + return tokens + } + + private fun precedence(op: String): Int = when (op) { + "+", "-" -> 1 + "*", "/" -> 2 + else -> 0 + } + + fun infixToPostfix(tokens: List): List { + val output = mutableListOf() + val ops = mutableListOf() + for (token in tokens) { + when { + token.toDoubleOrNull() != null -> output.add(token) + token == "π" -> output.add(token) + token == "(" -> ops.add(token) + token in knownFunctions -> ops.add(token) + token == "!" || token == "²" -> output.add(token) + token == ")" -> { + while (ops.isNotEmpty() && ops.last() != "(") + output.add(ops.removeLast()) + if (ops.isNotEmpty()) ops.removeLast() + if (ops.isNotEmpty() && ops.last() in knownFunctions) + output.add(ops.removeLast()) + } + else -> { + while (ops.isNotEmpty() && ops.last() !in knownFunctions && ops.last() != "(" + && precedence(ops.last()) >= precedence(token)) + output.add(ops.removeLast()) + ops.add(token) + } + } + } + while (ops.isNotEmpty()) output.add(ops.removeLast()) + return output + } + + fun evalPostfix(postfix: List): Double { + val stack = mutableListOf() + for (token in postfix) { + when { + token.toDoubleOrNull() != null -> stack.add(token.toDouble()) + token == "π" -> stack.add(Math.PI) + token == "!" -> { + val n = stack.removeLast().toLong() + if (n < 0 || n > 20) throw IllegalArgumentException() + stack.add((1..n).fold(1L) { acc, i -> acc * i }.toDouble()) + } + token == "²" -> { + val n = stack.removeLast() + stack.add(n * n) + } + token in knownFunctions -> { + val arg = stack.removeLast() + stack.add(when (token) { + "sin" -> Math.sin(Math.toRadians(arg)) + "cos" -> Math.cos(Math.toRadians(arg)) + "tan" -> Math.tan(Math.toRadians(arg)) + "sqrt" -> Math.sqrt(arg) + else -> throw IllegalArgumentException() + }) + } + else -> { + val right = stack.removeLast() + val left = stack.removeLast() + stack.add(when (token) { + "+" -> left + right + "-" -> left - right + "*" -> left * right + "/" -> left / right + else -> throw IllegalArgumentException() + }) + } + } + } + return stack.single() + } +} diff --git a/app/src/main/java/com/teamb/calculator/CalculatorState.kt b/app/src/main/java/com/teamb/calculator/CalculatorState.kt index 7b6ccc3..67172c9 100644 --- a/app/src/main/java/com/teamb/calculator/CalculatorState.kt +++ b/app/src/main/java/com/teamb/calculator/CalculatorState.kt @@ -1,9 +1,7 @@ package com.teamb.calculator -import com.teamb.calculator.action.CalculatorOperation - data class CalculatorState( - val number1: String = "", - val number2: String = "", - val operation: CalculatorOperation? = null + val expression: String = "", + val currentNumber: String = "", + val hasResult: Boolean = false ) diff --git a/app/src/main/java/com/teamb/calculator/CalculatorViewModel.kt b/app/src/main/java/com/teamb/calculator/CalculatorViewModel.kt index 3b18499..aa81b0e 100644 --- a/app/src/main/java/com/teamb/calculator/CalculatorViewModel.kt +++ b/app/src/main/java/com/teamb/calculator/CalculatorViewModel.kt @@ -4,13 +4,8 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel -import androidx.lifecycle.viewModelScope import com.teamb.calculator.action.CalculatorAction import com.teamb.calculator.action.CalculatorOperation -import kotlinx.coroutines.delay -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.asStateFlow -import kotlinx.coroutines.launch class CalculatorViewModel : ViewModel() { @@ -19,74 +14,136 @@ class CalculatorViewModel : ViewModel() { fun onAction(action: CalculatorAction) { when (action) { - CalculatorAction.Calculate -> performCalculation() - CalculatorAction.Clear -> performClear() - CalculatorAction.Decimal -> onDecimal() + CalculatorAction.Calculate -> performCalculate() + CalculatorAction.Clear -> state = CalculatorState() + CalculatorAction.Decimal -> performDecimal() CalculatorAction.Delete -> performDelete() - is CalculatorAction.Number -> onNumber(action.number) - is CalculatorAction.Operation -> onOperation(action.operation) + CalculatorAction.OpenParen -> performOpenParen() + CalculatorAction.CloseParen -> performCloseParen() + CalculatorAction.Factorial -> performFactorial() + CalculatorAction.Pi -> performPi() + CalculatorAction.Sin -> performSin() + CalculatorAction.Cos -> performCos() + CalculatorAction.Tan -> performTan() + CalculatorAction.Sqrt -> performSqrt() + CalculatorAction.Square -> performSquare() + is CalculatorAction.Number -> performNumber(action.number) + is CalculatorAction.Operation -> performOperation(action.operation) } } - private fun onOperation(operation: CalculatorOperation) { - if (state.operation == null && state.number1.isNotBlank()) { - state = state.copy(operation = operation) - } + private fun performNumber(number: Int) { + if (state.hasResult) state = CalculatorState() + state = state.copy(currentNumber = state.currentNumber.plus(number.toString())) } - private fun onNumber(number: Int) { - state = if (state.operation == null) { - state.copy( - number1 = state.number1.plus(number) - ) - } else { - state.copy( - number2 = state.number2.plus(number) + private fun performOperation(op: CalculatorOperation) { + if (state.hasResult) { + state = state.copy( + expression = state.expression + op.operator, + currentNumber = "", + hasResult = false ) + return } + val expr = state.expression + state.currentNumber + val stripped = if (expr.endsWith("+") || expr.endsWith("-") || + expr.endsWith("*") || expr.endsWith("/") + ) expr.dropLast(1) + op.operator else expr + op.operator + state = state.copy(expression = stripped, currentNumber = "") + } + private fun performDecimal() { + if (state.currentNumber.contains(".")) return + state = state.copy( + currentNumber = if (state.currentNumber.isEmpty()) "0." + else state.currentNumber.plus(".") + ) } private fun performDelete() { - if (state.operation == null && state.number1.isNotBlank()) { - state = state.copy(number1 = state.number1.dropLast(1)) - return - } else if (state.number2.isNotBlank()) { - state = state.copy(number2 = state.number2.dropLast(1)) - return - } else { - state = state.copy(operation = null) + when { + state.currentNumber.isNotEmpty() -> + state = state.copy(currentNumber = state.currentNumber.dropLast(1)) + state.expression.isNotEmpty() -> + state = state.copy(expression = state.expression.dropLast(1)) } } - private fun onDecimal() { - if (state.operation == null && state.number1.isNotBlank() && !state.number1.contains(".")) { - state = state.copy(number1 = state.number1.plus(".")) - return - } + private fun performOpenParen() { + state = state.copy( + expression = state.expression + state.currentNumber + "(", + currentNumber = "" + ) + } - if (state.number2.isNotBlank() && !state.number2.contains(".")) { - state = state.copy(number2 = state.number2.plus(".")) - return + private fun performCloseParen() { + state = state.copy( + expression = state.expression + state.currentNumber + ")", + currentNumber = "" + ) + } + + private fun performCalculate() { + val expr = state.expression + state.currentNumber + if (expr.isBlank()) return + val evaluated = evaluate(expr) + if (evaluated != null) { + val rounded = Math.round(evaluated * 1e12) / 1e12 + state = CalculatorState( + expression = rounded.toString().take(10), + hasResult = true + ) } } - private fun performClear() { - state = CalculatorState() + private fun performFactorial() { + if (state.currentNumber.isEmpty() && state.expression.isEmpty()) return + state = state.copy( + expression = state.expression + state.currentNumber + "!", + currentNumber = "" + ) } - private fun performCalculation() { - var num1 = state.number1.toDoubleOrNull() - val num2 = state.number2.toDoubleOrNull() - if (num1 != null && num2 != null && state.operation != null) { - when (state.operation) { - CalculatorOperation.Add -> num1 += num2 - CalculatorOperation.Divide -> num1 /= num2 - CalculatorOperation.Multiply -> num1 *= num2 - CalculatorOperation.Subtract -> num1 -= num2 - null -> num1 = 0.0 - } - } - state = CalculatorState(number1 = num1.toString().take(10)) + private fun performPi() { + state = state.copy(currentNumber = state.currentNumber + "π") + } + + private fun performSin() { + state = state.copy( + expression = state.expression + state.currentNumber + "sin(", + currentNumber = "" + ) + } + + private fun performCos() { + state = state.copy( + expression = state.expression + state.currentNumber + "cos(", + currentNumber = "" + ) + } + + private fun performTan() { + state = state.copy( + expression = state.expression + state.currentNumber + "tan(", + currentNumber = "" + ) + } + + private fun performSqrt() { + state = state.copy( + expression = state.expression + state.currentNumber + "sqrt(", + currentNumber = "" + ) } -} \ No newline at end of file + + private fun performSquare() { + if (state.currentNumber.isEmpty() && state.expression.isEmpty()) return + state = state.copy( + expression = state.expression + state.currentNumber + "²", + currentNumber = "" + ) + } + + private fun evaluate(expr: String): Double? = CalculatorEvaluator.evaluate(expr) +} diff --git a/app/src/main/java/com/teamb/calculator/MainActivity.kt b/app/src/main/java/com/teamb/calculator/MainActivity.kt index 112d780..41a194c 100644 --- a/app/src/main/java/com/teamb/calculator/MainActivity.kt +++ b/app/src/main/java/com/teamb/calculator/MainActivity.kt @@ -5,14 +5,9 @@ import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.viewModels import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.padding -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Surface import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp -import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen import com.teamb.calculator.components.Calculator -import com.teamb.calculator.ui.theme.CalculatorTheme class MainActivity : ComponentActivity() { @@ -21,24 +16,15 @@ class MainActivity : ComponentActivity() { super.onCreate(savedInstanceState) setContent { - CalculatorTheme() { - - val state = viewModel.state - Surface( - modifier = Modifier.fillMaxSize(), - color = MaterialTheme.colorScheme.background - ) { - Calculator( - state = state, modifier = Modifier - .fillMaxSize() - .padding(16.dp), - onAction = viewModel::onAction, - buttonSpacing = 12.dp - ) - } - } + val state = viewModel.state + // Đã chuyển CalculatorTheme và Surface vào bên trong component Calculator + // để quản lý Dark Mode tập trung, tránh lỗi lệch màu nền (khung đen). + Calculator( + state = state, + modifier = Modifier.fillMaxSize(), + onAction = viewModel::onAction, + buttonSpacing = 12.dp + ) } } - - } diff --git a/app/src/main/java/com/teamb/calculator/action/CalculatorAction.kt b/app/src/main/java/com/teamb/calculator/action/CalculatorAction.kt index 5d4175a..116cca9 100644 --- a/app/src/main/java/com/teamb/calculator/action/CalculatorAction.kt +++ b/app/src/main/java/com/teamb/calculator/action/CalculatorAction.kt @@ -5,6 +5,15 @@ sealed class CalculatorAction { object Delete : CalculatorAction() object Decimal : CalculatorAction() object Calculate : CalculatorAction() + object OpenParen : CalculatorAction() + object CloseParen : CalculatorAction() + object Factorial : CalculatorAction() + object Pi : CalculatorAction() + object Sin : CalculatorAction() + object Cos : CalculatorAction() + object Tan : CalculatorAction() + object Sqrt : CalculatorAction() + object Square : CalculatorAction() data class Number(val number: Int) : CalculatorAction() data class Operation(val operation: CalculatorOperation) : CalculatorAction() } diff --git a/app/src/main/java/com/teamb/calculator/action/CalculatorOperation.kt b/app/src/main/java/com/teamb/calculator/action/CalculatorOperation.kt index ca89d64..861f198 100644 --- a/app/src/main/java/com/teamb/calculator/action/CalculatorOperation.kt +++ b/app/src/main/java/com/teamb/calculator/action/CalculatorOperation.kt @@ -3,6 +3,6 @@ package com.teamb.calculator.action sealed class CalculatorOperation(val operator: String) { object Add : CalculatorOperation("+") object Subtract : CalculatorOperation("-") - object Multiply : CalculatorOperation("x") + object Multiply : CalculatorOperation("*") object Divide : CalculatorOperation("/") } diff --git a/app/src/main/java/com/teamb/calculator/components/AdvancedCalculatorPanel.kt b/app/src/main/java/com/teamb/calculator/components/AdvancedCalculatorPanel.kt new file mode 100644 index 0000000..24cfa0d --- /dev/null +++ b/app/src/main/java/com/teamb/calculator/components/AdvancedCalculatorPanel.kt @@ -0,0 +1,83 @@ +package com.teamb.calculator.components + +import androidx.compose.foundation.layout.* +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Star +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.Dp +import com.teamb.calculator.action.CalculatorAction +import com.teamb.calculator.action.CalculatorOperation + +@Composable +fun AdvancedCalculatorPanel( + onAction: (CalculatorAction) -> Unit, + onExpandToggle: () -> Unit, + buttonSpacing: Dp +) { + // Tối ưu hiệu năng: Memoize các callbacks để tránh recomposition các nút bấm + val handleAction = remember(onAction) { { action: CalculatorAction -> onAction(action) } } + val handleExpand = remember(onExpandToggle) { { onExpandToggle() } } + + Column( + modifier = Modifier.fillMaxWidth(), + verticalArrangement = Arrangement.spacedBy(buttonSpacing) + ) { + // Hàng 1: sin, cos, tan, √, x² - Sử dụng weight(1f) đồng nhất để tối ưu Layout CPU + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(buttonSpacing)) { + CalculatorButton(symbol = "sin", modifier = Modifier.aspectRatio(1f).weight(1f)) { handleAction(CalculatorAction.Sin) } + CalculatorButton(symbol = "cos", modifier = Modifier.aspectRatio(1f).weight(1f)) { handleAction(CalculatorAction.Cos) } + CalculatorButton(symbol = "tan", modifier = Modifier.aspectRatio(1f).weight(1f)) { handleAction(CalculatorAction.Tan) } + CalculatorButton(symbol = "√", modifier = Modifier.aspectRatio(1f).weight(1f)) { handleAction(CalculatorAction.Sqrt) } + CalculatorButton(symbol = "x²", modifier = Modifier.aspectRatio(1f).weight(1f)) { handleAction(CalculatorAction.Square) } + } + // Hàng 2: π, (, ), !, / + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(buttonSpacing)) { + CalculatorButton(symbol = "π", modifier = Modifier.aspectRatio(1f).weight(1f)) { handleAction(CalculatorAction.Pi) } + CalculatorButton(symbol = "(", modifier = Modifier.aspectRatio(1f).weight(1f)) { handleAction(CalculatorAction.OpenParen) } + CalculatorButton(symbol = ")", modifier = Modifier.aspectRatio(1f).weight(1f)) { handleAction(CalculatorAction.CloseParen) } + CalculatorButton(symbol = "!", modifier = Modifier.aspectRatio(1f).weight(1f)) { handleAction(CalculatorAction.Factorial) } + CalculatorButton(symbol = "/", modifier = Modifier.aspectRatio(1f).weight(1f)) { + handleAction(CalculatorAction.Operation(CalculatorOperation.Divide)) + } + } + // Hàng 3: 7, 8, 9, AC, Del + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(buttonSpacing)) { + CalculatorButton(symbol = "7", modifier = Modifier.aspectRatio(1f).weight(1f)) { handleAction(CalculatorAction.Number(7)) } + CalculatorButton(symbol = "8", modifier = Modifier.aspectRatio(1f).weight(1f)) { handleAction(CalculatorAction.Number(8)) } + CalculatorButton(symbol = "9", modifier = Modifier.aspectRatio(1f).weight(1f)) { handleAction(CalculatorAction.Number(9)) } + CalculatorButton(symbol = "AC", modifier = Modifier.aspectRatio(1f).weight(1f)) { handleAction(CalculatorAction.Clear) } + CalculatorButton(symbol = "Del", modifier = Modifier.aspectRatio(1f).weight(1f)) { handleAction(CalculatorAction.Delete) } + } + // Hàng 4: 4, 5, 6, *, - + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(buttonSpacing)) { + CalculatorButton(symbol = "4", modifier = Modifier.aspectRatio(1f).weight(1f)) { handleAction(CalculatorAction.Number(4)) } + CalculatorButton(symbol = "5", modifier = Modifier.aspectRatio(1f).weight(1f)) { handleAction(CalculatorAction.Number(5)) } + CalculatorButton(symbol = "6", modifier = Modifier.aspectRatio(1f).weight(1f)) { handleAction(CalculatorAction.Number(6)) } + CalculatorButton(symbol = "*", modifier = Modifier.aspectRatio(1f).weight(1f)) { + handleAction(CalculatorAction.Operation(CalculatorOperation.Multiply)) + } + CalculatorButton(symbol = "-", modifier = Modifier.aspectRatio(1f).weight(1f)) { + handleAction(CalculatorAction.Operation(CalculatorOperation.Subtract)) + } + } + // Hàng 5: 1, 2, 3, +, = + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(buttonSpacing)) { + CalculatorButton(symbol = "1", modifier = Modifier.aspectRatio(1f).weight(1f)) { handleAction(CalculatorAction.Number(1)) } + CalculatorButton(symbol = "2", modifier = Modifier.aspectRatio(1f).weight(1f)) { handleAction(CalculatorAction.Number(2)) } + CalculatorButton(symbol = "3", modifier = Modifier.aspectRatio(1f).weight(1f)) { handleAction(CalculatorAction.Number(3)) } + CalculatorButton(symbol = "+", modifier = Modifier.aspectRatio(1f).weight(1f)) { + handleAction(CalculatorAction.Operation(CalculatorOperation.Add)) + } + CalculatorButton(symbol = "=", modifier = Modifier.aspectRatio(1f).weight(1f)) { handleAction(CalculatorAction.Calculate) } + } + // Hàng 6: [ICON], 0, ., (Trống), (Trống) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(buttonSpacing)) { + CalculatorButton(icon = Icons.Default.Star, modifier = Modifier.aspectRatio(1f).weight(1f), contentDescription = "Expand") { handleExpand() } + CalculatorButton(symbol = "0", modifier = Modifier.aspectRatio(1f).weight(1f)) { handleAction(CalculatorAction.Number(0)) } + CalculatorButton(symbol = ".", modifier = Modifier.aspectRatio(1f).weight(1f)) { handleAction(CalculatorAction.Decimal) } + Spacer(modifier = Modifier.weight(2f)) + } + } +} diff --git a/app/src/main/java/com/teamb/calculator/components/Calculator.kt b/app/src/main/java/com/teamb/calculator/components/Calculator.kt index f0582f4..c3e8ce8 100644 --- a/app/src/main/java/com/teamb/calculator/components/Calculator.kt +++ b/app/src/main/java/com/teamb/calculator/components/Calculator.kt @@ -1,17 +1,28 @@ package com.teamb.calculator.components +import androidx.compose.animation.AnimatedContent +import androidx.compose.animation.core.tween +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.togetherWith +import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.* -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Settings +import androidx.compose.material.icons.filled.Star +import androidx.compose.material3.* +import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.testTag import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import com.teamb.calculator.CalculatorState import com.teamb.calculator.action.CalculatorAction import com.teamb.calculator.action.CalculatorOperation +import com.teamb.calculator.ui.theme.CalculatorTheme @Composable fun Calculator( @@ -20,172 +31,150 @@ fun Calculator( buttonSpacing: Dp = 8.dp, onAction: (CalculatorAction) -> Unit ) { - Box(modifier = modifier) { - Column( - Modifier - .fillMaxWidth() - .align(Alignment.BottomCenter), - verticalArrangement = Arrangement.spacedBy(buttonSpacing) - ) { + var isExpanded by remember { mutableStateOf(false) } + var isDarkMode by remember { mutableStateOf(false) } + val systemInDark = isSystemInDarkTheme() + + LaunchedEffect(Unit) { + isDarkMode = systemInDark + } - Text( - text = state.number1 + state.operation?.operator.orEmpty() + state.number2, - style = MaterialTheme.typography.displayLarge, - maxLines = 3, - modifier = Modifier - .fillMaxWidth() - .padding(vertical = 32.dp), - textAlign = TextAlign.End, - color = MaterialTheme.colorScheme.onBackground - ) + // Tối ưu hiệu năng: Memoize callbacks để tránh recomposition các nút bấm + val handleAction = remember(onAction) { { action: CalculatorAction -> onAction(action) } } + val toggleExpand = remember { { isExpanded = !isExpanded } } - Row( - Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.spacedBy(buttonSpacing) - ) { - CalculatorButton( - symbol = "AC", - modifier = Modifier - .aspectRatio(2f) - .weight(2f) + CalculatorTheme(darkTheme = isDarkMode) { + Surface( + modifier = modifier.fillMaxSize(), + color = MaterialTheme.colorScheme.background + ) { + Box(modifier = Modifier.fillMaxSize().padding(16.dp)) { + var showMenu by remember { mutableStateOf(false) } + + Row( + modifier = Modifier.fillMaxWidth().align(Alignment.TopStart), + horizontalArrangement = Arrangement.Start ) { - onAction(CalculatorAction.Clear) + Box { + IconButton(onClick = { showMenu = true }) { + Icon( + imageVector = Icons.Default.Settings, + contentDescription = "Settings", + tint = MaterialTheme.colorScheme.onBackground + ) + } + DropdownMenu( + expanded = showMenu, + onDismissRequest = { showMenu = false } + ) { + DropdownMenuItem( + text = { + Row(verticalAlignment = Alignment.CenterVertically) { + Text("Giao diện Tối") + Spacer(Modifier.width(8.dp)) + Switch( + checked = isDarkMode, + onCheckedChange = { isDarkMode = it } + ) + } + }, + onClick = { } + ) + DropdownMenuItem( + text = { Text("Lịch sử tính toán") }, + onClick = { showMenu = false } + ) + } + } } - CalculatorButton( - symbol = "Del", - modifier = Modifier - .aspectRatio(2f) - .weight(2f) - ) { onAction(CalculatorAction.Delete) } - CalculatorButton( - symbol = "/", - modifier = Modifier - .aspectRatio(1f) - .weight(1f) - ) { onAction(CalculatorAction.Operation(CalculatorOperation.Divide)) } - } - - Row( - Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.spacedBy(buttonSpacing) - ) { - - CalculatorButton( - symbol = "7", - modifier = Modifier - .aspectRatio(1f) - .weight(1f) - ) { onAction(CalculatorAction.Number(7)) } - CalculatorButton( - symbol = "8", - modifier = Modifier - .aspectRatio(1f) - .weight(1f) - ) { onAction(CalculatorAction.Number(8)) } - CalculatorButton( - symbol = "9", - modifier = Modifier - .aspectRatio(1f) - .weight(1f) - ) { onAction(CalculatorAction.Number(9)) } - CalculatorButton( - symbol = "*", - modifier = Modifier - .aspectRatio(1f) - .weight(1f) - ) { onAction(CalculatorAction.Operation(CalculatorOperation.Multiply)) } - } - - - Row( - Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.spacedBy(buttonSpacing) - ) { - - CalculatorButton( - symbol = "4", - modifier = Modifier - .aspectRatio(1f) - .weight(1f) - ) { onAction(CalculatorAction.Number(4)) } - CalculatorButton( - symbol = "5", - modifier = Modifier - .aspectRatio(1f) - .weight(1f) - ) { onAction(CalculatorAction.Number(5)) } - CalculatorButton( - symbol = "6", - modifier = Modifier - .aspectRatio(1f) - .weight(1f) - ) { onAction(CalculatorAction.Number(6)) } - CalculatorButton( - symbol = "-", - modifier = Modifier - .aspectRatio(1f) - .weight(1f) - ) { onAction(CalculatorAction.Operation(CalculatorOperation.Subtract)) } - } - - - Row( - Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.spacedBy(buttonSpacing) - ) { - - CalculatorButton( - symbol = "1", - modifier = Modifier - .aspectRatio(1f) - .weight(1f) - ) { onAction(CalculatorAction.Number(1)) } - CalculatorButton( - symbol = "2", - modifier = Modifier - .aspectRatio(1f) - .weight(1f) - ) { onAction(CalculatorAction.Number(2)) } - CalculatorButton( - symbol = "3", - modifier = Modifier - .aspectRatio(1f) - .weight(1f) - ) { onAction(CalculatorAction.Number(3)) } - CalculatorButton( - symbol = "+", - modifier = Modifier - .aspectRatio(1f) - .weight(1f) - ) { onAction(CalculatorAction.Operation(CalculatorOperation.Add)) } + Column( + Modifier + .fillMaxWidth() + .align(Alignment.BottomCenter), + verticalArrangement = Arrangement.spacedBy(buttonSpacing) + ) { + Text( + text = state.expression + state.currentNumber, + style = MaterialTheme.typography.displayLarge, + maxLines = 3, + modifier = Modifier + .fillMaxWidth() + .padding(vertical = 32.dp) + .semantics { testTag = "Result" }, + textAlign = TextAlign.End, + color = MaterialTheme.colorScheme.onBackground + ) + + AnimatedContent( + targetState = isExpanded, + transitionSpec = { + fadeIn(animationSpec = tween(300)) togetherWith + fadeOut(animationSpec = tween(300)) + }, + label = "LayoutSwitch" + ) { expanded -> + Surface( + color = MaterialTheme.colorScheme.background, + modifier = Modifier.fillMaxWidth() + ) { + if (expanded) { + AdvancedCalculatorPanel( + onAction = handleAction, + onExpandToggle = toggleExpand, + buttonSpacing = buttonSpacing + ) + } else { + StandardPanel( + onAction = handleAction, + onExpandToggle = toggleExpand, + buttonSpacing = buttonSpacing + ) + } + } + } + } } + } + } +} - - Row( - Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.spacedBy(buttonSpacing) - ) { - CalculatorButton( - symbol = "0", - modifier = Modifier - .aspectRatio(2f) - .weight(2f) - ) { onAction(CalculatorAction.Number(0)) } - - CalculatorButton( - symbol = ".", - modifier = Modifier - .aspectRatio(1f) - .weight(1f) - ) { onAction(CalculatorAction.Decimal) } - CalculatorButton( - symbol = "=", - modifier = Modifier - .aspectRatio(1f) - .weight(1f) - ) { onAction(CalculatorAction.Calculate) } - } +@Composable +fun StandardPanel( + onAction: (CalculatorAction) -> Unit, + onExpandToggle: () -> Unit, + buttonSpacing: Dp +) { + Column(verticalArrangement = Arrangement.spacedBy(buttonSpacing)) { + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(buttonSpacing)) { + CalculatorButton(symbol = "AC", modifier = Modifier.aspectRatio(1f).weight(1f)) { onAction(CalculatorAction.Clear) } + CalculatorButton(symbol = "Del", modifier = Modifier.aspectRatio(1f).weight(1f)) { onAction(CalculatorAction.Delete) } + CalculatorButton(icon = Icons.Default.Star, modifier = Modifier.aspectRatio(1f).weight(1f), contentDescription = "Expand") { onExpandToggle() } + CalculatorButton(symbol = "/", modifier = Modifier.aspectRatio(1f).weight(1f)) { onAction(CalculatorAction.Operation(CalculatorOperation.Divide)) } + } + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(buttonSpacing)) { + CalculatorButton(symbol = "7", modifier = Modifier.aspectRatio(1f).weight(1f)) { onAction(CalculatorAction.Number(7)) } + CalculatorButton(symbol = "8", modifier = Modifier.aspectRatio(1f).weight(1f)) { onAction(CalculatorAction.Number(8)) } + CalculatorButton(symbol = "9", modifier = Modifier.aspectRatio(1f).weight(1f)) { onAction(CalculatorAction.Number(9)) } + CalculatorButton(symbol = "*", modifier = Modifier.aspectRatio(1f).weight(1f)) { onAction(CalculatorAction.Operation(CalculatorOperation.Multiply)) } + } + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(buttonSpacing)) { + CalculatorButton(symbol = "4", modifier = Modifier.aspectRatio(1f).weight(1f)) { onAction(CalculatorAction.Number(4)) } + CalculatorButton(symbol = "5", modifier = Modifier.aspectRatio(1f).weight(1f)) { onAction(CalculatorAction.Number(5)) } + CalculatorButton(symbol = "6", modifier = Modifier.aspectRatio(1f).weight(1f)) { onAction(CalculatorAction.Number(6)) } + CalculatorButton(symbol = "-", modifier = Modifier.aspectRatio(1f).weight(1f)) { onAction(CalculatorAction.Operation(CalculatorOperation.Subtract)) } + } + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(buttonSpacing)) { + CalculatorButton(symbol = "1", modifier = Modifier.aspectRatio(1f).weight(1f)) { onAction(CalculatorAction.Number(1)) } + CalculatorButton(symbol = "2", modifier = Modifier.aspectRatio(1f).weight(1f)) { onAction(CalculatorAction.Number(2)) } + CalculatorButton(symbol = "3", modifier = Modifier.aspectRatio(1f).weight(1f)) { onAction(CalculatorAction.Number(3)) } + CalculatorButton(symbol = "+", modifier = Modifier.aspectRatio(1f).weight(1f)) { onAction(CalculatorAction.Operation(CalculatorOperation.Add)) } + } + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(buttonSpacing)) { + CalculatorButton(symbol = "0", modifier = Modifier.aspectRatio(1f).weight(1f)) { onAction(CalculatorAction.Number(0)) } + CalculatorButton(symbol = ".", modifier = Modifier.aspectRatio(1f).weight(1f)) { onAction(CalculatorAction.Decimal) } + CalculatorButton(symbol = "=", modifier = Modifier.aspectRatio(1f).weight(1f)) { onAction(CalculatorAction.Calculate) } + Spacer(Modifier.weight(1f)) } } -} \ No newline at end of file +} diff --git a/app/src/main/java/com/teamb/calculator/components/CalculatorButton.kt b/app/src/main/java/com/teamb/calculator/components/CalculatorButton.kt index 8265cdf..12830b6 100644 --- a/app/src/main/java/com/teamb/calculator/components/CalculatorButton.kt +++ b/app/src/main/java/com/teamb/calculator/components/CalculatorButton.kt @@ -1,30 +1,58 @@ package com.teamb.calculator.components +import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.shape.CircleShape -import androidx.compose.material3.ElevatedButton -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Text +import androidx.compose.material3.* import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.hapticfeedback.HapticFeedbackType import androidx.compose.ui.platform.LocalHapticFeedback +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp @Composable fun CalculatorButton( - symbol: String, + symbol: String? = null, + icon: ImageVector? = null, modifier: Modifier, + contentDescription: String? = null, onClick: () -> Unit ) { val haptic = LocalHapticFeedback.current - ElevatedButton( + + // Sử dụng FilledTonalButton thay cho ElevatedButton để tối ưu GPU (không đổ bóng) + FilledTonalButton( modifier = modifier, onClick = { - haptic.performHapticFeedback(HapticFeedbackType.LongPress) + // Sử dụng TextHandleMove cho cảm giác rung nhẹ và nhạy hơn trên máy cấu hình thấp + haptic.performHapticFeedback(HapticFeedbackType.TextHandleMove) onClick() }, - shape = CircleShape + shape = CircleShape, + colors = ButtonDefaults.filledTonalButtonColors( + containerColor = MaterialTheme.colorScheme.secondaryContainer, + contentColor = MaterialTheme.colorScheme.onSecondaryContainer + ), + contentPadding = PaddingValues(0.dp) ) { - Text(text = symbol, style = MaterialTheme.typography.displaySmall) + if (icon != null) { + Icon( + imageVector = icon, + contentDescription = contentDescription, + tint = MaterialTheme.colorScheme.onSecondaryContainer + ) + } else if (symbol != null) { + Text( + text = symbol, + style = MaterialTheme.typography.displaySmall.copy( + fontSize = if (symbol.length > 2) 16.sp else 24.sp + ), + maxLines = 1, + softWrap = false, + textAlign = TextAlign.Center + ) + } } } - diff --git a/app/src/test/java/com/teamb/calculator/CalculatorEvaluatorTest.kt b/app/src/test/java/com/teamb/calculator/CalculatorEvaluatorTest.kt new file mode 100644 index 0000000..7c19d26 --- /dev/null +++ b/app/src/test/java/com/teamb/calculator/CalculatorEvaluatorTest.kt @@ -0,0 +1,220 @@ +package com.teamb.calculator + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class CalculatorEvaluatorTest { + + private fun assertEval(expected: Double, expr: String, delta: Double = 1e-10) { + assertEquals(expected, CalculatorEvaluator.evaluate(expr)!!, delta) + } + + @Test + fun addition() { + assertEval(5.0, "2+3") + } + + @Test + fun subtraction() { + assertEval(1.0, "3-2") + } + + @Test + fun multiplication() { + assertEval(6.0, "2*3") + } + + @Test + fun division() { + assertEval(2.0, "6/3") + } + + @Test + fun pemdas() { + assertEval(9.0, "3+4*2-6/3") + } + + @Test + fun parentheses() { + assertEval(14.0, "(3+4)*2") + } + + @Test + fun nestedParentheses() { + assertEval(18.0, "((3+4)*2)+4") + } + + @Test + fun decimal() { + assertEval(5.5, "2.5+3") + } + + @Test + fun divisionByZeroReturnsInfinity() { + assertEquals(Double.POSITIVE_INFINITY, CalculatorEvaluator.evaluate("1/0")!!, 0.0) + } + + @Test + fun factorial() { + assertEval(120.0, "5!") + } + + @Test + fun factorialOfZero() { + assertEval(1.0, "0!") + } + + @Test + fun factorialNegativeReturnsNull() { + assertNull(CalculatorEvaluator.evaluate("-3!")) + } + + @Test + fun factorialTooLargeReturnsNull() { + assertNull(CalculatorEvaluator.evaluate("21!")) + } + + @Test + fun factorialInExpression() { + assertEval(27.0, "3+4!") + } + + @Test + fun pi() { + assertEval(Math.PI, "π") + } + + @Test + fun piInExpression() { + assertEval(Math.PI + 1, "π+1") + } + + @Test + fun square() { + assertEval(25.0, "5²") + } + + @Test + fun squareOfZero() { + assertEval(0.0, "0²") + } + + @Test + fun squareInExpression() { + assertEval(29.0, "4+5²") + } + + @Test + fun sin() { + assertEval(0.5, "sin(30)") + } + + @Test + fun sinOfZero() { + assertEval(0.0, "sin(0)") + } + + @Test + fun cos() { + assertEval(0.0, "cos(90)") + } + + @Test + fun cosOfZero() { + assertEval(1.0, "cos(0)") + } + + @Test + fun tan() { + assertEval(1.0, "tan(45)") + } + + @Test + fun tanOfZero() { + assertEval(0.0, "tan(0)") + } + + @Test + fun sqrt() { + assertEval(3.0, "sqrt(9)") + } + + @Test + fun sqrtOfZero() { + assertEval(0.0, "sqrt(0)") + } + + @Test + fun sqrtInExpression() { + assertEval(7.0, "4+sqrt(9)") + } + + @Test + fun sinInExpression() { + assertEval(3.5, "3+sin(30)") + } + + @Test + fun combinedOperators() { + assertEval(131.0, "4+5!+sqrt(9)+2²") + } + + @Test + fun factorialPemdas() { + assertEval(74.0, "2+3*4!") + } + + @Test + fun malformedExpression() { + assertNull(CalculatorEvaluator.evaluate("++")) + } + + @Test + fun emptyExpression() { + assertNull(CalculatorEvaluator.evaluate("")) + } + + @Test + fun tokenizeSimple() { + assertEquals(listOf("3", "+", "4"), CalculatorEvaluator.tokenize("3+4")) + } + + @Test + fun tokenizeWithParens() { + assertEquals(listOf("(", "3", "+", "4", ")"), CalculatorEvaluator.tokenize("(3+4)")) + } + + @Test + fun tokenizeWithFunction() { + assertEquals(listOf("sin", "(", "30", ")"), CalculatorEvaluator.tokenize("sin(30)")) + } + + @Test + fun tokenizeWithPi() { + assertEquals(listOf("π"), CalculatorEvaluator.tokenize("π")) + } + + @Test + fun tokenizeWithSquare() { + assertEquals(listOf("5", "²"), CalculatorEvaluator.tokenize("5²")) + } + + @Test + fun tokenizeWithFactorial() { + assertEquals(listOf("5", "!"), CalculatorEvaluator.tokenize("5!")) + } + + @Test + fun tokenizeDecimal() { + assertEquals(listOf("3.5"), CalculatorEvaluator.tokenize("3.5")) + } + + @Test + fun tokenizeComplex() { + assertEquals( + listOf("4", "+", "5", "!", "+", "sqrt", "(", "9", ")", "+", "2", "²"), + CalculatorEvaluator.tokenize("4+5!+sqrt(9)+2²") + ) + } +} diff --git a/app/src/test/java/com/teamb/calculator/ExampleUnitTest.kt b/app/src/test/java/com/teamb/calculator/ExampleUnitTest.kt deleted file mode 100644 index 7cc41d6..0000000 --- a/app/src/test/java/com/teamb/calculator/ExampleUnitTest.kt +++ /dev/null @@ -1,17 +0,0 @@ -package com.teamb.calculator - -import org.junit.Test - -import org.junit.Assert.* - -/** - * Example local unit test, which will execute on the development machine (host). - * - * See [testing documentation](http://d.android.com/tools/testing). - */ -class ExampleUnitTest { - @Test - fun addition_isCorrect() { - assertEquals(4, 2 + 2) - } -} \ No newline at end of file diff --git a/build.gradle b/build.gradle index 897f831..709fd31 100644 --- a/build.gradle +++ b/build.gradle @@ -1,14 +1,10 @@ -buildscript { - ext { - compose_version = '1.1.0-beta01' - } -}// Top-level build file where you can add configuration options common to all sub-projects/modules. +// Top-level build file where you can add configuration options common to all sub-projects/modules. plugins { - id 'com.android.application' version '7.2.0' apply false - id 'com.android.library' version '7.2.0' apply false - id 'org.jetbrains.kotlin.android' version '1.5.31' apply false + id 'com.android.application' version '8.2.2' apply false + id 'com.android.library' version '8.2.2' apply false + id 'org.jetbrains.kotlin.android' version '1.9.22' apply false } task clean(type: Delete) { delete rootProject.buildDir -} \ No newline at end of file +} diff --git a/gradle.properties b/gradle.properties index cd0519b..3c7a8bd 100644 --- a/gradle.properties +++ b/gradle.properties @@ -20,4 +20,4 @@ kotlin.code.style=official # Enables namespacing of each library's R class so that its R class includes only the # resources declared in the library itself and none from the library's dependencies, # thereby reducing the size of the R class for that library -android.nonTransitiveRClass=true \ No newline at end of file +android.nonTransitiveRClass=true diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index e708b1c..d64cd49 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index e8f94be..1af9e09 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,7 @@ -#Mon May 23 20:28:52 IST 2022 distributionBase=GRADLE_USER_HOME -distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-bin.zip distributionPath=wrapper/dists -zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip +networkTimeout=10000 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index 4f906e0..1aa94a4 100755 --- a/gradlew +++ b/gradlew @@ -1,7 +1,7 @@ -#!/usr/bin/env sh +#!/bin/sh # -# Copyright 2015 the original author or authors. +# Copyright © 2015-2021 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -17,67 +17,99 @@ # ############################################################################## -## -## Gradle start up script for UN*X -## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# ############################################################################## # Attempt to set APP_HOME + # Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" +MAX_FD=maximum warn () { echo "$*" -} +} >&2 die () { echo echo "$*" echo exit 1 -} +} >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar @@ -87,9 +119,9 @@ CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACMD=$JAVA_HOME/jre/sh/java else - JAVACMD="$JAVA_HOME/bin/java" + JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME @@ -98,88 +130,120 @@ Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else - JAVACMD="java" - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." + fi fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac fi -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. # For Cygwin or MSYS, switch paths to Windows format before running java -if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) fi - i=`expr $i + 1` + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg done - case $i in - 0) set -- ;; - 1) set -- "$args0" ;; - 2) set -- "$args0" "$args1" ;; - 3) set -- "$args0" "$args1" "$args2" ;; - 4) set -- "$args0" "$args1" "$args2" "$args3" ;; - 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac fi -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=`save "$@"` -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat index 107acd3..93e3f59 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -14,7 +14,7 @@ @rem limitations under the License. @rem -@if "%DEBUG%" == "" @echo off +@if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @@ -25,7 +25,8 @@ if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @@ -40,7 +41,7 @@ if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute +if %ERRORLEVEL% equ 0 goto execute echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. @@ -75,13 +76,15 @@ set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar :end @rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd +if %ERRORLEVEL% equ 0 goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% :mainEnd if "%OS%"=="Windows_NT" endlocal