Modern Apps git

← Modern-Apps.git

calculator: add live currency converter tab

Commit
6e963cb3a44b54ab9ef0a93e467e3d000f15e010
Author
Vayun Mathur <[email protected]>
When
2026-08-14 03:15 UTC (3 months ago)
Parents
57362d0

Diff

calculator/build.gradle.kts
diff --git a/calculator/build.gradle.kts b/calculator/build.gradle.ktsindex c0eca304d6..2de28927b7 100644--- a/calculator/build.gradle.kts+++ b/calculator/build.gradle.kts@@ -17,4 +17,6 @@ android {  dependencies {     implementation(libs.androidx.datastore.preferences)+    // Live currency exchange rates fetched from api.vayunmathur.com via the shared client.+    implementation(project(":library:network")) }
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 bd69b3a080..057687756a 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/MainActivity.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/MainActivity.kt@@ -11,6 +11,8 @@ 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.network.NetworkClient+import com.vayunmathur.library.network.TrustBundle import com.vayunmathur.library.ui.IconCalculate import com.vayunmathur.library.ui.IconFunctions import com.vayunmathur.library.ui.IconRuler@@ -26,6 +28,8 @@ class MainActivity : ComponentActivity() {      override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)+        // FIRST_PARTY covers api.vayunmathur.com, where the currency-rate proxy lives.+        NetworkClient.init(this, TrustBundle.FIRST_PARTY)         enableEdgeToEdge()         setContent {             DynamicTheme {
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.ktindex d2727a078c..360d744d97 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/ui/UnitConverterPage.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/ui/UnitConverterPage.kt@@ -27,6 +27,8 @@ 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.Button+import com.vayunmathur.library.ui.CircularProgressIndicator import com.vayunmathur.library.ui.DropdownMenu import com.vayunmathur.library.ui.DropdownMenuItem import com.vayunmathur.library.ui.FilledTonalIconButton@@ -68,52 +70,60 @@ fun UnitConverterScreen(state: UnitConverterUiState, actions: UnitConverterActio                 }             }             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(),+                if (state.isCurrencyCategory && category.units.isEmpty()) {+                    CurrencyStatus(+                        loading = state.currencyLoading,+                        error = state.currencyError,+                        onRetry = actions::retryCurrency,                     )-                    Row(verticalAlignment = Alignment.Bottom) {-                        LabeledUnitDropdown(-                            label = stringResource(R.string.converter_from),-                            units = category.units,-                            selectedToken = state.fromToken,-                            onSelect = actions::setFrom,-                            modifier = Modifier.weight(1f),+                } else {+                    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(),                         )-                        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,+                        Row(verticalAlignment = Alignment.Bottom) {+                            LabeledUnitDropdown(+                                label = stringResource(R.string.converter_from),+                                units = category.units,+                                selectedToken = state.fromToken,+                                onSelect = actions::setFrom,+                                modifier = Modifier.weight(1f),                             )-                            Text(-                                if (state.outputText.isEmpty()) "—" else "${state.outputText}\u202F$toSymbol",-                                fontSize = 28.sp,-                                maxLines = 1,+                            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,+                                )+                            }+                        }                     }                 }             }@@ -121,6 +131,33 @@ fun UnitConverterScreen(state: UnitConverterUiState, actions: UnitConverterActio     } } +/**+ * The Currency tab's placeholder while it has no units yet: a spinner during the fetch, or an+ * error with a retry button if it failed.+ */+@Composable+private fun CurrencyStatus(loading: Boolean, error: String?, onRetry: () -> Unit) {+    Column(+        Modifier.fillMaxWidth().padding(Spacing.xl),+        horizontalAlignment = Alignment.CenterHorizontally,+        verticalArrangement = Arrangement.spacedBy(Spacing.md),+    ) {+        if (loading) {+            CircularProgressIndicator()+            Text(+                stringResource(R.string.currency_loading),+                color = MaterialTheme.colorScheme.onSurfaceVariant,+            )+        } else {+            Text(+                error ?: stringResource(R.string.currency_unavailable),+                color = MaterialTheme.colorScheme.onSurfaceVariant,+            )+            Button(onClick = onRetry) { Text(stringResource(R.string.currency_retry)) }+        }+    }+}+ @Composable private fun LabeledUnitDropdown(     label: String,
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 8834351406..c75a8866bd 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/util/CalculatorUiContract.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/util/CalculatorUiContract.kt@@ -98,6 +98,12 @@ data class UnitConverterUiState(     val toToken: String = "",     val inputText: String = "",     val outputText: String = "",+    /** True while the live currency rates are being fetched (the Currency tab shows a spinner). */+    val currencyLoading: Boolean = false,+    /** Non-null when fetching currency rates failed; the Currency tab shows this with a retry. */+    val currencyError: String? = null,+    /** True once the selected category is the live Currency tab. */+    val isCurrencyCategory: Boolean = false, )  /** Unit-converter callbacks. Same no-op-default arrangement as [CalculatorActions]. */@@ -107,6 +113,8 @@ interface UnitConverterActions {     fun setTo(token: String) {}     fun setConverterInput(text: String) {}     fun swapUnits() {}+    /** Re-fetch live currency exchange rates after a failure. */+    fun retryCurrency() {}      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 2a5d532e34..3bc9f72a59 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/util/CalculatorViewModel.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/util/CalculatorViewModel.kt@@ -6,6 +6,8 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.graphics.Color import androidx.lifecycle.ViewModel+import androidx.lifecycle.viewModelScope+import kotlinx.coroutines.launch import kotlin.math.hypot  /** One plotted curve on the graph screen — Cartesian `y = f(x)` or polar `r = f(θ)`. */@@ -243,16 +245,33 @@ class CalculatorViewModel : ViewModel(), CalculatorActions, GraphActions, UnitCo     var converterValueText by mutableStateOf("1")         private set +    // Live currency rates power a "Currency" tab appended after the static categories. The tab+    // is always present (so it stays reachable while loading or after a failure); its units+    // populate once rates are fetched.+    private var currencyCategory by mutableStateOf<UnitCategory?>(null)+    private var currencyLoading by mutableStateOf(false)+    private var currencyError by mutableStateOf<String?>(null)++    /** Static physical-unit categories plus the (possibly still-empty) live Currency tab. */+    private val converterCategories: List<UnitCategory>+        get() = UnitRegistry.categories + (currencyCategory ?: EMPTY_CURRENCY_CATEGORY)++    private val currencyIndex: Int get() = converterCategories.lastIndex+     val unitConverterUiState: UnitConverterUiState         get() {-            val category = UnitRegistry.categories[converterCategoryIndex]+            val categories = converterCategories+            val index = converterCategoryIndex.coerceIn(categories.indices)             return UnitConverterUiState(-                categories = UnitRegistry.categories,-                selectedCategoryIndex = converterCategoryIndex,+                categories = categories,+                selectedCategoryIndex = index,                 fromToken = converterFromToken,                 toToken = converterToToken,                 inputText = converterValueText,-                outputText = convert(category),+                outputText = convert(categories[index]),+                currencyLoading = currencyLoading,+                currencyError = currencyError,+                isCurrencyCategory = index == currencyIndex,             )         } @@ -264,24 +283,60 @@ class CalculatorViewModel : ViewModel(), CalculatorActions, GraphActions, UnitCo     }      override fun selectCategory(index: Int) {-        if (index !in UnitRegistry.categories.indices) return+        val categories = converterCategories+        if (index !in categories.indices) return         converterCategoryIndex = index-        val units = UnitRegistry.categories[index].units-        converterFromToken = units[0].token-        converterToToken = units.getOrElse(1) { units[0] }.token+        val units = categories[index].units+        converterFromToken = units.getOrNull(0)?.token ?: ""+        converterToToken = units.getOrElse(1) { units.getOrNull(0) }?.token ?: converterFromToken     }      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 swappedInput = convert(UnitRegistry.categories[converterCategoryIndex])+        val categories = converterCategories+        val swappedInput = convert(categories[converterCategoryIndex.coerceIn(categories.indices)])         val from = converterFromToken         converterFromToken = converterToToken         converterToToken = from         if (swappedInput.toDoubleOrNull() != null) converterValueText = swappedInput     } +    override fun retryCurrency() = loadCurrencyRates()++    private fun loadCurrencyRates() {+        if (currencyLoading) return+        currencyLoading = true+        currencyError = null+        viewModelScope.launch {+            runCatching { CurrencyApi.rates() }+                .onSuccess { dto ->+                    val category = UnitRegistry.currencyCategory(dto.rates)+                    if (category == null) {+                        currencyError = "No exchange rates available"+                    } else {+                        val wasEmpty = currencyCategory?.units.isNullOrEmpty()+                        currencyCategory = category+                        // If the user is already on the Currency tab with nothing picked yet,+                        // seed sensible defaults (USD -> EUR) now that units exist.+                        if (converterCategoryIndex == currencyIndex && wasEmpty) {+                            val units = category.units+                            converterFromToken = units.getOrNull(0)?.token ?: converterFromToken+                            converterToToken =+                                units.getOrElse(1) { units.getOrNull(0) }?.token ?: converterToToken+                        }+                    }+                }+                .onFailure { currencyError = "Couldn't load exchange rates" }+            currencyLoading = false+        }+    }++    init {+        loadCurrencyRates()+    }+     /**      * 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.@@ -321,5 +376,9 @@ class CalculatorViewModel : ViewModel(), CalculatorActions, GraphActions, UnitCo             Color(0xFF4285F4), Color(0xFFEA4335), Color(0xFF34A853),             Color(0xFFFF9800), Color(0xFF9C27B0), Color(0xFF00BCD4),         )++        /** The Currency tab's stand-in before rates load: present so the tab shows, but empty. */+        private val EMPTY_CURRENCY_CATEGORY =+            UnitCategory("Currency", emptyList(), inEquations = false)     } }
calculator/src/main/java/com/vayunmathur/calculator/util/CurrencyApi.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/util/CurrencyApi.kt b/calculator/src/main/java/com/vayunmathur/calculator/util/CurrencyApi.ktnew file mode 100644index 0000000000..7ccd979079--- /dev/null+++ b/calculator/src/main/java/com/vayunmathur/calculator/util/CurrencyApi.kt@@ -0,0 +1,24 @@+package com.vayunmathur.calculator.util++import com.vayunmathur.library.network.NetworkClient+import kotlinx.serialization.Serializable++/**+ * Live currency exchange rates from the self-hosted proxy on `api.vayunmathur.com`, which+ * fetches and caches them from a free upstream. Rates are "units of the currency per 1+ * [base]" (base is USD, so USD == 1.0), which is exactly the `factorToBase` inverse the+ * converter needs — see [UnitRegistry.currencyCategory].+ */+object CurrencyApi {++    private const val URL = "https://api.vayunmathur.com/api/currency/rates"++    suspend fun rates(): CurrencyRatesDto = NetworkClient.getJson(URL)+}++@Serializable+data class CurrencyRatesDto(+    val base: String = "USD",+    val updated: Long = 0L,+    val rates: Map<String, Double> = emptyMap(),+)
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.ktindex 32c96b567d..f0558489c1 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/util/Units.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/util/Units.kt@@ -14,8 +14,9 @@ import kotlin.math.pow  * 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 }+/** The seven SI base dimensions, plus INFORMATION so bytes/bits are first-class, and+ * CURRENCY for the live money converter (converter-only; never used inside equations). */+enum class BaseDim { LENGTH, MASS, TIME, CURRENT, TEMPERATURE, AMOUNT, LUMINOUS, INFORMATION, CURRENCY }  /**  * A product of base dimensions with integer exponents (so speed is `LENGTH·TIME⁻¹`). Zero@@ -54,6 +55,7 @@ class Dimension private constructor(val exponents: Map<BaseDim, Int>) {         val TEMPERATURE = base(BaseDim.TEMPERATURE)         val AMOUNT = base(BaseDim.AMOUNT)         val INFORMATION = base(BaseDim.INFORMATION)+        val CURRENCY = base(BaseDim.CURRENCY)          // Common derived dimensions.         val AREA = LENGTH.pow(2)@@ -224,6 +226,53 @@ object UnitRegistry {             ?: options.firstOrNull()     } +    /** Widely-used currencies, surfaced at the top of the currency picker in this order. */+    val CURRENCY_PRIORITY: List<String> =+        listOf("USD", "EUR", "GBP", "JPY", "CNY", "INR", "CAD", "AUD", "CHF", "HKD")++    /** Display names for common ISO 4217 codes; codes not listed fall back to the code itself. */+    private val CURRENCY_NAMES: Map<String, String> = mapOf(+        "USD" to "US Dollar", "EUR" to "Euro", "GBP" to "British Pound", "JPY" to "Japanese Yen",+        "CNY" to "Chinese Yuan", "INR" to "Indian Rupee", "CAD" to "Canadian Dollar",+        "AUD" to "Australian Dollar", "CHF" to "Swiss Franc", "HKD" to "Hong Kong Dollar",+        "NZD" to "New Zealand Dollar", "SGD" to "Singapore Dollar", "SEK" to "Swedish Krona",+        "NOK" to "Norwegian Krone", "DKK" to "Danish Krone", "KRW" to "South Korean Won",+        "MXN" to "Mexican Peso", "BRL" to "Brazilian Real", "ZAR" to "South African Rand",+        "RUB" to "Russian Ruble", "TRY" to "Turkish Lira", "AED" to "UAE Dirham",+        "SAR" to "Saudi Riyal", "THB" to "Thai Baht", "IDR" to "Indonesian Rupiah",+        "MYR" to "Malaysian Ringgit", "PHP" to "Philippine Peso", "PLN" to "Polish Zloty",+        "CZK" to "Czech Koruna", "HUF" to "Hungarian Forint", "ILS" to "Israeli Shekel",+        "CLP" to "Chilean Peso", "COP" to "Colombian Peso", "ARS" to "Argentine Peso",+        "EGP" to "Egyptian Pound", "NGN" to "Nigerian Naira", "PKR" to "Pakistani Rupee",+        "BDT" to "Bangladeshi Taka", "VND" to "Vietnamese Dong", "UAH" to "Ukrainian Hryvnia",+        "TWD" to "Taiwan Dollar",+    )++    /**+     * Build the converter's live "Currency" category from [rates] (units of the currency per+     * 1 USD, so USD == 1.0). A currency's [UnitDef.factorToBase] is `1/rate` — its value in+     * USD, the base — which makes the ordinary [UnitDef.toBase]/[UnitDef.fromBase] path convert+     * between any two currencies. Common currencies lead the list; the rest follow+     * alphabetically. Currencies are converter-only, so this category is never `inEquations`.+     * Returns null when [rates] has no usable entries.+     */+    fun currencyCategory(rates: Map<String, Double>): UnitCategory? {+        val usable = rates.filterValues { it.isFinite() && it > 0.0 }+        if (usable.isEmpty()) return null+        val priority = CURRENCY_PRIORITY.filter { it in usable }+        val rest = usable.keys.filter { it !in priority }.sorted()+        val units = (priority + rest).map { code ->+            UnitDef(+                token = code,+                symbol = code,+                name = CURRENCY_NAMES[code] ?: code,+                dimension = Dimension.CURRENCY,+                factorToBase = 1.0 / usable.getValue(code),+            )+        }+        return UnitCategory("Currency", units, inEquations = false)+    }+     private fun buildCategories(): List<UnitCategory> {         val d = Dimension         return listOf(
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 e032a81a34..ea09f443e2 100644--- a/calculator/src/main/res/values/strings.xml+++ b/calculator/src/main/res/values/strings.xml@@ -32,4 +32,10 @@     <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>+    <!-- Converter: shown while live currency exchange rates are being fetched. -->+    <string name="currency_loading">Fetching exchange rates…</string>+    <!-- Converter: shown when exchange rates could not be loaded. -->+    <string name="currency_unavailable">Exchange rates are unavailable</string>+    <!-- Converter: button to retry fetching exchange rates after a failure. -->+    <string name="currency_retry">Retry</string> </resources>