diff --git a/.github/workflows/test-build.yml b/.github/workflows/test-build.yml
new file mode 100644
index 0000000..b346ab7
--- /dev/null
+++ b/.github/workflows/test-build.yml
@@ -0,0 +1,52 @@
+name: Test build
+
+# Builds a "Numio Test" APK for trying changes on a phone before a release.
+# It installs next to the real Numio (different app id), so nothing gets replaced.
+# Release APKs are still built and signed by hand, not here.
+
+on:
+ push:
+ branches-ignore: [main]
+ pull_request:
+ workflow_dispatch:
+
+jobs:
+ build:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: actions/setup-java@v4
+ with:
+ distribution: temurin
+ java-version: 21
+
+ - uses: gradle/actions/setup-gradle@v4
+
+ # Only changes the copy on this build machine, never the repo:
+ # app id com.rr.numio.test and the name "Numio Test".
+ - name: Make it a test app
+ run: |
+ sed -i 's/applicationId = "com.rr.numio"/applicationId = "com.rr.numio.test"/' app/build.gradle.kts
+ sed -i 's#Numio#Numio Test#' app/src/main/res/values/strings.xml
+ grep -n 'applicationId' app/build.gradle.kts
+ grep -n 'app_name' app/src/main/res/values/strings.xml
+
+ - name: Run unit tests
+ run: ./gradlew testDebugUnitTest --stacktrace
+
+ - name: Build test APK
+ run: ./gradlew assembleDebug --stacktrace
+
+ - name: Check no internet permission
+ run: |
+ AAPT=$(ls $ANDROID_HOME/build-tools/*/aapt | tail -1)
+ if $AAPT dump permissions app/build/outputs/apk/debug/app-debug.apk | grep -q 'android.permission.INTERNET'; then
+ echo "INTERNET permission found - Numio must stay offline"; exit 1
+ fi
+ echo "No INTERNET permission"
+
+ - uses: actions/upload-artifact@v4
+ with:
+ name: NumioTest-${{ github.sha }}
+ path: app/build/outputs/apk/debug/app-debug.apk
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index 8b697ae..e1c4d2e 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -17,8 +17,8 @@ android {
applicationId = "com.rr.numio"
minSdk = 24
targetSdk = 36
- versionCode = 8
- versionName = "1.0.7"
+ versionCode = 9
+ versionName = "1.0.8"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
diff --git a/app/src/main/java/com/rr/numio/ui.CalculatorScreen.kt b/app/src/main/java/com/rr/numio/ui.CalculatorScreen.kt
index 5427eac..c66bb4b 100644
--- a/app/src/main/java/com/rr/numio/ui.CalculatorScreen.kt
+++ b/app/src/main/java/com/rr/numio/ui.CalculatorScreen.kt
@@ -21,7 +21,15 @@ import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
+import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.ui.draw.clip
+import androidx.compose.ui.draw.drawWithContent
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.input.pointer.pointerInput
+import androidx.compose.ui.text.SpanStyle
+import androidx.compose.ui.text.TextLayoutResult
+import androidx.compose.ui.text.buildAnnotatedString
+import androidx.compose.ui.text.withStyle
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
@@ -34,7 +42,7 @@ import androidx.lifecycle.viewmodel.compose.viewModel
import com.rr.numio.data.HistoryEntity
import kotlinx.coroutines.delay
-enum class KeyType { NUM, OP, BACKSPACE, CLEAR_ALL, EQUAL }
+enum class KeyType { NUM, OP, BACKSPACE, CLEAR_ALL, EQUAL, BRACKET }
private val NumioBg = Color(0xFF1B1917)
private val NumioSurface = Color(0xFF3A3733)
@@ -65,7 +73,7 @@ fun CalculatorScreen(
var lastTapTime by remember { mutableLongStateOf(0L) }
val keys = listOf(
- listOf("AC" to KeyType.CLEAR_ALL, "C" to KeyType.BACKSPACE, "%" to KeyType.OP, "÷" to KeyType.OP),
+ listOf("AC" to KeyType.CLEAR_ALL, "C" to KeyType.BACKSPACE, "()" to KeyType.BRACKET, "%" to KeyType.OP, "÷" to KeyType.OP),
listOf("7" to KeyType.NUM, "8" to KeyType.NUM, "9" to KeyType.NUM, "×" to KeyType.OP),
listOf("4" to KeyType.NUM, "5" to KeyType.NUM, "6" to KeyType.NUM, "-" to KeyType.OP),
listOf("1" to KeyType.NUM, "2" to KeyType.NUM, "3" to KeyType.NUM, "+" to KeyType.OP)
@@ -154,130 +162,61 @@ fun CalculatorScreen(
}
}
- // Display card — takes all space the keypad doesn't use
+ // Landscape: display on the left, keypad on the right. Stacking them left the
+ // display so short that big system fonts (150%) squeezed the result out of view.
BoxWithConstraints(
modifier = Modifier
.weight(1f)
.fillMaxWidth()
- .padding(vertical = 12.dp)
- .clip(RoundedCornerShape(28.dp))
- .background(Color(0xFF0E0D0C))
- .padding(horizontal = 20.dp, vertical = 16.dp),
- contentAlignment = Alignment.BottomEnd
) {
- // In landscape the card is short: shrink both lines to fit, so the result is never
- // pushed out of view. fontScale keeps this right with bigger system fonts too.
- val fontScale = LocalDensity.current.fontScale
- val fitSp = ((maxHeight.value - 20f) / fontScale).coerceAtLeast(20f) // 20dp: gap + underline
- val exprSize = minOf(48f, fitSp * 0.30f).sp
- val resultSize = minOf(resultFontSize(uiState.result.length).value, fitSp * 0.36f).sp
- Column(
- horizontalAlignment = Alignment.End,
- modifier = Modifier.fillMaxWidth()
- ) {
- val exprScrollState = rememberScrollState()
- LaunchedEffect(uiState.expression) {
- exprScrollState.animateScrollTo(exprScrollState.maxValue)
- }
- // Expression — bigger and right-aligned
- Text(
- text = uiState.expression.ifEmpty { "0" },
- fontSize = exprSize,
- textAlign = TextAlign.End,
- maxLines = 1,
- overflow = TextOverflow.Clip,
- color = Color(0xFFCCBF8A),
- modifier = Modifier
- .fillMaxWidth()
- .horizontalScroll(exprScrollState)
- )
- if (uiState.result.isNotEmpty()) {
- Spacer(modifier = Modifier.height(4.dp))
- // Result — right-aligned, shrinks for long numbers
- Text(
- text = uiState.result,
- fontSize = resultSize,
- fontWeight = FontWeight.Light,
- textAlign = TextAlign.End,
- maxLines = 1,
- overflow = TextOverflow.Ellipsis,
- color = NumioTextOnDark,
- modifier = Modifier.fillMaxWidth()
+ if (maxWidth > maxHeight) {
+ Row(
+ modifier = Modifier.fillMaxSize(),
+ horizontalArrangement = Arrangement.spacedBy(16.dp)
+ ) {
+ CalcDisplay(
+ expression = uiState.expression,
+ result = uiState.result,
+ cursor = uiState.cursor,
+ showCursor = uiState.showCursor,
+ onTapExpression = { viewModel.moveCursor(it) },
+ accentLight = accentLight,
+ modifier = Modifier
+ .weight(1f)
+ .fillMaxHeight()
)
- }
- Box(
- modifier = Modifier
- .padding(top = 10.dp)
- .fillMaxWidth()
- .height(2.dp)
- .background(accentLight)
- )
- }
- }
-
- // Keypad — perfectly round keys
- BoxWithConstraints(
- modifier = Modifier
- .fillMaxWidth()
- .padding(bottom = 16.dp)
- ) {
- val gap = 12.dp
- // Size keys by width, but cap by height so landscape still fits
- val byWidth = (maxWidth - gap * 3) / 4
- val byHeight = (maxHeight * 0.65f - gap * 4) / 5
- val keySize = minOf(byWidth, byHeight)
- // Smaller keys (landscape) get smaller labels, so "AC" and "⌫" aren't clipped
- val labelScale = (keySize / 80.dp).coerceIn(0.45f, 1f)
-
- Column(
- verticalArrangement = Arrangement.spacedBy(gap),
- modifier = Modifier.align(Alignment.Center)
- ) {
- keys.forEach { row ->
- Row(horizontalArrangement = Arrangement.spacedBy(gap)) {
- row.forEach { (label, type) ->
- CircleKey(
- label = label,
- type = type,
- accent = accent,
- accentLight = NumioYellowLight,
- labelScale = labelScale,
- modifier = Modifier.size(keySize),
- onClick = { viewModel.onKeyPress(label) }
- )
- }
- }
- }
- Row(horizontalArrangement = Arrangement.spacedBy(gap)) {
- CircleKey(
- label = "0",
- type = KeyType.NUM,
+ CalcKeypad(
+ keys = keys,
accent = accent,
accentLight = NumioYellowLight,
- labelScale = labelScale,
+ heightShare = 1f,
+ onKey = { viewModel.onKeyPress(it) },
modifier = Modifier
- .width(keySize * 2 + gap)
- .height(keySize),
- shape = RoundedCornerShape(999.dp),
- onClick = { viewModel.onKeyPress("0") }
+ .weight(1f)
+ .fillMaxHeight()
)
- CircleKey(
- label = ".",
- type = KeyType.NUM,
- accent = accent,
- accentLight = NumioYellowLight,
- labelScale = labelScale,
- modifier = Modifier.size(keySize),
- onClick = { viewModel.onKeyPress(".") }
+ }
+ } else {
+ Column(modifier = Modifier.fillMaxSize()) {
+ // Display card — takes all space the keypad doesn't use
+ CalcDisplay(
+ expression = uiState.expression,
+ result = uiState.result,
+ cursor = uiState.cursor,
+ showCursor = uiState.showCursor,
+ onTapExpression = { viewModel.moveCursor(it) },
+ accentLight = accentLight,
+ modifier = Modifier
+ .weight(1f)
+ .fillMaxWidth()
)
- CircleKey(
- label = "=",
- type = KeyType.EQUAL,
+ CalcKeypad(
+ keys = keys,
accent = accent,
accentLight = NumioYellowLight,
- labelScale = labelScale,
- modifier = Modifier.size(keySize),
- onClick = { viewModel.onKeyPress("=") }
+ heightShare = 0.65f,
+ onKey = { viewModel.onKeyPress(it) },
+ modifier = Modifier.fillMaxWidth()
)
}
}
@@ -397,6 +336,7 @@ private fun CircleKey(
KeyType.BACKSPACE -> NumioSurface
KeyType.CLEAR_ALL -> NumioRed
KeyType.EQUAL -> accentLight
+ KeyType.BRACKET -> NumioSurface
}
val contentColor = when (type) {
KeyType.NUM -> NumioTextOnDark
@@ -404,6 +344,7 @@ private fun CircleKey(
KeyType.BACKSPACE -> NumioTextOnDark
KeyType.CLEAR_ALL -> Color.White
KeyType.EQUAL -> NumioBg
+ KeyType.BRACKET -> accent
}
// Bigger labels: AC/⌫ 15 → 18, digits and operators 26 → 32
val fontSize = (if (label == "AC" || label == "C") 18.sp else 32.sp) * labelScale
@@ -420,7 +361,11 @@ private fun CircleKey(
contentPadding = PaddingValues(0.dp)
) {
Text(
- text = if (label == "C") "⌫" else label,
+ text = when (label) {
+ "C" -> "⌫"
+ "()" -> "( )"
+ else -> label
+ },
fontSize = fontSize,
fontWeight = fontWeight
)
@@ -518,9 +463,234 @@ private fun HistorySheetContent(
}
// Result text shrinks as the number gets longer, so it never gets cut off
+@SuppressLint("UnusedBoxWithConstraintsScope")
+@Composable
+private fun CalcDisplay(
+ expression: String,
+ result: String,
+ cursor: Int,
+ showCursor: Boolean,
+ onTapExpression: (Int) -> Unit,
+ accentLight: Color,
+ modifier: Modifier = Modifier
+) {
+ BoxWithConstraints(
+ modifier = modifier
+ .padding(vertical = 12.dp)
+ .clip(RoundedCornerShape(28.dp))
+ .background(Color(0xFF0E0D0C))
+ .padding(horizontal = 20.dp, vertical = 16.dp),
+ contentAlignment = Alignment.BottomEnd
+ ) {
+ // Shrink both lines to fit the card. Heights are in dp, font sizes in sp, so divide
+ // by fontScale: at 150% system font 1sp is 1.5dp. Each line is set to 1.2× its font size.
+ val fontScale = LocalDensity.current.fontScale
+ val textDp = (maxHeight.value - 16f).coerceAtLeast(0f) // 4dp gap + 12dp underline
+ val lineToSp = 1f / (1.2f * fontScale)
+ val exprSize = minOf(48f, textDp * 0.40f * lineToSp).coerceAtLeast(8f)
+ val resultSize = minOf(resultFontSize(result.length).value, textDp * 0.50f * lineToSp)
+ .coerceAtLeast(8f)
+ Column(
+ horizontalAlignment = Alignment.End,
+ verticalArrangement = Arrangement.Bottom,
+ modifier = Modifier.fillMaxWidth()
+ ) {
+ val exprScrollState = rememberScrollState()
+ var exprLayout by remember { mutableStateOf(null) }
+ val currentOnTap by rememberUpdatedState(onTapExpression)
+ val exprColor = Color(0xFFCCBF8A)
+ // Cursor in the middle, or shown after a tap (also at the end) until = or AC.
+ val inMiddle = expression.isNotEmpty() && cursor < expression.length
+ val editing = expression.isNotEmpty() && (showCursor || inMiddle)
+
+ // Brackets still open get a faint ")" at the end: a hint that = will add them.
+ val stillOpen = expression.count { it == '(' } - expression.count { it == ')' }
+ val shown = buildAnnotatedString {
+ append(expression.ifEmpty { "0" })
+ if (stillOpen > 0) {
+ withStyle(SpanStyle(color = exprColor.copy(alpha = 0.35f))) {
+ append(")".repeat(stillOpen))
+ }
+ }
+ }
+
+ val blink by rememberInfiniteTransition(label = "cursor").animateFloat(
+ initialValue = 1f,
+ targetValue = 0.45f, // never fades out fully, so it's easy to spot
+ animationSpec = infiniteRepeatable(tween(530), RepeatMode.Reverse),
+ label = "cursorBlink"
+ )
+
+ // Keep the end in view while typing at the end; keep the cursor in view while editing.
+ LaunchedEffect(expression, cursor, exprLayout) {
+ val layout = exprLayout ?: return@LaunchedEffect
+ if (!inMiddle) {
+ exprScrollState.animateScrollTo(exprScrollState.maxValue)
+ return@LaunchedEffect
+ }
+ val x = layout.getCursorRect(cursor.coerceIn(0, layout.layoutInput.text.length))
+ .left.toInt()
+ val viewport = exprScrollState.viewportSize
+ val margin = 48
+ if (viewport > 0) {
+ if (x < exprScrollState.value + margin) {
+ exprScrollState.animateScrollTo((x - margin).coerceAtLeast(0))
+ } else if (x > exprScrollState.value + viewport - margin) {
+ exprScrollState.animateScrollTo(x - viewport + margin)
+ }
+ }
+ }
+
+ // Expression — bigger and right-aligned. weight(fill = false) measures it last,
+ // so if space ever runs out the expression gets clipped, never the result.
+ // Tap anywhere in it to put the cursor there and fix a number in the middle.
+ Text(
+ text = shown,
+ fontSize = exprSize.sp,
+ lineHeight = (exprSize * 1.2f).sp,
+ textAlign = TextAlign.End,
+ maxLines = 1,
+ overflow = TextOverflow.Clip,
+ color = exprColor,
+ onTextLayout = { exprLayout = it },
+ modifier = Modifier
+ .weight(1f, fill = false)
+ .fillMaxWidth()
+ .horizontalScroll(exprScrollState)
+ .pointerInput(Unit) {
+ detectTapGestures { position ->
+ exprLayout?.let { currentOnTap(it.getOffsetForPosition(position)) }
+ }
+ }
+ .drawWithContent {
+ drawContent()
+ val layout = exprLayout
+ if (editing && layout != null) {
+ val r = layout.getCursorRect(
+ cursor.coerceIn(0, layout.layoutInput.text.length)
+ )
+ drawLine(
+ color = accentLight.copy(alpha = blink),
+ start = Offset(r.left, r.top),
+ end = Offset(r.left, r.bottom),
+ strokeWidth = 3.dp.toPx()
+ )
+ }
+ }
+ )
+ if (result.isNotEmpty()) {
+ Spacer(modifier = Modifier.height(4.dp))
+ // Result — right-aligned, shrinks for long numbers
+ Text(
+ text = result,
+ fontSize = resultSize.sp,
+ lineHeight = (resultSize * 1.2f).sp,
+ fontWeight = FontWeight.Light,
+ textAlign = TextAlign.End,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ color = NumioTextOnDark,
+ modifier = Modifier.fillMaxWidth()
+ )
+ }
+ Box(
+ modifier = Modifier
+ .padding(top = 10.dp)
+ .fillMaxWidth()
+ .height(2.dp)
+ .background(accentLight)
+ )
+ }
+ }
+}
+
+/** Round keys. [heightShare] is how much of the available height the keys may use. */
+@SuppressLint("UnusedBoxWithConstraintsScope")
+@Composable
+private fun CalcKeypad(
+ keys: List>>,
+ accent: Color,
+ accentLight: Color,
+ heightShare: Float,
+ onKey: (String) -> Unit,
+ modifier: Modifier = Modifier
+) {
+ BoxWithConstraints(
+ modifier = modifier.padding(bottom = 16.dp)
+ ) {
+ val gap = 12.dp
+ // Size keys by width, but cap by height so landscape still fits
+ // The top row has 5 smaller keys (AC ⌫ ( ) % ÷) across the same width as 4 keys:
+ // 5 × small + 4 gaps = 4 × key + 3 gaps, so small = (4 × key − gap) / 5.
+ // Height: small + 4 keys + 4 gaps must fit, which gives the byHeight formula.
+ val byWidth = (maxWidth - gap * 3) / 4
+ val byHeight = ((maxHeight * heightShare - gap * 4) * 5 + gap) / 24
+ val keySize = minOf(byWidth, byHeight)
+ val smallKeySize = (keySize * 4 - gap) / 5
+ // Smaller keys (landscape) get smaller labels, so "AC" and "⌫" aren't clipped
+ val labelScale = (keySize / 80.dp).coerceIn(0.45f, 1f)
+ val smallLabelScale = (smallKeySize / 80.dp).coerceIn(0.45f, 1f)
+
+ Column(
+ verticalArrangement = Arrangement.spacedBy(gap),
+ modifier = Modifier.align(Alignment.Center)
+ ) {
+ keys.forEach { row ->
+ val small = row.size == 5
+ Row(horizontalArrangement = Arrangement.spacedBy(gap)) {
+ row.forEach { (label, type) ->
+ CircleKey(
+ label = label,
+ type = type,
+ accent = accent,
+ accentLight = accentLight,
+ labelScale = if (small) smallLabelScale else labelScale,
+ modifier = Modifier.size(if (small) smallKeySize else keySize),
+ onClick = { onKey(label) }
+ )
+ }
+ }
+ }
+ Row(horizontalArrangement = Arrangement.spacedBy(gap)) {
+ CircleKey(
+ label = "0",
+ type = KeyType.NUM,
+ accent = accent,
+ accentLight = accentLight,
+ labelScale = labelScale,
+ modifier = Modifier
+ .width(keySize * 2 + gap)
+ .height(keySize),
+ shape = RoundedCornerShape(999.dp),
+ onClick = { onKey("0") }
+ )
+ CircleKey(
+ label = ".",
+ type = KeyType.NUM,
+ accent = accent,
+ accentLight = accentLight,
+ labelScale = labelScale,
+ modifier = Modifier.size(keySize),
+ onClick = { onKey(".") }
+ )
+ CircleKey(
+ label = "=",
+ type = KeyType.EQUAL,
+ accent = accent,
+ accentLight = accentLight,
+ labelScale = labelScale,
+ modifier = Modifier.size(keySize),
+ onClick = { onKey("=") }
+ )
+ }
+ }
+ }
+}
+
private fun resultFontSize(length: Int) = when {
length <= 8 -> 58.sp
length <= 12 -> 46.sp
length <= 16 -> 36.sp
- else -> 28.sp
+ length <= 20 -> 28.sp
+ else -> 24.sp
}
\ No newline at end of file
diff --git a/app/src/main/java/com/rr/numio/ui.CalculatorViewModel.kt b/app/src/main/java/com/rr/numio/ui.CalculatorViewModel.kt
index 32b6b37..8e58e6b 100644
--- a/app/src/main/java/com/rr/numio/ui.CalculatorViewModel.kt
+++ b/app/src/main/java/com/rr/numio/ui.CalculatorViewModel.kt
@@ -23,6 +23,10 @@ private val sqrtFunction = object : Function("sqrt", 1) {
data class CalculatorUiState(
val expression: String = "",
val result: String = "",
+ /** Where the next key goes. Tap the expression to move it; normally it's at the end. */
+ val cursor: Int = 0,
+ /** True after tapping the expression: the cursor stays visible (even at the end) until = or AC. */
+ val showCursor: Boolean = false,
val isHistoryVisible: Boolean = false,
val isEasterEggVisible: Boolean = false
)
@@ -48,59 +52,112 @@ class CalculatorViewModel(application: Application) : AndroidViewModel(applicati
fun onKeyPress(label: String) {
val current = _uiState.value
+ val cursor = current.cursor.coerceIn(0, current.expression.length)
+ // Keys work on the text left of the cursor; the text right of it stays as it is.
+ val before = current.expression.substring(0, cursor)
+ val after = current.expression.substring(cursor)
when (label) {
"AC" -> {
justEvaluated = false
- _uiState.value = current.copy(expression = "", result = "")
+ _uiState.value = current.copy(expression = "", result = "", cursor = 0, showCursor = false)
}
"C" -> {
justEvaluated = false
- val newExpr = current.expression.dropLast(1)
- val liveResult = evaluatePreview(newExpr)
- _uiState.value = current.copy(expression = newExpr, result = liveResult)
+ val newBefore = before.dropLast(1)
+ val newExpr = newBefore + after
+ _uiState.value = current.copy(
+ expression = newExpr,
+ result = evaluatePreview(newExpr),
+ cursor = newBefore.length
+ )
}
"=" -> evaluate()
else -> {
val isOperator = label in operators
- val base = when {
+ val (base, rest) = when {
justEvaluated && isOperator ->
- if (current.result.isNotEmpty() && current.result != "Error") current.result
- else current.expression
- justEvaluated -> ""
- else -> current.expression
+ (if (current.result.isNotEmpty() && current.result != "Error") current.result
+ else current.expression) to ""
+ justEvaluated -> "" to ""
+ else -> before to after
}
justEvaluated = false
- val newExpression = appendInput(base, label)
- val liveResult = evaluatePreview(newExpression)
- _uiState.value = current.copy(expression = newExpression, result = liveResult)
+ var newBefore = appendInput(base, label)
+ var newAfter = rest
+ if (label == "()" && newBefore == "$base)" && rest.startsWith(")")) {
+ // A ")" is already right after the cursor: step over it, don't add another.
+ newBefore = base + ")"
+ newAfter = rest.drop(1)
+ } else if (label in binaryOps && newBefore != base &&
+ rest.firstOrNull()?.toString() in binaryOps
+ ) {
+ // Cursor before an operator (11|+12) and a new operator typed: replace it.
+ newAfter = rest.drop(1)
+ }
+ val newExpression = newBefore + newAfter
+ _uiState.value = current.copy(
+ expression = newExpression,
+ result = evaluatePreview(newExpression),
+ cursor = newBefore.length
+ )
}
}
}
+
+ /** Tapping the expression puts the cursor there, to fix or add a number in the middle. */
+ fun moveCursor(position: Int) {
+ val current = _uiState.value
+ val newCursor = position.coerceIn(0, current.expression.length)
+ if (newCursor == current.cursor && current.showCursor && !justEvaluated) return
+ justEvaluated = false
+ _uiState.value = current.copy(
+ cursor = newCursor,
+ showCursor = true,
+ result = evaluatePreview(current.expression)
+ )
+ }
+
private val binaryOps = setOf("+", "-", "×", "÷", "^")
private fun appendInput(expr: String, label: String): String {
val last = expr.lastOrNull()?.toString()
+ // After % or ) a new number means multiply: 5%2 → 5%×2, (2+3)4 → (2+3)×4
+ val afterClosed = last == "%" || last == ")"
return when {
+ label == "()" -> {
+ // One smart key: closes an open bracket after a number, otherwise opens one.
+ // A bracket right after a number multiplies: 2( → 2×(
+ val stillOpen = expr.count { it == '(' } - expr.count { it == ')' }
+ val c = expr.lastOrNull()
+ val afterValue = c != null && (c.isDigit() || c == ')' || c == '%' || c == '.')
+ when {
+ stillOpen > 0 && afterValue -> expr.trimEnd('.') + ")"
+ afterValue -> expr.trimEnd('.') + "×("
+ else -> "$expr("
+ }
+ }
label in binaryOps -> {
- if (label == "-" && (last == null || last in setOf("×", "÷", "^"))) {
+ if (label == "-" && (last == null || last in setOf("×", "÷", "^", "("))) {
return expr + "-"
}
val trimmed = expr.trimEnd { it.toString() in binaryOps || it == '.' }
- if (trimmed.isEmpty()) expr else trimmed + label
+ // Nothing to work on yet: right at the start, or right after "("
+ if (trimmed.isEmpty() || trimmed.last() == '(') expr else trimmed + label
}
label == "%" -> {
val trimmed = expr.trimEnd { it.toString() in binaryOps || it == '.' }
- if (trimmed.isEmpty() || trimmed.last() == '%') expr else "$trimmed%"
+ if (trimmed.isEmpty() || trimmed.last() == '%' || trimmed.last() == '(') expr
+ else "$trimmed%"
}
label == "." -> {
val currentNumber = expr.takeLastWhile { it.isDigit() || it == '.' }
when {
'.' in currentNumber -> expr
- currentNumber.isEmpty() -> expr + (if (last == "%") "×0." else "0.")
+ currentNumber.isEmpty() -> expr + (if (afterClosed) "×0." else "0.")
else -> "$expr."
}
}
- else -> if (last == "%") "$expr×$label" else expr + label
+ else -> if (afterClosed) "$expr×$label" else expr + label
}
}
fun toggleHistory() {
@@ -116,6 +173,8 @@ class CalculatorViewModel(application: Application) : AndroidViewModel(applicati
_uiState.value = _uiState.value.copy(
expression = entry.result,
result = "",
+ cursor = entry.result.length,
+ showCursor = false,
isHistoryVisible = false
)
}
@@ -130,38 +189,70 @@ class CalculatorViewModel(application: Application) : AndroidViewModel(applicati
private fun isCompleteExpression(expr: String): Boolean {
if (expr.isBlank()) return false
- val trailingOperator = Regex("[+\\-×÷^]$")
- return !trailingOperator.containsMatchIn(expr)
+ val trailingOperator = Regex("[+\\-×÷^(]$")
+ if (trailingOperator.containsMatchIn(expr)) return false
+ // Editing in the middle can leave broken spots, like deleting the 1 in 45-1+124
+ // gives 45-+124. Show no answer until it's fixed, instead of a wrong one.
+ if (expr.first() in "+×÷^%)") return false
+ for (i in 1 until expr.length) {
+ val a = expr[i - 1]
+ val b = expr[i]
+ val aIsOp = a in "+-×÷^"
+ when {
+ // two signs in a row; only a minus after × ÷ ^ ( is fine (2×-3, (-3))
+ b in "+×÷^" && (aIsOp || a == '(') -> return false
+ b == '-' && a in "+-" -> return false
+ // % or ) right after a sign or "("
+ (b == '%' || b == ')') && (aIsOp || a == '(') -> return false
+ }
+ }
+ return true
+ }
+
+ /** Adds the ")" still missing at the end, so (2+3 can already show 5. */
+ private fun closeBrackets(expr: String): String {
+ val stillOpen = expr.count { it == '(' } - expr.count { it == ')' }
+ return if (stillOpen > 0) expr + ")".repeat(stillOpen) else expr
}
private fun evaluatePreview(expression: String): String {
if (!isCompleteExpression(expression)) return ""
- return try {
- val sanitized = expression
- .replace("×", "*")
- .replace("÷", "/")
- .replace("%", "/100")
- .replace(Regex("√(\\d+(\\.\\d+)?)"), "sqrt($1)")
-
- val res = ExpressionBuilder(sanitized)
- .function(sqrtFunction)
- .build()
- .evaluate()
-
- if (res.isNaN() || res.isInfinite()) ""
- else formatNumber(res)
- } catch (e: Exception) {
- ""
- }
+ return calculate(closeBrackets(expression)) ?: ""
}
private fun evaluate() {
- val expression = _uiState.value.expression
- if (!isCompleteExpression(expression)) {
+ val typed = _uiState.value.expression
+ if (!isCompleteExpression(typed)) {
_uiState.value = _uiState.value.copy(result = "Error")
return
}
- try {
+ val expression = closeBrackets(typed)
+ val resStr = calculate(expression)
+ if (resStr == null) {
+ _uiState.value = _uiState.value.copy(result = "Error")
+ return
+ }
+ justEvaluated = true
+ _uiState.value = _uiState.value.copy(
+ expression = expression,
+ result = resStr,
+ cursor = expression.length,
+ showCursor = false
+ )
+
+ viewModelScope.launch {
+ repository.save(expression = expression, result = resStr)
+ }
+ }
+
+ /**
+ * The answer as display text, or null when it can't be worked out.
+ * Keypad maths is done exactly (see [ExactMath]); exp4j is only the fallback,
+ * e.g. for a result like 1.5E20 reused from history.
+ */
+ private fun calculate(expression: String): String? {
+ ExactMath.evaluate(expression)?.let { return formatExact(it) }
+ return try {
val sanitized = expression
.replace("×", "*")
.replace("÷", "/")
@@ -173,20 +264,9 @@ class CalculatorViewModel(application: Application) : AndroidViewModel(applicati
.build()
.evaluate()
- if (res.isNaN() || res.isInfinite()) {
- _uiState.value = _uiState.value.copy(result = "Error")
- return
- }
-
- val resStr = formatNumber(res)
- justEvaluated = true
- _uiState.value = _uiState.value.copy(result = resStr)
-
- viewModelScope.launch {
- repository.save(expression = expression, result = resStr)
- }
+ if (res.isNaN() || res.isInfinite()) null else formatNumber(res)
} catch (e: Exception) {
- _uiState.value = _uiState.value.copy(result = "Error")
+ null
}
}
diff --git a/app/src/main/java/com/rr/numio/ui.ConverterScreen.kt b/app/src/main/java/com/rr/numio/ui.ConverterScreen.kt
index c0aa984..8733047 100644
--- a/app/src/main/java/com/rr/numio/ui.ConverterScreen.kt
+++ b/app/src/main/java/com/rr/numio/ui.ConverterScreen.kt
@@ -22,8 +22,11 @@ import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
+import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.collectLatest
data class ConversionUnit(val name: String, val toBase: Double)
@@ -184,6 +187,20 @@ fun ConverterScreen(
LaunchedEffect(result) {
if (result.isNotEmpty()) resultInView.bringIntoView()
}
+ // Also when the keyboard opens without the result changing (tapping the same field
+ // again): wait for the keyboard to finish sliding up, then scroll the result into view.
+ val density = LocalDensity.current
+ val imeInsets = WindowInsets.ime
+ val currentResult by rememberUpdatedState(result)
+ LaunchedEffect(imeInsets, density) {
+ snapshotFlow { imeInsets.getBottom(density) }
+ .collectLatest { keyboardHeight ->
+ if (keyboardHeight > 0 && currentResult.isNotEmpty()) {
+ delay(150) // collectLatest restarts this while the keyboard is still moving
+ resultInView.bringIntoView()
+ }
+ }
+ }
Column(
modifier = Modifier
diff --git a/app/src/main/java/com/rr/numio/ui.ExactMath.kt b/app/src/main/java/com/rr/numio/ui.ExactMath.kt
new file mode 100644
index 0000000..faf757c
--- /dev/null
+++ b/app/src/main/java/com/rr/numio/ui.ExactMath.kt
@@ -0,0 +1,118 @@
+package com.rr.numio.ui
+
+import java.math.BigDecimal
+import java.math.MathContext
+import java.util.Locale
+
+/**
+ * Exact maths for what the keypad can type: numbers, + - × ÷ % and brackets.
+ *
+ * exp4j works in Double, which only keeps about 16 digits, so
+ * 9007199254740993 − 9007199254740992 came out as 0 instead of 1.
+ * BigDecimal keeps every digit for + − × and 34 digits for ÷.
+ *
+ * Returns null when the text has anything else in it (like 1.5E20 reused from history)
+ * or can't be worked out (like ÷ 0), so the caller can fall back to exp4j.
+ */
+internal object ExactMath {
+ private val DIVIDE = MathContext.DECIMAL128
+ private val HUNDRED = BigDecimal(100)
+ private const val ALLOWED = "0123456789.+-×÷%()"
+
+ fun evaluate(expression: String): BigDecimal? {
+ if (expression.isEmpty() || expression.any { it !in ALLOWED }) return null
+ return try {
+ Parser(expression).parse()
+ } catch (e: NumberFormatException) {
+ null
+ } catch (e: ArithmeticException) {
+ null
+ }
+ }
+
+ /**
+ * expression := term (+|- term)* ; term := unary (×|÷ unary)*
+ * unary := -unary | (number | "(" expression ")") %*
+ */
+ private class Parser(private val s: String) {
+ private var pos = 0
+
+ fun parse(): BigDecimal {
+ val value = expression()
+ if (pos != s.length) throw NumberFormatException("Unexpected '${s[pos]}' at $pos")
+ return value
+ }
+
+ private fun peek(): Char? = if (pos < s.length) s[pos] else null
+
+ private fun expression(): BigDecimal {
+ var value = term()
+ while (peek() == '+' || peek() == '-') {
+ val op = s[pos++]
+ val right = term()
+ value = if (op == '+') value.add(right) else value.subtract(right)
+ }
+ return value
+ }
+
+ private fun term(): BigDecimal {
+ var value = unary()
+ while (peek() == '×' || peek() == '÷') {
+ val op = s[pos++]
+ val right = unary()
+ value = if (op == '×') value.multiply(right) else value.divide(right, DIVIDE)
+ }
+ return value
+ }
+
+ private fun unary(): BigDecimal {
+ if (peek() == '-') {
+ pos++
+ return unary().negate()
+ }
+ var value = if (peek() == '(') {
+ pos++
+ val inside = expression()
+ if (peek() != ')') throw NumberFormatException("Missing ) at $pos")
+ pos++
+ inside
+ } else {
+ number()
+ }
+ while (peek() == '%') {
+ pos++
+ value = value.divide(HUNDRED, DIVIDE)
+ }
+ return value
+ }
+
+ private fun number(): BigDecimal {
+ val start = pos
+ while (pos < s.length && (s[pos] in '0'..'9' || s[pos] == '.')) pos++
+ if (start == pos) throw NumberFormatException("Number expected at $start")
+ return BigDecimal(s.substring(start, pos))
+ }
+ }
+}
+
+private val SCIENTIFIC_ABOVE = BigDecimal("1E15")
+private val SCIENTIFIC_BELOW = BigDecimal("1E-6")
+
+/**
+ * Display text for an exact result. Whole numbers up to 20 digits are shown in full,
+ * everything else follows the same rules as [formatNumber].
+ */
+fun formatExact(value: BigDecimal, significantDigits: Int = 12): String {
+ if (value.signum() == 0) return "0"
+ val plain = value.stripTrailingZeros()
+ val digits = plain.precision() - plain.scale()
+ if (plain.scale() <= 0 && digits <= 20) return plain.toPlainString()
+ val size = plain.abs()
+ if (size >= SCIENTIFIC_ABOVE || size < SCIENTIFIC_BELOW) {
+ val text = String.format(Locale.ROOT, "%.${significantDigits - 1}e", plain)
+ val mantissa = text.substringBefore('e').trimEnd('0').trimEnd('.')
+ val exponent = text.substringAfter('e').toInt()
+ return "${mantissa}E$exponent"
+ }
+ return plain.round(MathContext(15)).stripTrailingZeros().toPlainString()
+}
diff --git a/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
index 80b730f..6751c8f 100644
--- a/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
+++ b/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml
@@ -2,4 +2,5 @@
+
diff --git a/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
index 80b730f..6751c8f 100644
--- a/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
+++ b/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml
@@ -2,4 +2,5 @@
+
diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher_monochrome.webp b/app/src/main/res/mipmap-hdpi/ic_launcher_monochrome.webp
new file mode 100644
index 0000000..a65e22e
Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher_monochrome.webp differ
diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher_monochrome.webp b/app/src/main/res/mipmap-mdpi/ic_launcher_monochrome.webp
new file mode 100644
index 0000000..44db662
Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher_monochrome.webp differ
diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher_monochrome.webp b/app/src/main/res/mipmap-xhdpi/ic_launcher_monochrome.webp
new file mode 100644
index 0000000..2c80253
Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher_monochrome.webp differ
diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher_monochrome.webp b/app/src/main/res/mipmap-xxhdpi/ic_launcher_monochrome.webp
new file mode 100644
index 0000000..21ffd12
Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher_monochrome.webp differ
diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_monochrome.webp b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_monochrome.webp
new file mode 100644
index 0000000..e9a6bd5
Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_monochrome.webp differ
diff --git a/app/src/test/java/com/rr/numio/ui/ExactMathTest.kt b/app/src/test/java/com/rr/numio/ui/ExactMathTest.kt
new file mode 100644
index 0000000..f036170
--- /dev/null
+++ b/app/src/test/java/com/rr/numio/ui/ExactMathTest.kt
@@ -0,0 +1,65 @@
+package com.rr.numio.ui
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Test
+
+class ExactMathTest {
+
+ private fun calc(expression: String): String? =
+ ExactMath.evaluate(expression)?.let { formatExact(it) }
+
+ @Test
+ fun bigNumbersKeepEveryDigit() {
+ // Issue #1: Double gave 0 here
+ assertEquals("1", calc("9007199254740993-9007199254740992"))
+ assertEquals("9007199254740994", calc("9007199254740993+1"))
+ assertEquals("9999999800000001", calc("99999999×99999999"))
+ }
+
+ @Test
+ fun everydayMathStaysTheSame() {
+ assertEquals("5", calc("2+3"))
+ assertEquals("0.3", calc("0.1+0.2"))
+ assertEquals("0.333333333333333", calc("1÷3"))
+ assertEquals("0.666666666666667", calc("2÷3"))
+ assertEquals("14", calc("2+3×4"))
+ assertEquals("-6", calc("-2×3"))
+ assertEquals("-6", calc("2×-3"))
+ assertEquals("2.5", calc("5÷2"))
+ }
+
+ @Test
+ fun percentWorksLikeBefore() {
+ assertEquals("0.5", calc("50%"))
+ assertEquals("50.1", calc("50+10%"))
+ assertEquals("0.06", calc("2×3%"))
+ }
+
+ @Test
+ fun brackets() {
+ // Issue #4
+ assertEquals("20", calc("(2+3)×4"))
+ assertEquals("14", calc("2×(3+4)"))
+ assertEquals("-5", calc("-(2+3)"))
+ assertEquals("1", calc("(50+50)%"))
+ assertEquals("21", calc("((1+2)×(3+4))"))
+ assertEquals("2", calc("10÷(2+3)"))
+ assertNull(ExactMath.evaluate("(2+3")) // the screen adds the missing ")" first
+ assertNull(ExactMath.evaluate("()"))
+ }
+
+ @Test
+ fun hugeAndTinyUseScientific() {
+ assertEquals("1E25", calc("10000000000000×1000000000000"))
+ assertEquals("1E-7", calc("1÷10000000"))
+ }
+
+ @Test
+ fun otherInputFallsBackToExp4j() {
+ assertNull(ExactMath.evaluate("1.5E20+1")) // result reused from history
+ assertNull(ExactMath.evaluate("5÷0"))
+ assertNull(ExactMath.evaluate("2+"))
+ assertNull(ExactMath.evaluate(""))
+ }
+}
diff --git a/fastlane/metadata/android/en-US/changelogs/9.txt b/fastlane/metadata/android/en-US/changelogs/9.txt
new file mode 100644
index 0000000..faeee5b
--- /dev/null
+++ b/fastlane/metadata/android/en-US/changelogs/9.txt
@@ -0,0 +1,6 @@
+- New ( ) key for brackets
+- Tap the sum to place a cursor and edit in the middle
+- Exact maths: big numbers keep every digit
+- Landscape: display and keys side by side, readable with large fonts
+- Converter: result stays visible above the keyboard
+- Themed icon support (Android 13+)