calculator: units in calculations and a unit converter tab
- Commit
b8657d84eb73c0e1f321d8a14344a80dd980f4a3- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-13 21:32 UTC (3 months ago)
- Parents
9f7ccd5
Diff
calculator/src/main/java/com/vayunmathur/calculator/MainActivity.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/MainActivity.kt b/calculator/src/main/java/com/vayunmathur/calculator/MainActivity.ktindex f61fb59cfa..bd69b3a080 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/MainActivity.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/MainActivity.kt@@ -8,10 +8,12 @@ import androidx.activity.viewModels import androidx.compose.runtime.Composable import com.vayunmathur.calculator.ui.CalculatorPage import com.vayunmathur.calculator.ui.GraphPage+import com.vayunmathur.calculator.ui.UnitConverterPage import com.vayunmathur.calculator.util.CalculatorViewModel import com.vayunmathur.library.ui.DynamicTheme import com.vayunmathur.library.ui.IconCalculate import com.vayunmathur.library.ui.IconFunctions+import com.vayunmathur.library.ui.IconRuler import com.vayunmathur.library.util.BottomBarItem import com.vayunmathur.library.util.BottomNavBar import com.vayunmathur.library.util.MainNavigation@@ -40,6 +42,9 @@ sealed interface Route : NavKey { @Serializable data object Graph : Route++ @Serializable+ data object Units : Route } @Composable@@ -54,6 +59,7 @@ fun Navigation(viewModel: CalculatorViewModel) { listOf( BottomBarItem("Calculator", Route.Calculator) { IconCalculate() }, BottomBarItem("Graph", Route.Graph) { IconFunctions() },+ BottomBarItem("Units", Route.Units) { IconRuler() }, ), current, )@@ -61,5 +67,6 @@ fun Navigation(viewModel: CalculatorViewModel) { ) { entry<Route.Calculator> { CalculatorPage(viewModel) } entry<Route.Graph> { GraphPage(viewModel) }+ entry<Route.Units> { UnitConverterPage(viewModel) } } }
calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorPage.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorPage.kt b/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorPage.ktindex f1880ca5dd..b321fa2b4e 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorPage.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorPage.kt@@ -5,17 +5,21 @@ import com.vayunmathur.calculator.R import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.ExperimentalLayoutApi+import androidx.compose.foundation.layout.FlowRow import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf@@ -33,15 +37,21 @@ import com.vayunmathur.calculator.util.CalculatorViewModel import com.vayunmathur.calculator.util.HistoryEntry import com.vayunmathur.library.ui.R as UiR import com.vayunmathur.library.ui.AlertDialog+import com.vayunmathur.library.ui.AssistChip import com.vayunmathur.library.ui.Button import com.vayunmathur.library.ui.ButtonDefaults import com.vayunmathur.library.ui.Card import com.vayunmathur.library.ui.CenterAlignedTopAppBar+import com.vayunmathur.library.ui.FilterChip import com.vayunmathur.library.ui.HorizontalDivider import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.IconHistory+import com.vayunmathur.library.ui.IconRuler import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.ModalBottomSheet+import com.vayunmathur.library.ui.PrimaryScrollableTabRow import com.vayunmathur.library.ui.Scaffold+import com.vayunmathur.library.ui.Tab import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.TextButton @@ -116,9 +126,11 @@ fun CalculatorScreen( */ initialShowHistory: Boolean = false, initialSecond: Boolean = false,+ initialShowUnitPicker: Boolean = false, ) { var showHistory by remember { mutableStateOf(initialShowHistory) } var second by remember { mutableStateOf(initialSecond) }+ var showUnitPicker by remember { mutableStateOf(initialShowUnitPicker) } fun ins(text: String): (CalculatorActions) -> Unit = { it.append(text) } @@ -184,7 +196,10 @@ fun CalculatorScreen( Scaffold( topBar = { CenterAlignedTopAppBar(- actions = { IconButton({ showHistory = true }) { IconHistory() } },+ actions = {+ IconButton({ showUnitPicker = true }) { IconRuler() }+ IconButton({ showHistory = true }) { IconHistory() }+ }, ) }, ) { padding ->@@ -216,6 +231,26 @@ fun CalculatorScreen( softWrap = false, color = MaterialTheme.colorScheme.onSurfaceVariant, )+ if (state.unitOptions.isNotEmpty()) {+ Row(+ Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).padding(top = 8.dp),+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Text(+ stringResource(R.string.convert_to),+ fontSize = 12.sp,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ state.unitOptions.forEach { unit ->+ FilterChip(+ selected = unit == state.selectedUnit,+ onClick = { actions.selectOutputUnit(unit.token) },+ label = { Text(unit.symbol) },+ )+ }+ }+ } } HorizontalDivider()@@ -232,6 +267,53 @@ fun CalculatorScreen( } if (showHistory) HistoryDialog(state.history, actions) { showHistory = false }+ if (showUnitPicker) UnitPickerSheet(state, actions) { showUnitPicker = false }+}++@OptIn(ExperimentalLayoutApi::class)+@Composable+private fun UnitPickerSheet(+ state: CalculatorUiState,+ actions: CalculatorActions,+ onDismiss: () -> Unit,+) {+ val categories = state.unitCategories.filter { it.inEquations }+ var categoryIndex by remember { mutableStateOf(0) }+ ModalBottomSheet(onDismissRequest = onDismiss) {+ Text(+ stringResource(R.string.insert_unit),+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),+ fontSize = 20.sp,+ )+ if (categories.isNotEmpty()) {+ PrimaryScrollableTabRow(selectedTabIndex = categoryIndex) {+ categories.forEachIndexed { index, category ->+ Tab(+ selected = index == categoryIndex,+ onClick = { categoryIndex = index },+ text = { Text(category.name) },+ )+ }+ }+ categories.getOrNull(categoryIndex)?.let { category ->+ FlowRow(+ Modifier+ .fillMaxWidth()+ .heightIn(max = 360.dp)+ .verticalScroll(rememberScrollState())+ .padding(16.dp),+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ category.units.forEach { unit ->+ AssistChip(+ onClick = { actions.append(unit.token); onDismiss() },+ label = { Text(unit.symbol) },+ )+ }+ }+ }+ }+ } } @Composable
calculator/src/main/java/com/vayunmathur/calculator/ui/UnitConverterPage.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/ui/UnitConverterPage.kt b/calculator/src/main/java/com/vayunmathur/calculator/ui/UnitConverterPage.ktnew file mode 100644index 0000000000..d2727a078c--- /dev/null+++ b/calculator/src/main/java/com/vayunmathur/calculator/ui/UnitConverterPage.kt@@ -0,0 +1,173 @@+package com.vayunmathur.calculator.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.input.KeyboardType+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import androidx.compose.foundation.text.KeyboardOptions+import com.vayunmathur.calculator.R+import com.vayunmathur.calculator.util.CalculatorViewModel+import com.vayunmathur.calculator.util.UnitConverterActions+import com.vayunmathur.calculator.util.UnitConverterUiState+import com.vayunmathur.calculator.util.UnitDef+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.CenterAlignedTopAppBar+import com.vayunmathur.library.ui.DropdownMenu+import com.vayunmathur.library.ui.DropdownMenuItem+import com.vayunmathur.library.ui.FilledTonalIconButton+import com.vayunmathur.library.ui.IconArrowDropDown+import com.vayunmathur.library.ui.IconSwapLanguages+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.OutlinedTextField+import com.vayunmathur.library.ui.PrimaryScrollableTabRow+import com.vayunmathur.library.ui.Scaffold+import com.vayunmathur.library.ui.Spacing+import com.vayunmathur.library.ui.Tab+import com.vayunmathur.library.ui.Text++/** Binds [CalculatorViewModel] to the stateless [UnitConverterScreen]. */+@Composable+fun UnitConverterPage(viewModel: CalculatorViewModel) {+ UnitConverterScreen(state = viewModel.unitConverterUiState, actions = viewModel)+}++/**+ * The units tab: a plain from/to converter with no equations, one category per tab. Stateless+ * so it can be rendered from a `@Preview` — see `src/screenshotTest`.+ */+@Composable+fun UnitConverterScreen(state: UnitConverterUiState, actions: UnitConverterActions) {+ Scaffold(+ topBar = { CenterAlignedTopAppBar(title = { Text(stringResource(R.string.units)) }) },+ ) { padding ->+ val category = state.categories.getOrNull(state.selectedCategoryIndex)+ Column(Modifier.fillMaxSize().padding(padding)) {+ PrimaryScrollableTabRow(selectedTabIndex = state.selectedCategoryIndex) {+ state.categories.forEachIndexed { index, cat ->+ Tab(+ selected = index == state.selectedCategoryIndex,+ onClick = { actions.selectCategory(index) },+ text = { Text(cat.name) },+ )+ }+ }+ if (category != null) {+ Column(+ Modifier.fillMaxWidth().padding(Spacing.lg),+ verticalArrangement = Arrangement.spacedBy(Spacing.md),+ ) {+ OutlinedTextField(+ value = state.inputText,+ onValueChange = actions::setConverterInput,+ label = { Text(stringResource(R.string.converter_value)) },+ singleLine = true,+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal),+ modifier = Modifier.fillMaxWidth(),+ )+ Row(verticalAlignment = Alignment.Bottom) {+ LabeledUnitDropdown(+ label = stringResource(R.string.converter_from),+ units = category.units,+ selectedToken = state.fromToken,+ onSelect = actions::setFrom,+ modifier = Modifier.weight(1f),+ )+ FilledTonalIconButton(+ onClick = actions::swapUnits,+ modifier = Modifier.padding(horizontal = Spacing.sm),+ ) { IconSwapLanguages() }+ LabeledUnitDropdown(+ label = stringResource(R.string.converter_to),+ units = category.units,+ selectedToken = state.toToken,+ onSelect = actions::setTo,+ modifier = Modifier.weight(1f),+ )+ }+ val toSymbol = category.units.firstOrNull { it.token == state.toToken }?.symbol.orEmpty()+ Card(Modifier.fillMaxWidth()) {+ Column(Modifier.padding(Spacing.lg)) {+ Text(+ stringResource(R.string.converter_result),+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ fontSize = 14.sp,+ )+ Text(+ if (state.outputText.isEmpty()) "—" else "${state.outputText}\u202F$toSymbol",+ fontSize = 28.sp,+ maxLines = 1,+ )+ }+ }+ }+ }+ }+ }+}++@Composable+private fun LabeledUnitDropdown(+ label: String,+ units: List<UnitDef>,+ selectedToken: String,+ onSelect: (String) -> Unit,+ modifier: Modifier = Modifier,+) {+ Column(modifier) {+ Text(label, color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 12.sp)+ UnitDropdown(units, selectedToken, onSelect, Modifier.fillMaxWidth().padding(top = 4.dp))+ }+}++/**+ * A unit selector built from [OutlinedButton] + [DropdownMenu] rather than the library's+ * `ExposedDropdownMenu` wrapper, which currently recurses into itself.+ */+@Composable+private fun UnitDropdown(+ units: List<UnitDef>,+ selectedToken: String,+ onSelect: (String) -> Unit,+ modifier: Modifier = Modifier,+) {+ var expanded by remember { mutableStateOf(false) }+ val selected = units.firstOrNull { it.token == selectedToken }+ Box(modifier) {+ OutlinedButton(onClick = { expanded = true }, modifier = Modifier.fillMaxWidth()) {+ Text(+ selected?.symbol.orEmpty(),+ modifier = Modifier.weight(1f),+ textAlign = TextAlign.Start,+ maxLines = 1,+ )+ IconArrowDropDown()+ }+ DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {+ units.forEach { unit ->+ DropdownMenuItem(+ text = { Text("${unit.symbol} — ${unit.name}") },+ onClick = {+ onSelect(unit.token)+ expanded = false+ },+ )+ }+ }+ }+}
calculator/src/main/java/com/vayunmathur/calculator/util/CalculatorUiContract.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/util/CalculatorUiContract.kt b/calculator/src/main/java/com/vayunmathur/calculator/util/CalculatorUiContract.ktindex afba1bccc7..8834351406 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/util/CalculatorUiContract.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/util/CalculatorUiContract.kt@@ -26,6 +26,12 @@ data class CalculatorUiState( val memory: Double = 0.0, val angleMode: AngleMode = AngleMode.RADIANS, val history: List<HistoryEntry> = emptyList(),+ /** Units compatible with the current result's dimension; empty when it's dimensionless. */+ val unitOptions: List<UnitDef> = emptyList(),+ /** The unit the result is currently shown in, chosen from [unitOptions]. */+ val selectedUnit: UnitDef? = null,+ /** Every category the unit picker can insert from. */+ val unitCategories: List<UnitCategory> = emptyList(), ) /** Everything the graph screen draws. */@@ -53,6 +59,9 @@ interface CalculatorActions { fun useHistory(entry: HistoryEntry) {} fun clearHistory() {} + /** Show the result in the compatible unit identified by [token]. */+ fun selectOutputUnit(token: String) {}+ companion object { val Noop: CalculatorActions = object : CalculatorActions {} }@@ -80,3 +89,26 @@ interface GraphActions { val Noop: GraphActions = object : GraphActions {} } }++/** Everything the unit-converter screen draws. */+data class UnitConverterUiState(+ val categories: List<UnitCategory> = emptyList(),+ val selectedCategoryIndex: Int = 0,+ val fromToken: String = "",+ val toToken: String = "",+ val inputText: String = "",+ val outputText: String = "",+)++/** Unit-converter callbacks. Same no-op-default arrangement as [CalculatorActions]. */+interface UnitConverterActions {+ fun selectCategory(index: Int) {}+ fun setFrom(token: String) {}+ fun setTo(token: String) {}+ fun setConverterInput(text: String) {}+ fun swapUnits() {}++ companion object {+ val Noop: UnitConverterActions = object : UnitConverterActions {}+ }+}
calculator/src/main/java/com/vayunmathur/calculator/util/CalculatorViewModel.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/util/CalculatorViewModel.kt b/calculator/src/main/java/com/vayunmathur/calculator/util/CalculatorViewModel.ktindex 4b756ca148..e7d9be01f0 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/util/CalculatorViewModel.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/util/CalculatorViewModel.kt@@ -32,7 +32,7 @@ data class GraphMarker( * Holds all calculator state at the Activity scope so it survives switching between the * Calculator and Graph tabs (which reset the nav back stack). */-class CalculatorViewModel : ViewModel(), CalculatorActions, GraphActions {+class CalculatorViewModel : ViewModel(), CalculatorActions, GraphActions, UnitConverterActions { // ---- Shared ---- var angleMode by mutableStateOf(AngleMode.RADIANS)@@ -40,13 +40,14 @@ class CalculatorViewModel : ViewModel(), CalculatorActions, GraphActions { override fun toggleAngleMode() { angleMode = if (angleMode == AngleMode.RADIANS) AngleMode.DEGREES else AngleMode.RADIANS+ recomputePreview() } // ---- Calculator tab ---- var input by mutableStateOf("") private set - /** Live-evaluated preview of [input]; empty when blank or invalid. */+ /** Live-evaluated preview of [input]; empty when blank or invalid. Unit-aware. */ var preview by mutableStateOf("") private set @@ -58,6 +59,17 @@ class CalculatorViewModel : ViewModel(), CalculatorActions, GraphActions { var memory by mutableStateOf(0.0) private set + /** Units the current result can be shown in; empty when the result is dimensionless. */+ var unitOptions by mutableStateOf<List<UnitDef>>(emptyList())+ private set++ /** The unit [preview] is currently rendered in. */+ var selectedUnit by mutableStateOf<UnitDef?>(null)+ private set++ /** The most recent parsed preview value, kept so switching output units is instant. */+ private var previewQuantity: Quantity? = null+ val history = mutableStateListOf<HistoryEntry>() /**@@ -71,6 +83,9 @@ class CalculatorViewModel : ViewModel(), CalculatorActions, GraphActions { memory = memory, angleMode = angleMode, history = history,+ unitOptions = unitOptions,+ selectedUnit = selectedUnit,+ unitCategories = UnitRegistry.categories, ) /** Snapshot of everything [com.vayunmathur.calculator.ui.GraphScreen] draws. */@@ -84,7 +99,7 @@ class CalculatorViewModel : ViewModel(), CalculatorActions, GraphActions { fun updateInput(value: String) { input = value- preview = computePreview(value)+ recomputePreview() } override fun append(text: String) = updateInput(input + text)@@ -98,22 +113,31 @@ class CalculatorViewModel : ViewModel(), CalculatorActions, GraphActions { /** Evaluate the current input, push it to history, store `ans`, show the result. */ override fun evaluate() { if (input.isBlank()) return- val value = try {- Expression.parse(input).eval(angle = angleMode, ans = lastAnswer)+ val quantity = try {+ Expression.parse(input).evalQuantity(angle = angleMode, ans = lastAnswer) } catch (e: ExpressionError) { return // leave input untouched; the preview already flagged the problem }- if (value.isNaN()) return- val result = formatResult(value)- history.add(0, HistoryEntry(input, result))- lastAnswer = value- updateInput(result)+ if (quantity.value.isNaN()) return+ val unit = if (quantity.isDimensionless) null else (selectedUnit ?: UnitRegistry.defaultUnitFor(quantity.dimension))+ val display = formatQuantity(quantity, unit)+ history.add(0, HistoryEntry(input, display))+ lastAnswer = quantity.value+ if (unit != null) selectedUnit = unit+ // The token form re-parses, so the result can seed the next calculation.+ updateInput(formatQuantity(quantity, unit, useToken = true)) } override fun useHistory(entry: HistoryEntry) = updateInput(entry.result) override fun clearHistory() = history.clear() + override fun selectOutputUnit(token: String) {+ val unit = unitOptions.firstOrNull { it.token == token } ?: return+ selectedUnit = unit+ previewQuantity?.let { preview = formatQuantity(it, unit) }+ }+ // Memory register operations. M+/M- fold the current preview (or input) into memory. override fun memoryClear() { memory = 0.0 } override fun memoryRecall() = append(formatResult(memory))@@ -125,13 +149,25 @@ class CalculatorViewModel : ViewModel(), CalculatorActions, GraphActions { .takeIf { !it.isNaN() } } catch (e: ExpressionError) { null } - private fun computePreview(value: String): String {- if (value.isBlank()) return ""- return try {- val r = Expression.parse(value).eval(angle = angleMode, ans = lastAnswer)- if (r.isNaN()) "" else formatResult(r)+ /** Re-derive [preview], [unitOptions] and [selectedUnit] from the current [input]. */+ private fun recomputePreview() {+ val quantity = try {+ if (input.isBlank()) null+ else Expression.parse(input).evalQuantity(angle = angleMode, ans = lastAnswer)+ .takeIf { !it.value.isNaN() } } catch (e: ExpressionError) {- ""+ null+ }+ previewQuantity = quantity+ if (quantity == null || quantity.isDimensionless) {+ unitOptions = emptyList()+ selectedUnit = null+ preview = if (quantity == null) "" else formatResult(quantity.value)+ } else {+ val options = UnitRegistry.unitsFor(quantity.dimension)+ unitOptions = options+ if (selectedUnit !in options) selectedUnit = UnitRegistry.defaultUnitFor(quantity.dimension)+ preview = formatQuantity(quantity, selectedUnit) } } @@ -195,6 +231,55 @@ class CalculatorViewModel : ViewModel(), CalculatorActions, GraphActions { private fun dropMarkersFor(id: Long) = markers.removeAll { id in it.curveIds } + // ---- Units tab (converter) ----+ var converterCategoryIndex by mutableStateOf(0)+ private set+ var converterFromToken by mutableStateOf(UnitRegistry.categories[0].units[0].token)+ private set+ var converterToToken by mutableStateOf(+ UnitRegistry.categories[0].units.getOrElse(1) { UnitRegistry.categories[0].units[0] }.token,+ )+ private set+ var converterValueText by mutableStateOf("1")+ private set++ val unitConverterUiState: UnitConverterUiState+ get() {+ val category = UnitRegistry.categories[converterCategoryIndex]+ return UnitConverterUiState(+ categories = UnitRegistry.categories,+ selectedCategoryIndex = converterCategoryIndex,+ fromToken = converterFromToken,+ toToken = converterToToken,+ inputText = converterValueText,+ outputText = convert(category),+ )+ }++ private fun convert(category: UnitCategory): String {+ val from = category.units.firstOrNull { it.token == converterFromToken } ?: return ""+ val to = category.units.firstOrNull { it.token == converterToToken } ?: return ""+ val value = converterValueText.toDoubleOrNull() ?: return ""+ return formatResult(to.fromBase(from.toBase(value)))+ }++ override fun selectCategory(index: Int) {+ if (index !in UnitRegistry.categories.indices) return+ converterCategoryIndex = index+ val units = UnitRegistry.categories[index].units+ converterFromToken = units[0].token+ converterToToken = units.getOrElse(1) { units[0] }.token+ }++ override fun setFrom(token: String) { converterFromToken = token }+ override fun setTo(token: String) { converterToToken = token }+ override fun setConverterInput(text: String) { converterValueText = text }+ override fun swapUnits() {+ val from = converterFromToken+ converterFromToken = converterToToken+ converterToToken = from+ }+ /** * Samples every visible curve over the current viewport. Drawing and analysis share this * so a marker always lands exactly on the line that was drawn.
calculator/src/main/java/com/vayunmathur/calculator/util/Expression.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/util/Expression.kt b/calculator/src/main/java/com/vayunmathur/calculator/util/Expression.ktindex 1dd325bdec..0db8289494 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/util/Expression.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/util/Expression.kt@@ -51,8 +51,16 @@ class EvalContext(val variable: Double, val angle: AngleMode, val ans: Double) */ class Expression private constructor(private val root: Node) { - /** Evaluate for a given free-variable value, [angle] mode and [ans]. */+ /**+ * Evaluate for a given free-variable value, [angle] mode and [ans], returning the numeric+ * magnitude only. Preserves the graphing path and every dimensionless caller: for a+ * dimensionless expression this is exactly the number, so nothing downstream changes.+ */ fun eval(variable: Double = 0.0, angle: AngleMode = AngleMode.RADIANS, ans: Double = 0.0): Double =+ evalQuantity(variable, angle, ans).value++ /** Evaluate to a full [Quantity], carrying units through the calculation. */+ fun evalQuantity(variable: Double = 0.0, angle: AngleMode = AngleMode.RADIANS, ans: Double = 0.0): Quantity = root.eval(EvalContext(variable, angle, ans)) companion object {@@ -62,19 +70,23 @@ class Expression private constructor(private val root: Node) { // ---- AST ---- internal sealed interface Node {- fun eval(ctx: EvalContext): Double+ fun eval(ctx: EvalContext): Quantity } private class Num(val value: Double) : Node {- override fun eval(ctx: EvalContext) = value+ override fun eval(ctx: EvalContext) = Quantity.scalar(value) } private object Var : Node {- override fun eval(ctx: EvalContext) = ctx.variable+ override fun eval(ctx: EvalContext) = Quantity.scalar(ctx.variable) } private object Ans : Node {- override fun eval(ctx: EvalContext) = ctx.ans+ override fun eval(ctx: EvalContext) = Quantity.scalar(ctx.ans)+ }++ private class UnitNode(val unit: UnitDef) : Node {+ override fun eval(ctx: EvalContext) = Quantity(unit.factorToBase, unit.dimension, unit.offsetK) } private class Neg(val operand: Node) : Node {@@ -82,11 +94,11 @@ class Expression private constructor(private val root: Node) { } private class Fact(val operand: Node) : Node {- override fun eval(ctx: EvalContext) = factorial(operand.eval(ctx))+ override fun eval(ctx: EvalContext) = Quantity.scalar(factorial(operand.eval(ctx).requireScalar("Factorial"))) } private class Binary(val op: Char, val left: Node, val right: Node) : Node {- override fun eval(ctx: EvalContext): Double {+ override fun eval(ctx: EvalContext): Quantity { val a = left.eval(ctx) val b = right.eval(ctx) return when (op) {@@ -102,15 +114,21 @@ class Expression private constructor(private val root: Node) { } private class Call(val name: String, val args: List<Node>) : Node {- override fun eval(ctx: EvalContext): Double {- val a = args.map { it.eval(ctx) }+ override fun eval(ctx: EvalContext): Quantity {+ // `abs` is the one function that keeps its argument's dimension; everything else is+ // defined on plain numbers, so its arguments must be dimensionless.+ if (name == "abs") {+ if (args.size != 1) throw ExpressionError("abs expects 1 argument")+ return args[0].eval(ctx).abs()+ }+ val a = args.map { it.eval(ctx).requireScalar(name) } fun one(): Double { if (a.size != 1) throw ExpressionError("$name expects 1 argument") return a[0] } fun toRad(v: Double) = if (ctx.angle == AngleMode.DEGREES) v * PI / 180.0 else v fun fromRad(v: Double) = if (ctx.angle == AngleMode.DEGREES) v * 180.0 / PI else v- return when (name) {+ val result: Double = when (name) { "sin" -> sin(toRad(one())) "cos" -> cos(toRad(one())) "tan" -> tan(toRad(one()))@@ -132,7 +150,6 @@ class Expression private constructor(private val root: Node) { "ln" -> ln(one()) "log2" -> log2(one()) "log" -> if (a.size == 2) ln(a[1]) / ln(a[0]) else log10(one())- "abs" -> abs(one()) "floor" -> floor(one()) "ceil" -> ceil(one()) "round" -> round(one())@@ -150,6 +167,7 @@ class Expression private constructor(private val root: Node) { "min" -> a.min() else -> throw ExpressionError("Unknown function '$name'") }+ return Quantity.scalar(result) } private fun require2(a: List<Double>) {@@ -302,7 +320,8 @@ class Expression private constructor(private val root: Node) { if (src[pos] == 'θ') { pos++; return Var } val start = pos while (pos < src.length && (src[pos].isLetterOrDigit() || src[pos] == '_')) pos++- val name = src.substring(start, pos).lowercase()+ val raw = src.substring(start, pos)+ val name = raw.lowercase() return when (name) { "x", "t", "theta" -> Var "ans" -> Ans@@ -318,7 +337,10 @@ class Expression private constructor(private val root: Node) { pos++ Call(name, args) } else {- throw ExpressionError("Unknown symbol '$name'")+ // Not a function call: try the unit registry (case-sensitively, so `mm`+ // and `Mm` differ) before giving up.+ val unit = UnitRegistry.parseTokens[raw]+ if (unit != null) UnitNode(unit) else throw ExpressionError("Unknown symbol '$raw'") } } }@@ -336,6 +358,12 @@ class Expression private constructor(private val root: Node) { // ---- Special functions shared by the AST ---- +/** Unwrap a [Quantity] that must be dimensionless, or fail with a clear message. */+private fun Quantity.requireScalar(context: String): Double {+ if (!isDimensionless) throw ExpressionError("$context requires a dimensionless value")+ return value+}+ /** Lanczos approximation of the gamma function (valid across the reals except poles). */ private fun gamma(x: Double): Double { val g = 7.0
calculator/src/main/java/com/vayunmathur/calculator/util/Formatting.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/util/Formatting.kt b/calculator/src/main/java/com/vayunmathur/calculator/util/Formatting.ktindex dff62731b0..f5acac81de 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/util/Formatting.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/util/Formatting.kt@@ -26,3 +26,25 @@ fun formatResult(value: Double): String { rounded.toPlainString() } }++/** The magnitude of [q] expressed in [unit] (handling affine temperature and deltas). */+fun displayValueIn(q: Quantity, unit: UnitDef): Double =+ if (q.dimension == Dimension.TEMPERATURE) {+ if (q.tempOffsetK != null) unit.fromBase(q.value + q.tempOffsetK) // absolute+ else q.value / unit.factorToBase // delta: degree-size only, no offset+ } else {+ unit.fromBase(q.value)+ }++/**+ * Formats a [Quantity] for display, converting it into [unit] and appending a label. A+ * dimensionless quantity (or a null [unit]) is just its number. When [useToken] is set the+ * ASCII parse token and a plain space are used so the string re-parses (for result round-trips);+ * otherwise the pretty [UnitDef.symbol] and a thin space are used for display.+ */+fun formatQuantity(q: Quantity, unit: UnitDef?, useToken: Boolean = false): String {+ if (q.isDimensionless || unit == null) return formatResult(q.value)+ val label = if (useToken) unit.token else unit.symbol+ val separator = if (useToken) " " else "\u202F"+ return formatResult(displayValueIn(q, unit)) + separator + label+}
calculator/src/main/java/com/vayunmathur/calculator/util/Units.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/util/Units.kt b/calculator/src/main/java/com/vayunmathur/calculator/util/Units.ktnew file mode 100644index 0000000000..32c96b567d--- /dev/null+++ b/calculator/src/main/java/com/vayunmathur/calculator/util/Units.kt@@ -0,0 +1,471 @@+package com.vayunmathur.calculator.util++import kotlin.math.PI+import kotlin.math.floor+import kotlin.math.pow++/**+ * A dimensional-analysis layer that lets the expression engine carry units through a+ * calculation (e.g. `5m + 2ft`) and lets the Units tab convert between them.+ *+ * The model is coherent-SI at heart: every [Quantity] holds its magnitude in coherent base+ * units (metre, kilogram, second, kelvin, …), so addition just checks the [Dimension]s match+ * and multiplication just multiplies. Temperatures are the one affine exception and are+ * documented on [Quantity].+ */++/** The seven SI base dimensions, plus INFORMATION so bytes/bits are first-class. */+enum class BaseDim { LENGTH, MASS, TIME, CURRENT, TEMPERATURE, AMOUNT, LUMINOUS, INFORMATION }++/**+ * A product of base dimensions with integer exponents (so speed is `LENGTH·TIME⁻¹`). Zero+ * exponents are dropped, so structural [equals] doubles as dimensional compatibility.+ */+class Dimension private constructor(val exponents: Map<BaseDim, Int>) {++ val isDimensionless: Boolean get() = exponents.isEmpty()++ operator fun times(other: Dimension) = of(merge(exponents, other.exponents, 1))+ operator fun div(other: Dimension) = of(merge(exponents, other.exponents, -1))+ fun pow(n: Int) = of(exponents.mapValues { it.value * n })++ override fun equals(other: Any?) = other is Dimension && other.exponents == exponents+ override fun hashCode() = exponents.hashCode()+ override fun toString() =+ if (isDimensionless) "1" else exponents.entries.joinToString("·") { "${it.key}^${it.value}" }++ companion object {+ val NONE = Dimension(emptyMap())++ fun of(map: Map<BaseDim, Int>) = Dimension(map.filterValues { it != 0 })+ private fun base(d: BaseDim) = of(mapOf(d to 1))++ private fun merge(a: Map<BaseDim, Int>, b: Map<BaseDim, Int>, sign: Int): Map<BaseDim, Int> {+ val out = a.toMutableMap()+ for ((k, v) in b) out[k] = (out[k] ?: 0) + sign * v+ return out+ }++ // Base dimensions.+ val LENGTH = base(BaseDim.LENGTH)+ val MASS = base(BaseDim.MASS)+ val TIME = base(BaseDim.TIME)+ val CURRENT = base(BaseDim.CURRENT)+ val TEMPERATURE = base(BaseDim.TEMPERATURE)+ val AMOUNT = base(BaseDim.AMOUNT)+ val INFORMATION = base(BaseDim.INFORMATION)++ // Common derived dimensions.+ val AREA = LENGTH.pow(2)+ val VOLUME = LENGTH.pow(3)+ val SPEED = LENGTH / TIME+ val FREQUENCY = TIME.pow(-1)+ val FORCE = MASS * LENGTH / TIME.pow(2)+ val ENERGY = FORCE * LENGTH+ val POWER = ENERGY / TIME+ val PRESSURE = FORCE / AREA+ val CHARGE = CURRENT * TIME+ val VOLTAGE = POWER / CURRENT+ val RESISTANCE = VOLTAGE / CURRENT+ val CAPACITANCE = CHARGE / VOLTAGE+ }+}++/**+ * A magnitude with a [dimension], as produced by evaluating an expression node.+ *+ * [value] is the linear magnitude in coherent base units (m, kg, s, …). Temperature is affine+ * and gets special treatment: [value] is a **kelvin-sized delta** and [tempOffsetK] distinguishes+ * an *absolute* temperature (`tempOffsetK != null`, absolute kelvin = `value + tempOffsetK`) from+ * a *delta* (`tempOffsetK == null`).+ *+ * The user's rule for `+`/`-` chains of temperatures (example `200k - 5c → 195K`): the first+ * temperature is absolute; each one added/subtracted onto it contributes only its degree-size+ * (its [value]), so `5c` behaves like a 5 K offset rather than 278.15 K.+ */+class Quantity(+ val value: Double,+ val dimension: Dimension,+ val tempOffsetK: Double? = null,+) {+ val isDimensionless: Boolean get() = dimension.isDimensionless+ private val isTemperature: Boolean get() = dimension == Dimension.TEMPERATURE++ operator fun unaryMinus() = Quantity(-value, dimension, tempOffsetK)++ operator fun plus(other: Quantity) = addOrSub(other, 1.0)+ operator fun minus(other: Quantity) = addOrSub(other, -1.0)++ private fun addOrSub(other: Quantity, sign: Double): Quantity {+ if (dimension != other.dimension) {+ throw ExpressionError("Cannot add or subtract incompatible units")+ }+ if (isTemperature) {+ // The right operand always collapses to its degree-size (a delta).+ val rightDelta = other.value+ return if (tempOffsetK != null) {+ // Absolute left: fold into absolute kelvin, then re-normalise (offset 0).+ Quantity((value + tempOffsetK) + sign * rightDelta, Dimension.TEMPERATURE, 0.0)+ } else {+ Quantity(value + sign * rightDelta, Dimension.TEMPERATURE, null)+ }+ }+ return Quantity(value + sign * other.value, dimension, null)+ }++ operator fun times(other: Quantity): Quantity {+ // A dimensionless scalar scales the other operand and preserves its temperature offset,+ // which is what turns `20 * celsius` into an absolute 293.15 K.+ if (isDimensionless && tempOffsetK == null) {+ return Quantity(value * other.value, other.dimension, other.tempOffsetK)+ }+ if (other.isDimensionless && other.tempOffsetK == null) {+ return Quantity(value * other.value, dimension, tempOffsetK)+ }+ // Two dimensional operands: combine dimensions; any temperature collapses to a delta.+ return Quantity(value * other.value, dimension * other.dimension, null)+ }++ operator fun div(other: Quantity): Quantity {+ if (other.isDimensionless && other.tempOffsetK == null) {+ return Quantity(value / other.value, dimension, tempOffsetK)+ }+ return Quantity(value / other.value, dimension / other.dimension, null)+ }++ operator fun rem(other: Quantity): Quantity {+ if (!other.isDimensionless && dimension != other.dimension) {+ throw ExpressionError("Cannot take the remainder of incompatible units")+ }+ return Quantity(value % other.value, dimension, null)+ }++ fun pow(other: Quantity): Quantity {+ if (!other.isDimensionless) throw ExpressionError("Exponent must be dimensionless")+ if (isDimensionless) return Quantity(value.pow(other.value), Dimension.NONE)+ val n = other.value+ if (n != floor(n)) throw ExpressionError("Cannot raise a unit to a non-integer power")+ return Quantity(value.pow(n), dimension.pow(n.toInt()))+ }++ fun abs(): Quantity = Quantity(kotlin.math.abs(value), dimension, tempOffsetK)++ companion object {+ fun scalar(value: Double) = Quantity(value, Dimension.NONE)+ }+}++/**+ * One unit the user can pick. [token] is the ASCII spelling the parser understands (inserted+ * by the keypad picker, e.g. `degC`, `um`, `ohm`); [symbol] is the pretty display form+ * (`°C`, `µm`, `Ω`); [aliases] are extra spellings the parser also accepts (e.g. `c` for `degC`).+ *+ * [factorToBase] scales a magnitude to coherent base units. [offsetK] is set only for affine+ * temperature units and is the absolute kelvin at zero of the unit (0 for K, 273.15 for °C).+ */+class UnitDef(+ val token: String,+ val symbol: String,+ val name: String,+ val dimension: Dimension,+ val factorToBase: Double,+ val offsetK: Double? = null,+ val aliases: List<String> = emptyList(),+) {+ /** Magnitude in this unit → coherent base value (absolute kelvin for temperatures). */+ fun toBase(magnitude: Double): Double = magnitude * factorToBase + (offsetK ?: 0.0)++ /** Coherent base value → magnitude in this unit. */+ fun fromBase(baseValue: Double): Double = (baseValue - (offsetK ?: 0.0)) / factorToBase+}++/** A named group of units, shown as one tab in the converter. */+class UnitCategory(+ val name: String,+ val units: List<UnitDef>,+ /** Whether these units are also usable inside equations (angle units are converter-only). */+ val inEquations: Boolean = true,+)++/**+ * The single source of unit truth: the converter's [categories], the parser's [parseTokens],+ * and the output-selector's [unitsFor].+ */+object UnitRegistry {++ // Names the engine reserves for variables/constants/ans; a unit token must never shadow one.+ private val RESERVED = setOf("e", "t", "x", "theta", "pi", "tau", "phi", "ans")++ private val FAHRENHEIT_OFFSET_K = 273.15 - 32.0 * 5.0 / 9.0++ val categories: List<UnitCategory> = buildCategories()++ /** Case-sensitive lookup for the parser, keyed by every token and alias. */+ val parseTokens: Map<String, UnitDef> = buildMap {+ for (category in categories) {+ if (!category.inEquations) continue+ for (unit in category.units) {+ for (key in listOf(unit.token) + unit.aliases) {+ if (key.lowercase() in RESERVED) continue+ putIfAbsent(key, unit)+ }+ }+ }+ }++ /** Units sharing [dimension], to populate the output-unit selector. */+ fun unitsFor(dimension: Dimension): List<UnitDef> =+ categories.flatMap { it.units }.filter { it.dimension == dimension }++ /** A sensible default output unit for [dimension]: the coherent base if present. */+ fun defaultUnitFor(dimension: Dimension): UnitDef? {+ val options = unitsFor(dimension)+ return options.firstOrNull { it.factorToBase == 1.0 && (it.offsetK == null || it.offsetK == 0.0) }+ ?: options.firstOrNull()+ }++ private fun buildCategories(): List<UnitCategory> {+ val d = Dimension+ return listOf(+ UnitCategory(+ "Length",+ listOf(+ UnitDef("km", "km", "Kilometre", d.LENGTH, 1000.0),+ UnitDef("m", "m", "Metre", d.LENGTH, 1.0),+ UnitDef("cm", "cm", "Centimetre", d.LENGTH, 0.01),+ UnitDef("mm", "mm", "Millimetre", d.LENGTH, 0.001),+ UnitDef("um", "µm", "Micrometre", d.LENGTH, 1e-6),+ UnitDef("nm", "nm", "Nanometre", d.LENGTH, 1e-9),+ UnitDef("mi", "mi", "Mile", d.LENGTH, 1609.344),+ UnitDef("yd", "yd", "Yard", d.LENGTH, 0.9144),+ UnitDef("ft", "ft", "Foot", d.LENGTH, 0.3048),+ UnitDef("in", "in", "Inch", d.LENGTH, 0.0254),+ UnitDef("nmi", "nmi", "Nautical mile", d.LENGTH, 1852.0),+ ),+ ),+ UnitCategory(+ "Mass",+ listOf(+ UnitDef("tonne", "t", "Tonne", d.MASS, 1000.0),+ UnitDef("kg", "kg", "Kilogram", d.MASS, 1.0),+ UnitDef("g", "g", "Gram", d.MASS, 0.001),+ UnitDef("mg", "mg", "Milligram", d.MASS, 1e-6),+ UnitDef("ug", "µg", "Microgram", d.MASS, 1e-9),+ UnitDef("lb", "lb", "Pound", d.MASS, 0.45359237),+ UnitDef("oz", "oz", "Ounce", d.MASS, 0.028349523125),+ UnitDef("st", "st", "Stone", d.MASS, 6.35029318),+ ),+ ),+ UnitCategory(+ "Time",+ listOf(+ UnitDef("ns", "ns", "Nanosecond", d.TIME, 1e-9),+ UnitDef("us", "µs", "Microsecond", d.TIME, 1e-6),+ UnitDef("ms", "ms", "Millisecond", d.TIME, 0.001),+ UnitDef("s", "s", "Second", d.TIME, 1.0),+ UnitDef("min", "min", "Minute", d.TIME, 60.0),+ UnitDef("h", "h", "Hour", d.TIME, 3600.0),+ UnitDef("day", "day", "Day", d.TIME, 86400.0),+ UnitDef("wk", "wk", "Week", d.TIME, 604800.0),+ UnitDef("yr", "yr", "Year", d.TIME, 31557600.0),+ ),+ ),+ UnitCategory(+ "Temperature",+ listOf(+ UnitDef("K", "K", "Kelvin", d.TEMPERATURE, 1.0, offsetK = 0.0, aliases = listOf("k")),+ UnitDef("degC", "°C", "Celsius", d.TEMPERATURE, 1.0, offsetK = 273.15, aliases = listOf("c")),+ UnitDef("degF", "°F", "Fahrenheit", d.TEMPERATURE, 5.0 / 9.0, offsetK = FAHRENHEIT_OFFSET_K),+ UnitDef("degR", "°R", "Rankine", d.TEMPERATURE, 5.0 / 9.0, offsetK = 0.0),+ ),+ ),+ UnitCategory(+ "Area",+ listOf(+ UnitDef("km2", "km²", "Square kilometre", d.AREA, 1e6),+ UnitDef("m2", "m²", "Square metre", d.AREA, 1.0),+ UnitDef("cm2", "cm²", "Square centimetre", d.AREA, 1e-4),+ UnitDef("mm2", "mm²", "Square millimetre", d.AREA, 1e-6),+ UnitDef("ha", "ha", "Hectare", d.AREA, 10000.0),+ UnitDef("acre", "acre", "Acre", d.AREA, 4046.8564224),+ UnitDef("ft2", "ft²", "Square foot", d.AREA, 0.09290304),+ UnitDef("in2", "in²", "Square inch", d.AREA, 0.00064516),+ UnitDef("mi2", "mi²", "Square mile", d.AREA, 2589988.110336),+ ),+ ),+ UnitCategory(+ "Volume",+ listOf(+ UnitDef("m3", "m³", "Cubic metre", d.VOLUME, 1.0),+ UnitDef("cm3", "cm³", "Cubic centimetre", d.VOLUME, 1e-6),+ UnitDef("L", "L", "Litre", d.VOLUME, 0.001, aliases = listOf("l")),+ UnitDef("mL", "mL", "Millilitre", d.VOLUME, 1e-6, aliases = listOf("ml")),+ UnitDef("gal", "gal", "Gallon (US)", d.VOLUME, 0.003785411784),+ UnitDef("qt", "qt", "Quart (US)", d.VOLUME, 9.46352946e-4),+ UnitDef("pt", "pt", "Pint (US)", d.VOLUME, 4.73176473e-4),+ UnitDef("cup", "cup", "Cup (US)", d.VOLUME, 2.365882365e-4),+ UnitDef("floz", "fl oz", "Fluid ounce (US)", d.VOLUME, 2.95735295625e-5),+ UnitDef("ft3", "ft³", "Cubic foot", d.VOLUME, 0.028316846592),+ UnitDef("in3", "in³", "Cubic inch", d.VOLUME, 1.6387064e-5),+ ),+ ),+ UnitCategory(+ "Speed",+ listOf(+ UnitDef("mps", "m/s", "Metres per second", d.SPEED, 1.0),+ UnitDef("kmh", "km/h", "Kilometres per hour", d.SPEED, 1.0 / 3.6),+ UnitDef("mph", "mph", "Miles per hour", d.SPEED, 0.44704),+ UnitDef("fps", "ft/s", "Feet per second", d.SPEED, 0.3048),+ UnitDef("kn", "kn", "Knot", d.SPEED, 0.514444),+ ),+ ),+ UnitCategory(+ "Data",+ listOf(+ UnitDef("bit", "bit", "Bit", d.INFORMATION, 1.0),+ UnitDef("B", "B", "Byte", d.INFORMATION, 8.0),+ UnitDef("kB", "kB", "Kilobyte", d.INFORMATION, 8e3),+ UnitDef("MB", "MB", "Megabyte", d.INFORMATION, 8e6),+ UnitDef("GB", "GB", "Gigabyte", d.INFORMATION, 8e9),+ UnitDef("TB", "TB", "Terabyte", d.INFORMATION, 8e12),+ UnitDef("KiB", "KiB", "Kibibyte", d.INFORMATION, 8.0 * 1024),+ UnitDef("MiB", "MiB", "Mebibyte", d.INFORMATION, 8.0 * 1024 * 1024),+ UnitDef("GiB", "GiB", "Gibibyte", d.INFORMATION, 8.0 * 1024 * 1024 * 1024),+ UnitDef("TiB", "TiB", "Tebibyte", d.INFORMATION, 8.0 * 1024 * 1024 * 1024 * 1024),+ UnitDef("kbit", "kbit", "Kilobit", d.INFORMATION, 1e3),+ UnitDef("Mbit", "Mbit", "Megabit", d.INFORMATION, 1e6),+ UnitDef("Gbit", "Gbit", "Gigabit", d.INFORMATION, 1e9),+ ),+ ),+ UnitCategory(+ "Energy",+ listOf(+ UnitDef("J", "J", "Joule", d.ENERGY, 1.0),+ UnitDef("kJ", "kJ", "Kilojoule", d.ENERGY, 1000.0),+ UnitDef("MJ", "MJ", "Megajoule", d.ENERGY, 1e6),+ UnitDef("cal", "cal", "Calorie", d.ENERGY, 4.184),+ UnitDef("kcal", "kcal", "Kilocalorie", d.ENERGY, 4184.0),+ UnitDef("Wh", "Wh", "Watt-hour", d.ENERGY, 3600.0),+ UnitDef("kWh", "kWh", "Kilowatt-hour", d.ENERGY, 3.6e6),+ UnitDef("eV", "eV", "Electronvolt", d.ENERGY, 1.602176634e-19),+ UnitDef("BTU", "BTU", "British thermal unit", d.ENERGY, 1055.05585262),+ UnitDef("erg", "erg", "Erg", d.ENERGY, 1e-7),+ ),+ ),+ UnitCategory(+ "Power",+ listOf(+ UnitDef("mW", "mW", "Milliwatt", d.POWER, 0.001),+ UnitDef("W", "W", "Watt", d.POWER, 1.0),+ UnitDef("kW", "kW", "Kilowatt", d.POWER, 1000.0),+ UnitDef("MW", "MW", "Megawatt", d.POWER, 1e6),+ UnitDef("GW", "GW", "Gigawatt", d.POWER, 1e9),+ UnitDef("hp", "hp", "Horsepower", d.POWER, 745.6998715823),+ ),+ ),+ UnitCategory(+ "Pressure",+ listOf(+ UnitDef("Pa", "Pa", "Pascal", d.PRESSURE, 1.0),+ UnitDef("hPa", "hPa", "Hectopascal", d.PRESSURE, 100.0),+ UnitDef("kPa", "kPa", "Kilopascal", d.PRESSURE, 1000.0),+ UnitDef("MPa", "MPa", "Megapascal", d.PRESSURE, 1e6),+ UnitDef("bar", "bar", "Bar", d.PRESSURE, 1e5),+ UnitDef("mbar", "mbar", "Millibar", d.PRESSURE, 100.0),+ UnitDef("atm", "atm", "Atmosphere", d.PRESSURE, 101325.0),+ UnitDef("psi", "psi", "Pound per square inch", d.PRESSURE, 6894.757293168),+ UnitDef("mmHg", "mmHg", "Millimetre of mercury", d.PRESSURE, 133.322387415),+ UnitDef("torr", "torr", "Torr", d.PRESSURE, 133.32236842105263),+ ),+ ),+ UnitCategory(+ "Force",+ listOf(+ UnitDef("N", "N", "Newton", d.FORCE, 1.0),+ UnitDef("kN", "kN", "Kilonewton", d.FORCE, 1000.0),+ UnitDef("mN", "mN", "Millinewton", d.FORCE, 0.001),+ UnitDef("lbf", "lbf", "Pound-force", d.FORCE, 4.4482216152605),+ UnitDef("kgf", "kgf", "Kilogram-force", d.FORCE, 9.80665),+ UnitDef("dyn", "dyn", "Dyne", d.FORCE, 1e-5),+ ),+ ),+ UnitCategory(+ "Frequency",+ listOf(+ UnitDef("Hz", "Hz", "Hertz", d.FREQUENCY, 1.0),+ UnitDef("kHz", "kHz", "Kilohertz", d.FREQUENCY, 1000.0),+ UnitDef("MHz", "MHz", "Megahertz", d.FREQUENCY, 1e6),+ UnitDef("GHz", "GHz", "Gigahertz", d.FREQUENCY, 1e9),+ ),+ ),+ UnitCategory(+ "Current",+ listOf(+ UnitDef("uA", "µA", "Microampere", d.CURRENT, 1e-6),+ UnitDef("mA", "mA", "Milliampere", d.CURRENT, 0.001),+ UnitDef("A", "A", "Ampere", d.CURRENT, 1.0),+ UnitDef("kA", "kA", "Kiloampere", d.CURRENT, 1000.0),+ ),+ ),+ UnitCategory(+ "Voltage",+ listOf(+ UnitDef("uV", "µV", "Microvolt", d.VOLTAGE, 1e-6),+ UnitDef("mV", "mV", "Millivolt", d.VOLTAGE, 0.001),+ UnitDef("V", "V", "Volt", d.VOLTAGE, 1.0),+ UnitDef("kV", "kV", "Kilovolt", d.VOLTAGE, 1000.0),+ ),+ ),+ UnitCategory(+ "Resistance",+ listOf(+ UnitDef("mohm", "mΩ", "Milliohm", d.RESISTANCE, 0.001),+ UnitDef("ohm", "Ω", "Ohm", d.RESISTANCE, 1.0),+ UnitDef("kohm", "kΩ", "Kiloohm", d.RESISTANCE, 1000.0),+ UnitDef("Mohm", "MΩ", "Megaohm", d.RESISTANCE, 1e6),+ ),+ ),+ UnitCategory(+ "Charge",+ listOf(+ UnitDef("uC", "µC", "Microcoulomb", d.CHARGE, 1e-6),+ UnitDef("mC", "mC", "Millicoulomb", d.CHARGE, 0.001),+ UnitDef("C", "C", "Coulomb", d.CHARGE, 1.0),+ UnitDef("mAh", "mAh", "Milliamp-hour", d.CHARGE, 3.6),+ UnitDef("Ah", "Ah", "Amp-hour", d.CHARGE, 3600.0),+ ),+ ),+ UnitCategory(+ "Capacitance",+ listOf(+ UnitDef("pF", "pF", "Picofarad", d.CAPACITANCE, 1e-12),+ UnitDef("nF", "nF", "Nanofarad", d.CAPACITANCE, 1e-9),+ UnitDef("uF", "µF", "Microfarad", d.CAPACITANCE, 1e-6),+ UnitDef("mF", "mF", "Millifarad", d.CAPACITANCE, 0.001),+ UnitDef("F", "F", "Farad", d.CAPACITANCE, 1.0),+ ),+ ),+ UnitCategory(+ "Amount",+ listOf(+ UnitDef("umol", "µmol", "Micromole", d.AMOUNT, 1e-6),+ UnitDef("mmol", "mmol", "Millimole", d.AMOUNT, 0.001),+ UnitDef("mol", "mol", "Mole", d.AMOUNT, 1.0),+ UnitDef("kmol", "kmol", "Kilomole", d.AMOUNT, 1000.0),+ ),+ ),+ UnitCategory(+ "Angle",+ listOf(+ UnitDef("rad", "rad", "Radian", Dimension.NONE, 1.0),+ UnitDef("deg", "°", "Degree", Dimension.NONE, PI / 180.0),+ UnitDef("grad", "grad", "Gradian", Dimension.NONE, PI / 200.0),+ UnitDef("arcmin", "′", "Arcminute", Dimension.NONE, PI / 10800.0),+ UnitDef("arcsec", "″", "Arcsecond", Dimension.NONE, PI / 648000.0),+ UnitDef("rev", "rev", "Revolution", Dimension.NONE, 2 * PI),+ ),+ inEquations = false,+ ),+ )+ }+}
calculator/src/main/res/values/strings.xml
diff --git a/calculator/src/main/res/values/strings.xml b/calculator/src/main/res/values/strings.xmlindex add5cdfa1f..e032a81a34 100644--- a/calculator/src/main/res/values/strings.xml+++ b/calculator/src/main/res/values/strings.xml@@ -16,4 +16,20 @@ <string name="feature_maximum">maximum</string> <!-- Graph: label on a marker where two curves cross. Lowercase noun, shown as "intersection (1, 1)". --> <string name="feature_intersection">intersection</string>+ <!-- Bottom navigation label for the unit converter tab. -->+ <string name="units">Units</string>+ <!-- Calculator: content description / title for the unit picker that inserts a unit into the expression. -->+ <string name="insert_unit">Insert unit</string>+ <!-- Calculator: label before the dropdown that chooses which unit the result is shown in. -->+ <string name="convert_to">Convert to</string>+ <!-- Converter: label for the field holding the value being converted. -->+ <string name="converter_value">Value</string>+ <!-- Converter: label above the unit the value is converted from. -->+ <string name="converter_from">From</string>+ <!-- Converter: label above the unit the value is converted to. -->+ <string name="converter_to">To</string>+ <!-- Converter: label above the converted result. -->+ <string name="converter_result">Result</string>+ <!-- Converter: content description for the button that swaps the from and to units. -->+ <string name="converter_swap">Swap units</string> </resources>
calculator/src/screenshotTest/kotlin/com/vayunmathur/calculator/ui/MetadataPreviews.kt
diff --git a/calculator/src/screenshotTest/kotlin/com/vayunmathur/calculator/ui/MetadataPreviews.kt b/calculator/src/screenshotTest/kotlin/com/vayunmathur/calculator/ui/MetadataPreviews.ktindex 41ab2f1671..860a842084 100644--- a/calculator/src/screenshotTest/kotlin/com/vayunmathur/calculator/ui/MetadataPreviews.kt+++ b/calculator/src/screenshotTest/kotlin/com/vayunmathur/calculator/ui/MetadataPreviews.kt@@ -15,6 +15,9 @@ import com.vayunmathur.calculator.util.GraphPoint import com.vayunmathur.calculator.util.GraphUiState import com.vayunmathur.calculator.util.GraphViewport import com.vayunmathur.calculator.util.HistoryEntry+import com.vayunmathur.calculator.util.UnitConverterActions+import com.vayunmathur.calculator.util.UnitConverterUiState+import com.vayunmathur.calculator.util.UnitRegistry import com.vayunmathur.library.ui.DynamicTheme /** Phone-shaped, roughly 1080x2340 at xxhdpi — comfortably above the F-Droid minimum. */@@ -116,4 +119,23 @@ class MetadataPreviews { ) } }++ @PreviewTest+ @Preview(name = "4-units", device = PHONE, showSystemUi = true)+ @Composable+ fun Preview4Units() {+ DynamicTheme(darkTheme = true) {+ UnitConverterScreen(+ state = UnitConverterUiState(+ categories = UnitRegistry.categories,+ selectedCategoryIndex = 3, // Temperature+ fromToken = "degC",+ toToken = "degF",+ inputText = "100",+ outputText = "212",+ ),+ actions = UnitConverterActions.Noop,+ )+ }+ } }
calculator/src/test/java/com/vayunmathur/calculator/util/UnitsTest.kt
diff --git a/calculator/src/test/java/com/vayunmathur/calculator/util/UnitsTest.kt b/calculator/src/test/java/com/vayunmathur/calculator/util/UnitsTest.ktnew file mode 100644index 0000000000..db2c73fb68--- /dev/null+++ b/calculator/src/test/java/com/vayunmathur/calculator/util/UnitsTest.kt@@ -0,0 +1,202 @@+package com.vayunmathur.calculator.util++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertTrue++class UnitsTest {++ private fun q(src: String, x: Double = 0.0, angle: AngleMode = AngleMode.RADIANS): Quantity =+ Expression.parse(src).evalQuantity(x, angle)++ private fun unit(token: String): UnitDef =+ UnitRegistry.parseTokens[token] ?: error("no unit '$token'")++ private fun assertClose(expected: Double, actual: Double, tolerance: Double = 1e-6) {+ assertTrue(+ kotlin.math.abs(expected - actual) <= tolerance,+ "expected $expected but was $actual",+ )+ }++ // ---- dimension algebra ----++ @Test+ fun derivedDimensionsComposeFromBaseDimensions() {+ assertEquals(Dimension.AREA, Dimension.LENGTH * Dimension.LENGTH)+ assertEquals(Dimension.VOLUME, Dimension.LENGTH.pow(3))+ assertEquals(Dimension.SPEED, Dimension.LENGTH / Dimension.TIME)+ assertEquals(Dimension.NONE, Dimension.LENGTH / Dimension.LENGTH)+ assertTrue(Dimension.NONE.isDimensionless)+ assertTrue((Dimension.LENGTH / Dimension.LENGTH).isDimensionless)+ }++ @Test+ fun dimensionEqualityIgnoresConstructionOrder() {+ val force1 = Dimension.MASS * Dimension.LENGTH / Dimension.TIME.pow(2)+ val force2 = Dimension.LENGTH / Dimension.TIME * Dimension.MASS / Dimension.TIME+ assertEquals(force1, force2)+ assertEquals(Dimension.FORCE, force1)+ }++ // ---- linear conversions ----++ @Test+ fun addingLengthsInDifferentUnitsSharesADimension() {+ val r = q("5m + 2ft")+ assertEquals(Dimension.LENGTH, r.dimension)+ assertClose(5.6096, r.value) // base metres+ assertClose(560.96, unit("cm").fromBase(r.value)) // shown in cm+ }++ @Test+ fun massConversion() {+ assertClose(1.0, unit("lb").fromBase(q("0.45359237kg").value))+ }++ @Test+ fun timeConversion() {+ assertEquals(Dimension.TIME, q("1h").dimension)+ assertClose(3600.0, q("1h").value)+ }++ @Test+ fun areaVolumeSpeedDataEnergyPressureForceSamples() {+ assertEquals(Dimension.AREA, q("5m^2").dimension)+ assertClose(5.0, q("5m^2").value)++ assertEquals(Dimension.VOLUME, q("2L").dimension)+ assertClose(0.002, q("2L").value)++ assertEquals(Dimension.SPEED, q("36kmh").dimension)+ assertClose(10.0, q("36kmh").value)++ assertEquals(Dimension.INFORMATION, q("1B").dimension)+ assertClose(8.0, q("1B").value) // one byte = 8 bits+ assertClose(1024.0, unit("B").fromBase(q("1KiB").value))++ assertEquals(Dimension.ENERGY, q("1kWh").dimension)+ assertClose(3.6e6, q("1kWh").value)++ assertEquals(Dimension.PRESSURE, q("1atm").dimension)+ assertClose(101325.0, q("1atm").value)++ assertEquals(Dimension.FORCE, q("1N").dimension)+ assertClose(1.0, q("1N").value)+ }++ @Test+ fun multiplyingUnitsProducesADerivedDimension() {+ // force × length = energy+ val r = q("2N * 3m")+ assertEquals(Dimension.ENERGY, r.dimension)+ assertClose(6.0, r.value)+ }++ // ---- temperature ----++ @Test+ fun standaloneTemperatureIsAbsolute() {+ val r = q("20c")+ assertEquals(Dimension.TEMPERATURE, r.dimension)+ assertTrue(r.tempOffsetK != null, "standalone temperature should be absolute")+ assertClose(293.15, displayValueIn(r, unit("K")))+ assertClose(68.0, displayValueIn(r, unit("degF")))+ }++ @Test+ fun firstTemperatureIsAbsoluteAndTheRestAreDeltas() {+ // The user's rule: 200k - 5c -> 195K.+ val r = q("200k - 5c")+ assertEquals(Dimension.TEMPERATURE, r.dimension)+ assertTrue(r.tempOffsetK != null)+ assertClose(195.0, displayValueIn(r, unit("K")))+ }++ @Test+ fun addingTwoCelsiusValuesAddsDegreeSizes() {+ val r = q("5c + 3c")+ assertClose(8.0, displayValueIn(r, unit("degC")))+ }++ // ---- error cases ----++ @Test+ fun addingIncompatibleUnitsFails() {+ assertFailsWith<ExpressionError> { q("1m + 1kg") }+ }++ @Test+ fun transcendentalFunctionsRejectDimensionalArguments() {+ assertFailsWith<ExpressionError> { q("sin(1m)") }+ assertFailsWith<ExpressionError> { q("ln(2kg)") }+ }++ @Test+ fun nonIntegerPowerOfADimensionalBaseFails() {+ assertFailsWith<ExpressionError> { q("m^0.5") }+ }++ @Test+ fun absKeepsItsDimension() {+ val r = q("|(-3)m|")+ assertEquals(Dimension.LENGTH, r.dimension)+ assertClose(3.0, r.value)+ }++ // ---- parser disambiguation ----++ @Test+ fun functionCallsAndUnitsWithTheSameNameCoexist() {+ // min(...) is the function; 5min is five minutes.+ assertClose(2.0, q("min(2,3)").value)+ assertTrue(q("min(2,3)").isDimensionless)++ val fiveMinutes = q("5min")+ assertEquals(Dimension.TIME, fiveMinutes.dimension)+ assertClose(300.0, fiveMinutes.value)+ assertClose(5.0, unit("min").fromBase(fiveMinutes.value))+ }++ @Test+ fun lowercaseEIsStillEulersConstant() {+ assertClose(2 * kotlin.math.E, q("2e").value)+ assertTrue(q("2e").isDimensionless)+ }++ @Test+ fun xIsStillTheFreeVariable() {+ assertClose(4.0, q("x", x = 4.0).value)+ assertTrue(q("x", x = 4.0).isDimensionless)+ }++ @Test+ fun caseDistinguishesUnits() {+ // Lowercase c is Celsius (temperature); uppercase C is coulomb (charge).+ assertEquals(Dimension.TEMPERATURE, q("5c").dimension)+ assertEquals(Dimension.CHARGE, q("5C").dimension)+ // Lowercase mm is millimetre; the two never collide because lookup is case-sensitive.+ assertClose(0.001, q("1mm").value)+ }++ // ---- converter path ----++ @Test+ fun converterAffineTemperatureRoundTrips() {+ val c = unit("degC")+ val f = unit("degF")+ // 100 °C -> 212 °F+ assertClose(212.0, f.fromBase(c.toBase(100.0)))+ // and back+ assertClose(100.0, c.fromBase(f.toBase(212.0)))+ }++ @Test+ fun formatQuantityAppendsSymbolAndTokenForms() {+ val r = q("5m + 2ft")+ assertEquals("560.96\u202Fcm", formatQuantity(r, unit("cm")))+ assertEquals("560.96 cm", formatQuantity(r, unit("cm"), useToken = true))+ assertEquals("5", formatQuantity(Quantity.scalar(5.0), null))+ }+}