Modern Apps git

← Modern-Apps.git

calculator: ktlint rollout — format module and fix residue

Commit
a50cb070a56ae518983101bdc27db67c6ff6026c
Author
Vayun Mathur <[email protected]>
When
2026-12-01 19:15 UTC (4 days ago)
Parents
4c3b743
Ran ./format calculator over the whole module: 1,487
violations in 62 files at census (main 1,152, test 274,
androidTest 39, screenshotTest 22) are down to zero,
verified by ktlintCheck on every source set.

Manual fixes for the six non-autocorrectable residues:
- Renamed domain/Units.kt to UnitRegistry.kt and
  domain/UnitsBasicCategories.kt to BasicUnitCategories.kt,
  and test GraphDrawAndSettingsTest.kt to GraphDrawTest.kt,
  so each file is named after its single top-level
  declaration (standard:filename). Declarations themselves
  are unchanged; calculator/AGENTS.md key-file entries were
  updated for the new paths.
- Merged the doubled KDocs in UnitRegistry and
  CalculatorUiContract (standard:no-consecutive-comments),
  also correcting the contract stale claim that it lives
  in `util`: it lives in `platform` alongside the
  ViewModel, and `ui` depends on `platform`.
- Split the over-long AndroidComposeTestRule type
  application in WidgetSettingsComposeTest across lines
  (standard:max-line-length); the rule construction is
  unchanged.

No ktlint rule was disabled, no detekt or lint config was
touched, and no baseline was added. detekt needed no
fixes: formatting expansion produced no LongMethod or
other findings in this module.

Verified: ./gradlew :calculator:detekt :calculator:lint
:calculator:ktlintCheck :calculator:compileDevKotlin
green; :calculator:testDevUnitTest green (202 tests,
0 failures).

Diff

calculator/AGENTS.md
diff --git a/calculator/AGENTS.md b/calculator/AGENTS.mdindex 0c0efc19b5..4b5a30560c 100644--- a/calculator/AGENTS.md+++ b/calculator/AGENTS.md@@ -18,7 +18,7 @@ _Install: ./install calculator (dev by default)._ - Unit converter across many categories incl. live currency rates (`CurrencyApi` over `:library:network`) - Home-screen widgets for both calculator and unit converter (`:library:widgets` Glance) **Architecture / data-flow:** Single-screen `MainActivity` hosting `ui/` pages (`CalculatorPage`, `GraphPage`, `UnitConverterPage`) over a `util/` ViewModel + pure expression/graph/units helpers; widget receivers in `widget/` share the same logic. Internet is used only for currency rates.-**Entry points + reading order:** `MainActivity.kt` → `ui/CalculatorPage.kt` → `util/CalculatorViewModel.kt` + `util/CalculatorUiContract.kt` → `util/Expression.kt` / `util/GraphAnalysis.kt` / `util/Units.kt` → `widget/CalculatorGlanceWidget.kt`.+**Entry points + reading order:** `MainActivity.kt` → `ui/CalculatorPage.kt` → `util/CalculatorViewModel.kt` + `util/CalculatorUiContract.kt` → `util/Expression.kt` / `util/GraphAnalysis.kt` / `domain/UnitRegistry.kt` → `widget/CalculatorGlanceWidget.kt`. **Gotchas:** - `util/` is NOT a closed package root — don't add more files there - Currency rates are the only network call — everything else must stay offline-safe@@ -37,7 +37,8 @@ _Install: ./install calculator (dev by default)._ - com/vayunmathur/calculator/util/CalculatorUiContract.kt - com/vayunmathur/calculator/util/Expression.kt — expression parsing/eval - com/vayunmathur/calculator/util/GraphAnalysis.kt — root/intercept/min-max/intersection-- com/vayunmathur/calculator/util/Units.kt+- com/vayunmathur/calculator/domain/UnitRegistry.kt+- com/vayunmathur/calculator/domain/BasicUnitCategories.kt - com/vayunmathur/calculator/util/CurrencyApi.kt — only network call - com/vayunmathur/calculator/util/Formatting.kt ### widget/ — Glance widgets sharing the same logic
calculator/src/androidTest/java/com/vayunmathur/calculator/ui/CalculatorEvaluateTest.kt
diff --git a/calculator/src/androidTest/java/com/vayunmathur/calculator/ui/CalculatorEvaluateTest.kt b/calculator/src/androidTest/java/com/vayunmathur/calculator/ui/CalculatorEvaluateTest.ktindex 51b5b8911c..c701251be7 100644--- a/calculator/src/androidTest/java/com/vayunmathur/calculator/ui/CalculatorEvaluateTest.kt+++ b/calculator/src/androidTest/java/com/vayunmathur/calculator/ui/CalculatorEvaluateTest.kt@@ -24,7 +24,6 @@ import org.junit.runner.RunWith  */ @RunWith(AndroidJUnit4::class) class CalculatorEvaluateTest {-     @Test     fun tapKeys_evaluates_showsResult() {         val instrumentation = InstrumentationRegistry.getInstrumentation()@@ -75,13 +74,15 @@ class CalculatorEvaluateTest {         packageManager: PackageManager,         packageName: String,     ) {-        val info = try {-            packageManager.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS)-        } catch (e: PackageManager.NameNotFoundException) {-            throw AssertionError("package $packageName not installed", e)-        }-        val commands = info.requestedPermissions.orEmpty().map { "pm grant $packageName $it" } +-            SPECIAL_ACCESS_COMMANDS.map { it.format(packageName) }+        val info =+            try {+                packageManager.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS)+            } catch (e: PackageManager.NameNotFoundException) {+                throw AssertionError("package $packageName not installed", e)+            }+        val commands =+            info.requestedPermissions.orEmpty().map { "pm grant $packageName $it" } ++                SPECIAL_ACCESS_COMMANDS.map { it.format(packageName) }         for (command in commands) {             try {                 uiAutomation.executeShellCommand(command).close()@@ -105,9 +106,10 @@ class CalculatorEvaluateTest {          * have no pm-grantable permission, but the shell can flip their appops.          * Ignored where the appop does not exist; the gate assertion reports it.          */-        private val SPECIAL_ACCESS_COMMANDS = arrayOf(-            "appops set %s SCHEDULE_EXACT_ALARM allow",-            "appops set %s USE_FULL_SCREEN_INTENT allow",-        )+        private val SPECIAL_ACCESS_COMMANDS =+            arrayOf(+                "appops set %s SCHEDULE_EXACT_ALARM allow",+                "appops set %s USE_FULL_SCREEN_INTENT allow",+            )     } }
calculator/src/androidTest/java/com/vayunmathur/calculator/ui/CalculatorGraphTest.kt
diff --git a/calculator/src/androidTest/java/com/vayunmathur/calculator/ui/CalculatorGraphTest.kt b/calculator/src/androidTest/java/com/vayunmathur/calculator/ui/CalculatorGraphTest.ktindex 9c79ef944d..b08de0dd09 100644--- a/calculator/src/androidTest/java/com/vayunmathur/calculator/ui/CalculatorGraphTest.kt+++ b/calculator/src/androidTest/java/com/vayunmathur/calculator/ui/CalculatorGraphTest.kt@@ -20,7 +20,6 @@ import org.junit.runner.RunWith  */ @RunWith(AndroidJUnit4::class) class CalculatorGraphTest {-     @Test     fun graphTab_addFunction_showsFunctionRow() {         val instrumentation = InstrumentationRegistry.getInstrumentation()@@ -58,13 +57,15 @@ class CalculatorGraphTest {         packageManager: PackageManager,         packageName: String,     ) {-        val info = try {-            packageManager.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS)-        } catch (e: PackageManager.NameNotFoundException) {-            throw AssertionError("package $packageName not installed", e)-        }-        val commands = info.requestedPermissions.orEmpty().map { "pm grant $packageName $it" } +-            SPECIAL_ACCESS_COMMANDS.map { it.format(packageName) }+        val info =+            try {+                packageManager.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS)+            } catch (e: PackageManager.NameNotFoundException) {+                throw AssertionError("package $packageName not installed", e)+            }+        val commands =+            info.requestedPermissions.orEmpty().map { "pm grant $packageName $it" } ++                SPECIAL_ACCESS_COMMANDS.map { it.format(packageName) }         for (command in commands) {             try {                 uiAutomation.executeShellCommand(command).close()@@ -82,9 +83,10 @@ class CalculatorGraphTest {         private const val ADD_FUNCTION = "Add function"         private const val FUNCTION_PLACEHOLDER = "f(x)"         private const val PERMISSION_GATE_TITLE = "Grant Required Permissions"-        private val SPECIAL_ACCESS_COMMANDS = arrayOf(-            "appops set %s SCHEDULE_EXACT_ALARM allow",-            "appops set %s USE_FULL_SCREEN_INTENT allow",-        )+        private val SPECIAL_ACCESS_COMMANDS =+            arrayOf(+                "appops set %s SCHEDULE_EXACT_ALARM allow",+                "appops set %s USE_FULL_SCREEN_INTENT allow",+            )     } }
calculator/src/androidTest/java/com/vayunmathur/calculator/ui/CalculatorUnitsTest.kt
diff --git a/calculator/src/androidTest/java/com/vayunmathur/calculator/ui/CalculatorUnitsTest.kt b/calculator/src/androidTest/java/com/vayunmathur/calculator/ui/CalculatorUnitsTest.ktindex e34143cadb..a8cebf7a58 100644--- a/calculator/src/androidTest/java/com/vayunmathur/calculator/ui/CalculatorUnitsTest.kt+++ b/calculator/src/androidTest/java/com/vayunmathur/calculator/ui/CalculatorUnitsTest.kt@@ -20,7 +20,6 @@ import org.junit.runner.RunWith  */ @RunWith(AndroidJUnit4::class) class CalculatorUnitsTest {-     @Test     fun unitsTab_selectCategory_showsResult() {         val instrumentation = InstrumentationRegistry.getInstrumentation()@@ -49,9 +48,10 @@ class CalculatorUnitsTest {         )         // The converter remembers the last-used category across launches,         // so find whichever is showing and switch to the other one.-        val current = CATEGORIES.firstNotNullOfOrNull { name ->-            device.wait(Until.findObject(By.text(name)), SHORT_TIMEOUT_MS)?.let { name to it }-        }+        val current =+            CATEGORIES.firstNotNullOfOrNull { name ->+                device.wait(Until.findObject(By.text(name)), SHORT_TIMEOUT_MS)?.let { name to it }+            }         assertNotNull("category selector never appeared", current)         current!!.second.click()         val target = if (current.first == "Mass") "Length" else "Mass"@@ -74,13 +74,15 @@ class CalculatorUnitsTest {         packageManager: PackageManager,         packageName: String,     ) {-        val info = try {-            packageManager.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS)-        } catch (e: PackageManager.NameNotFoundException) {-            throw AssertionError("package $packageName not installed", e)-        }-        val commands = info.requestedPermissions.orEmpty().map { "pm grant $packageName $it" } +-            SPECIAL_ACCESS_COMMANDS.map { it.format(packageName) }+        val info =+            try {+                packageManager.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS)+            } catch (e: PackageManager.NameNotFoundException) {+                throw AssertionError("package $packageName not installed", e)+            }+        val commands =+            info.requestedPermissions.orEmpty().map { "pm grant $packageName $it" } ++                SPECIAL_ACCESS_COMMANDS.map { it.format(packageName) }         for (command in commands) {             try {                 uiAutomation.executeShellCommand(command).close()@@ -96,18 +98,35 @@ class CalculatorUnitsTest {         private const val SHORT_TIMEOUT_MS = 5_000L         private const val EQUALS_KEY = "="         private const val UNITS_TAB = "Units"+         // Candidate categories observed on device; the converter opens on         // whichever was last used, so the test switches away from it.-        private val CATEGORIES = arrayOf(-            "Length", "Mass", "Temperature", "Time", "Speed", "Area", "Volume",-            "Data", "Energy", "Power", "Pressure", "Force", "Frequency", "Charge",-            "Current", "Voltage", "Resistance",-        )+        private val CATEGORIES =+            arrayOf(+                "Length",+                "Mass",+                "Temperature",+                "Time",+                "Speed",+                "Area",+                "Volume",+                "Data",+                "Energy",+                "Power",+                "Pressure",+                "Force",+                "Frequency",+                "Charge",+                "Current",+                "Voltage",+                "Resistance",+            )         private const val RESULT_LABEL = "Result"         private const val PERMISSION_GATE_TITLE = "Grant Required Permissions"-        private val SPECIAL_ACCESS_COMMANDS = arrayOf(-            "appops set %s SCHEDULE_EXACT_ALARM allow",-            "appops set %s USE_FULL_SCREEN_INTENT allow",-        )+        private val SPECIAL_ACCESS_COMMANDS =+            arrayOf(+                "appops set %s SCHEDULE_EXACT_ALARM allow",+                "appops set %s USE_FULL_SCREEN_INTENT allow",+            )     } }
calculator/src/androidTest/java/com/vayunmathur/calculator/ui/FullE2eTest.kt
diff --git a/calculator/src/androidTest/java/com/vayunmathur/calculator/ui/FullE2eTest.kt b/calculator/src/androidTest/java/com/vayunmathur/calculator/ui/FullE2eTest.ktindex 8a85a88793..5230639f5f 100644--- a/calculator/src/androidTest/java/com/vayunmathur/calculator/ui/FullE2eTest.kt+++ b/calculator/src/androidTest/java/com/vayunmathur/calculator/ui/FullE2eTest.kt@@ -7,12 +7,12 @@ import androidx.test.platform.app.InstrumentationRegistry import androidx.test.uiautomator.By import androidx.test.uiautomator.UiDevice import androidx.test.uiautomator.Until-import java.io.IOException import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Assert.assertNull import org.junit.Test import org.junit.runner.RunWith+import java.io.IOException  /**  * Full e2e test: launches the app, grants every requested permission, and@@ -30,7 +30,6 @@ import org.junit.runner.RunWith  */ @RunWith(AndroidJUnit4::class) class FullE2eTest {-     @Test     fun launch_grantsPermissions_showsMainContent() {         val instrumentation = InstrumentationRegistry.getInstrumentation()@@ -69,11 +68,12 @@ class FullE2eTest {         packageManager: PackageManager,         packageName: String,     ) {-        val info = try {-            packageManager.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS)-        } catch (e: PackageManager.NameNotFoundException) {-            throw AssertionError("package $packageName not installed", e)-        }+        val info =+            try {+                packageManager.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS)+            } catch (e: PackageManager.NameNotFoundException) {+                throw AssertionError("package $packageName not installed", e)+            }         for (permission in info.requestedPermissions.orEmpty()) {             try {                 uiAutomation.executeShellCommand("pm grant $packageName $permission").close()@@ -108,9 +108,10 @@ class FullE2eTest {          * have no pm-grantable permission, but the shell can flip their appops.          * Ignored where the appop does not exist; the gate assertion reports it.          */-        private val SPECIAL_ACCESS_COMMANDS = arrayOf(-            "appops set %s SCHEDULE_EXACT_ALARM allow",-            "appops set %s USE_FULL_SCREEN_INTENT allow",-        )+        private val SPECIAL_ACCESS_COMMANDS =+            arrayOf(+                "appops set %s SCHEDULE_EXACT_ALARM allow",+                "appops set %s USE_FULL_SCREEN_INTENT allow",+            )     } }
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 f2431d88e4..33e843964c 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/MainActivity.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/MainActivity.kt@@ -48,6 +48,5 @@ class MainActivity : MaActivity() {         if (intent.opensUnits()) unitsRequest++     } -    private fun Intent?.opensUnits(): Boolean =-        this?.getBooleanExtra(UnitsGlanceWidget.EXTRA_OPEN_UNITS, false) == true+    private fun Intent?.opensUnits(): Boolean = this?.getBooleanExtra(UnitsGlanceWidget.EXTRA_OPEN_UNITS, false) == true }
calculator/src/main/java/com/vayunmathur/calculator/Navigation.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/Navigation.kt b/calculator/src/main/java/com/vayunmathur/calculator/Navigation.ktindex 1e786fb3fc..9f628ce433 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/Navigation.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/Navigation.kt@@ -6,6 +6,7 @@ import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect+import androidx.compose.ui.Modifier import com.vayunmathur.calculator.platform.CalculatorViewModel import com.vayunmathur.calculator.ui.CalculatorPage import com.vayunmathur.calculator.ui.GraphPage@@ -24,10 +25,12 @@ import com.vayunmathur.library.util.EntryProviderScope import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.util.SiblingPage import com.vayunmathur.library.util.rememberNavBackStack-import androidx.compose.ui.Modifier  @Composable-fun Navigation(viewModel: CalculatorViewModel, unitsRequest: Int = 0) {+fun Navigation(+    viewModel: CalculatorViewModel,+    unitsRequest: Int = 0,+) {     /** The three tab destinations, registered once and shared by both layout branches below. */     fun EntryProviderScope<Route>.calculatorEntries() {         entry<Route.Calculator>(metadata = SiblingPage()) { CalculatorPage(viewModel) }@@ -40,11 +43,12 @@ fun Navigation(viewModel: CalculatorViewModel, unitsRequest: Int = 0) {         if (unitsRequest > 0 && backStack.last() != Route.Units) backStack.reset(Route.Units)     }     val current = backStack.last()-    val tabs = listOf(-        BottomBarItem("Calculator", Route.Calculator) { IconCalculate() },-        BottomBarItem("Graph", Route.Graph) { IconFunctions() },-        BottomBarItem("Units", Route.Units) { IconRuler() },-    )+    val tabs =+        listOf(+            BottomBarItem("Calculator", Route.Calculator) { IconCalculate() },+            BottomBarItem("Graph", Route.Graph) { IconFunctions() },+            BottomBarItem("Units", Route.Units) { IconRuler() },+        )     // Wide or short windows get the rail on the left instead of the bottom bar,     // matching TabbedPagerScaffold's expanded branch (appstore). This frees the     // full height for the keypad/display instead of spending ~64dp on a bottom
calculator/src/main/java/com/vayunmathur/calculator/domain/BasicUnitCategories.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/domain/UnitsBasicCategories.kt b/calculator/src/main/java/com/vayunmathur/calculator/domain/BasicUnitCategories.ktsimilarity index 85%rename from calculator/src/main/java/com/vayunmathur/calculator/domain/UnitsBasicCategories.ktrename to calculator/src/main/java/com/vayunmathur/calculator/domain/BasicUnitCategories.ktindex ce4d423439..a9a1b0a10f 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/domain/UnitsBasicCategories.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/domain/BasicUnitCategories.kt@@ -5,7 +5,6 @@ package com.vayunmathur.calculator.domain  * stays a single readable source without one oversized category builder.  */ internal object BasicUnitCategories {-     // Length (metres).     private const val METRES_PER_KM = 1000.0     private const val METRES_PER_CM = 0.01@@ -51,13 +50,15 @@ internal object BasicUnitCategories {     private const val SECONDS_PER_WEEK = 604800.0     private const val SECONDS_PER_YEAR = 31557600.0 -    fun lengthCategory(): UnitCategory = UnitCategory(-        "Length",-        metricLengthUnits() + imperialLengthUnits() + parsecLengthUnits() +-            largeLightLengthUnits() + smallLightLengthUnits() + astronomicalLengthUnits(),-    )+    fun lengthCategory(): UnitCategory =+        UnitCategory(+            "Length",+            metricLengthUnits() + imperialLengthUnits() + parsecLengthUnits() ++                largeLightLengthUnits() + smallLightLengthUnits() + astronomicalLengthUnits(),+        ) -    private fun metricLengthUnits(): List<UnitDef> = listOf(+    private fun metricLengthUnits(): List<UnitDef> =+        listOf(             UnitDef("km", "km", "Kilometre", Dimension.LENGTH, METRES_PER_KM),             UnitDef("m", "m", "Metre", Dimension.LENGTH, 1.0),             UnitDef("cm", "cm", "Centimetre", Dimension.LENGTH, METRES_PER_CM),@@ -66,7 +67,8 @@ internal object BasicUnitCategories {             UnitDef("nm", "nm", "Nanometre", Dimension.LENGTH, METRES_PER_NM),         ) -    private fun imperialLengthUnits(): List<UnitDef> = listOf(+    private fun imperialLengthUnits(): List<UnitDef> =+        listOf(             UnitDef("mi", "mi", "Mile", Dimension.LENGTH, METRES_PER_MILE),             UnitDef("yd", "yd", "Yard", Dimension.LENGTH, METRES_PER_YARD),             UnitDef("ft", "ft", "Foot", Dimension.LENGTH, METRES_PER_FOOT),@@ -74,7 +76,8 @@ internal object BasicUnitCategories {             UnitDef("nmi", "nmi", "Nautical mile", Dimension.LENGTH, METRES_PER_NAUTICAL_MILE),         ) -    private fun parsecLengthUnits(): List<UnitDef> = listOf(+    private fun parsecLengthUnits(): List<UnitDef> =+        listOf(             UnitDef(                 "Gpc",                 "Gpc",@@ -82,7 +85,7 @@ internal object BasicUnitCategories {                 Dimension.LENGTH,                 METRES_PER_GIGAPARSEC,                 aliases = listOf("gpc", "gigaparsec", "gigaparsecs"),-                ),+            ),             UnitDef(                 "Mpc",                 "Mpc",@@ -90,7 +93,7 @@ internal object BasicUnitCategories {                 Dimension.LENGTH,                 METRES_PER_MEGAPARSEC,                 aliases = listOf("mpc", "megaparsec", "megaparsecs"),-                ),+            ),             UnitDef(                 "kpc",                 "kpc",@@ -98,7 +101,7 @@ internal object BasicUnitCategories {                 Dimension.LENGTH,                 METRES_PER_KILOPARSEC,                 aliases = listOf("kiloparsec", "kiloparsecs"),-                ),+            ),             UnitDef(                 "pc",                 "pc",@@ -106,10 +109,11 @@ internal object BasicUnitCategories {                 Dimension.LENGTH,                 METRES_PER_PARSEC,                 aliases = listOf("parsec", "parsecs"),-                ),+            ),         ) -    private fun largeLightLengthUnits(): List<UnitDef> = listOf(+    private fun largeLightLengthUnits(): List<UnitDef> =+        listOf(             UnitDef(                 "ly",                 "ly",@@ -117,7 +121,7 @@ internal object BasicUnitCategories {                 Dimension.LENGTH,                 METRES_PER_LIGHT_YEAR,                 aliases = listOf("lightyear", "lightyears"),-                ),+            ),             UnitDef(                 "lw",                 "lw",@@ -125,7 +129,7 @@ internal object BasicUnitCategories {                 Dimension.LENGTH,                 METRES_PER_LIGHT_WEEK,                 aliases = listOf("lwk", "lightweek", "lightweeks"),-                ),+            ),             UnitDef(                 "ld",                 "ld",@@ -133,7 +137,7 @@ internal object BasicUnitCategories {                 Dimension.LENGTH,                 METRES_PER_LIGHT_DAY,                 aliases = listOf("lday", "lightday", "lightdays"),-                ),+            ),             UnitDef(                 "lh",                 "lh",@@ -141,7 +145,7 @@ internal object BasicUnitCategories {                 Dimension.LENGTH,                 METRES_PER_LIGHT_HOUR,                 aliases = listOf("lighthour", "lighthours"),-                ),+            ),             UnitDef(                 "lmin",                 "lmin",@@ -149,10 +153,11 @@ internal object BasicUnitCategories {                 Dimension.LENGTH,                 METRES_PER_LIGHT_MINUTE,                 aliases = listOf("lightminute", "lightminutes"),-                ),+            ),         ) -    private fun smallLightLengthUnits(): List<UnitDef> = listOf(+    private fun smallLightLengthUnits(): List<UnitDef> =+        listOf(             UnitDef(                 "ls",                 "ls",@@ -160,43 +165,47 @@ internal object BasicUnitCategories {                 Dimension.LENGTH,                 METRES_PER_LIGHT_SECOND,                 aliases = listOf("lightsecond", "lightseconds"),-                ),+            ),             UnitDef(                 "lms",                 "lms",                 "Light-millisecond",                 Dimension.LENGTH,                 METRES_PER_LIGHT_MILLISECOND,-                aliases = listOf(-                "lightmillisecond",-                "lightmilliseconds",-                ),-                ),+                aliases =+                    listOf(+                        "lightmillisecond",+                        "lightmilliseconds",+                    ),+            ),             UnitDef(                 "lus",                 "lµs",                 "Light-microsecond",                 Dimension.LENGTH,                 METRES_PER_LIGHT_MICROSECOND,-                aliases = listOf(-                "lightmicrosecond",-                "lightmicroseconds",-                ),-                ),+                aliases =+                    listOf(+                        "lightmicrosecond",+                        "lightmicroseconds",+                    ),+            ),             UnitDef(                 "lns",                 "lns",                 "Light-nanosecond",                 Dimension.LENGTH,                 METRES_PER_LIGHT_NANOSECOND,-                aliases = listOf(-                "lightnanosecond",-                "lightnanoseconds",-                ),-                ),+                aliases =+                    listOf(+                        "lightnanosecond",+                        "lightnanoseconds",+                    ),+            ),         ) -    private fun astronomicalLengthUnits(): List<UnitDef> = listOf(+    private fun astronomicalLengthUnits(): List<UnitDef> =+        listOf(             UnitDef(                 "AU",                 "AU",@@ -204,7 +213,7 @@ internal object BasicUnitCategories {                 Dimension.LENGTH,                 METRES_PER_AU,                 aliases = listOf("au", "astronomicalunit", "astronomicalunits"),-                ),+            ),         )      fun massCategory(): UnitCategory {
calculator/src/main/java/com/vayunmathur/calculator/domain/Expression.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/domain/Expression.kt b/calculator/src/main/java/com/vayunmathur/calculator/domain/Expression.ktindex 5210673019..948607ff54 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/domain/Expression.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/domain/Expression.kt@@ -66,10 +66,16 @@ private val PAIR_FUNCTIONS = setOf("root", "mod", "atan2", "ncr", "npr", "gcd", enum class AngleMode { RADIANS, DEGREES }  /** Thrown when an expression cannot be tokenised or parsed. */-class ExpressionError(message: String) : Exception(message)+class ExpressionError(+    message: String,+) : Exception(message)  /** Values supplied at evaluation time: the free variable, angle mode, and last answer. */-class EvalContext(val variable: Double, val angle: AngleMode, val ans: Double)+class EvalContext(+    val variable: Double,+    val angle: AngleMode,+    val ans: Double,+)  /**  * A parsed, reusable mathematical expression. Parsing happens once (via [parse]); the@@ -83,20 +89,27 @@ class EvalContext(val variable: Double, val angle: AngleMode, val ans: Double)  * library, and multi-argument functions: `log(b,x)`, `root(n,x)`, `nCr(n,r)`,  * `nPr(n,r)`, `mod(a,b)`, `gcd(a,b)`, `lcm(a,b)`, `atan2(y,x)`, `max(…)`, `min(…)`.  */-class Expression private constructor(private val root: Node) {-+class Expression private constructor(+    private val root: Node,+) {     /**      * Evaluate for a given free-variable value, [angle] mode and [ans], returning the numeric      * magnitude only ([Quantity.baseValue], so an absolute temperature is its kelvin).      * 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).baseValue+    fun eval(+        variable: Double = 0.0,+        angle: AngleMode = AngleMode.RADIANS,+        ans: Double = 0.0,+    ): Double = evalQuantity(variable, angle, ans).baseValue      /** 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))+    fun evalQuantity(+        variable: Double = 0.0,+        angle: AngleMode = AngleMode.RADIANS,+        ans: Double = 0.0,+    ): Quantity = root.eval(EvalContext(variable, angle, ans))      /** Parses expression text into an [Expression]. */     companion object {@@ -109,7 +122,9 @@ class Expression private constructor(private val root: Node) {         fun eval(ctx: EvalContext): Quantity     } -    private class Num(val value: Double) : Node {+    private class Num(+        val value: Double,+    ) : Node {         override fun eval(ctx: EvalContext) = Quantity.scalar(value)     } @@ -121,24 +136,36 @@ class Expression private constructor(private val root: Node) {         override fun eval(ctx: EvalContext) = Quantity.scalar(ctx.ans)     } -    private class UnitNode(val unit: UnitDef) : Node {+    private class UnitNode(+        val unit: UnitDef,+    ) : Node {         override fun eval(ctx: EvalContext) = Quantity(unit.factorToBase, unit.dimension, unit.offsetK)     }      /** An absolute point in time, written `#<epochSeconds>` (inserted by the date/time pickers). */-    private class InstantLit(val epochSeconds: Double) : Node {+    private class InstantLit(+        val epochSeconds: Double,+    ) : Node {         override fun eval(ctx: EvalContext) = Quantity(epochSeconds, Dimension.TIME, instant = true)     } -    private class Neg(val operand: Node) : Node {+    private class Neg(+        val operand: Node,+    ) : Node {         override fun eval(ctx: EvalContext) = -operand.eval(ctx)     } -    private class Fact(val operand: Node) : Node {+    private class Fact(+        val operand: Node,+    ) : Node {         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 {+    private class Binary(+        val op: Char,+        val left: Node,+        val right: Node,+    ) : Node {         override fun eval(ctx: EvalContext): Quantity {             val a = left.eval(ctx)             val b = right.eval(ctx)@@ -154,7 +181,10 @@ class Expression private constructor(private val root: Node) {         }     } -    private class Call(val name: String, val args: List<Node>) : Node {+    private class Call(+        val name: String,+        val args: List<Node>,+    ) : Node {         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.@@ -167,64 +197,81 @@ class Expression private constructor(private val root: Node) {         }          /** Dispatch a dimensionless call to its function group. */-        private fun evaluateScalar(a: List<Double>, angle: AngleMode): Double = when {-            name in TRIG_FUNCTIONS -> evalTrig(singleArg(a), angle)-            name in HYPERBOLIC_FUNCTIONS -> evalHyperbolic(singleArg(a))-            name in SINGLE_ARG_FUNCTIONS -> evalSingle(singleArg(a))-            name in PAIR_FUNCTIONS -> evalPair(a, angle)-            name == "log" -> if (a.size == 2) ln(a[1]) / ln(a[0]) else log10(singleArg(a))-            name == "max" -> a.maxOrNull() ?: throw ExpressionError("max expects at least 1 argument")-            name == "min" -> a.minOrNull() ?: throw ExpressionError("min expects at least 1 argument")-            else -> throw ExpressionError("Unknown function '$name'")-        }+        private fun evaluateScalar(+            a: List<Double>,+            angle: AngleMode,+        ): Double =+            when {+                name in TRIG_FUNCTIONS -> evalTrig(singleArg(a), angle)+                name in HYPERBOLIC_FUNCTIONS -> evalHyperbolic(singleArg(a))+                name in SINGLE_ARG_FUNCTIONS -> evalSingle(singleArg(a))+                name in PAIR_FUNCTIONS -> evalPair(a, angle)+                name == "log" -> if (a.size == 2) ln(a[1]) / ln(a[0]) else log10(singleArg(a))+                name == "max" -> a.maxOrNull() ?: throw ExpressionError("max expects at least 1 argument")+                name == "min" -> a.minOrNull() ?: throw ExpressionError("min expects at least 1 argument")+                else -> throw ExpressionError("Unknown function '$name'")+            }          private fun singleArg(a: List<Double>): Double {             if (a.size != 1) throw ExpressionError("$name expects 1 argument")             return a[0]         } -        private fun toRad(v: Double, angle: AngleMode) =-            if (angle == AngleMode.DEGREES) v * PI / DEGREES_IN_HALF_CIRCLE else v--        private fun fromRad(v: Double, angle: AngleMode) =-            if (angle == AngleMode.DEGREES) v * DEGREES_IN_HALF_CIRCLE / PI else v--        private fun evalTrig(x: Double, angle: AngleMode): Double = when (name) {-            "sin" -> sin(toRad(x, angle))-            "cos" -> cos(toRad(x, angle))-            "tan" -> tan(toRad(x, angle))-            "asin" -> fromRad(asin(x), angle)-            "acos" -> fromRad(acos(x), angle)-            "atan" -> fromRad(atan(x), angle)-            "sec" -> 1.0 / cos(toRad(x, angle))-            "csc" -> 1.0 / sin(toRad(x, angle))-            else -> 1.0 / tan(toRad(x, angle)) // "cot"-        }+        private fun toRad(+            v: Double,+            angle: AngleMode,+        ) = if (angle == AngleMode.DEGREES) v * PI / DEGREES_IN_HALF_CIRCLE else v++        private fun fromRad(+            v: Double,+            angle: AngleMode,+        ) = if (angle == AngleMode.DEGREES) v * DEGREES_IN_HALF_CIRCLE / PI else v++        private fun evalTrig(+            x: Double,+            angle: AngleMode,+        ): Double =+            when (name) {+                "sin" -> sin(toRad(x, angle))+                "cos" -> cos(toRad(x, angle))+                "tan" -> tan(toRad(x, angle))+                "asin" -> fromRad(asin(x), angle)+                "acos" -> fromRad(acos(x), angle)+                "atan" -> fromRad(atan(x), angle)+                "sec" -> 1.0 / cos(toRad(x, angle))+                "csc" -> 1.0 / sin(toRad(x, angle))+                else -> 1.0 / tan(toRad(x, angle)) // "cot"+            } -        private fun evalHyperbolic(x: Double): Double = when (name) {-            "sinh" -> sinh(x)-            "cosh" -> cosh(x)-            "tanh" -> tanh(x)-            "asinh" -> asinh(x)-            "acosh" -> acosh(x)-            else -> atanh(x) // "atanh"-        }+        private fun evalHyperbolic(x: Double): Double =+            when (name) {+                "sinh" -> sinh(x)+                "cosh" -> cosh(x)+                "tanh" -> tanh(x)+                "asinh" -> asinh(x)+                "acosh" -> acosh(x)+                else -> atanh(x) // "atanh"+            } -        private fun evalSingle(x: Double): Double = when (name) {-            "sqrt", "√" -> sqrt(x)-            "cbrt" -> cbrt(x)-            "exp" -> exp(x)-            "ln" -> ln(x)-            "log2" -> log2(x)-            "floor" -> floor(x)-            "ceil" -> ceil(x)-            "round" -> round(x)-            "sign" -> sign(x)-            "gamma" -> gamma(x)-            else -> factorial(x) // "fact"-        }+        private fun evalSingle(x: Double): Double =+            when (name) {+                "sqrt", "√" -> sqrt(x)+                "cbrt" -> cbrt(x)+                "exp" -> exp(x)+                "ln" -> ln(x)+                "log2" -> log2(x)+                "floor" -> floor(x)+                "ceil" -> ceil(x)+                "round" -> round(x)+                "sign" -> sign(x)+                "gamma" -> gamma(x)+                else -> factorial(x) // "fact"+            } -        private fun evalPair(a: List<Double>, angle: AngleMode): Double {+        private fun evalPair(+            a: List<Double>,+            angle: AngleMode,+        ): Double {             require2(a)             return when (name) {                 "root" -> realRoot(a[0], a[1])@@ -251,7 +298,9 @@ class Expression private constructor(private val root: Node) {      * postfix → primary ('!')*                (factorial)      * primary → number | const | var | ans | func '(' args ')' | '(' expr ')' | '|' expr '|'      */-    private class Parser(input: String) {+    private class Parser(+        input: String,+    ) {         private val src = input         private var pos = 0 @@ -306,12 +355,16 @@ class Expression private constructor(private val root: Node) {             // Treating it as the start of another factor made every |x| expression             // recurse into an unterminated bar and throw.             if (c == '|' && barDepth > 0) return null-            val op = when (c) {-                '*', '/', '%' -> { pos++; c }-                // Implicit multiplication: value directly followed by a group/name.-                '(', '|' -> '*'-                else -> if (isImplicitFactorStart(c)) '*' else return null-            }+            val op =+                when (c) {+                    '*', '/', '%' -> {+                        pos+++                        c+                    }+                    // Implicit multiplication: value directly followed by a group/name.+                    '(', '|' -> '*'+                    else -> if (isImplicitFactorStart(c)) '*' else return null+                }             return if (op == '/' || op == '%') Binary(op, left, parseDivisor()) else Binary(op, left, parseFactor())         } @@ -347,8 +400,14 @@ class Expression private constructor(private val root: Node) {          private fun parseFactor(): Node {             val c = peek()-            if (c == '+') { pos++; return parseFactor() }-            if (c == '-') { pos++; return Neg(parseFactor()) }+            if (c == '+') {+                pos+++                return parseFactor()+            }+            if (c == '-') {+                pos+++                return Neg(parseFactor())+            }             return parsePower()         } @@ -363,7 +422,10 @@ class Expression private constructor(private val root: Node) {          private fun parsePostfix(): Node {             var node = parsePrimary()-            while (peek() == '!') { pos++; node = Fact(node) }+            while (peek() == '!') {+                pos+++                node = Fact(node)+            }             return node         } @@ -448,9 +510,18 @@ class Expression private constructor(private val root: Node) {          private fun parseIdentifier(): Node {             skipSpaces()-            if (src[pos] == '√') { pos++; return Call("sqrt", listOf(parseFactor())) }-            if (src[pos] == 'π') { pos++; return Num(PI) }-            if (src[pos] == 'θ') { pos++; return Var }+            if (src[pos] == '√') {+                pos+++                return Call("sqrt", listOf(parseFactor()))+            }+            if (src[pos] == 'π') {+                pos+++                return Num(PI)+            }+            if (src[pos] == 'θ') {+                pos+++                return Var+            }             val start = pos             while (pos < src.length && (src[pos].isLetterOrDigit() || src[pos] == '_')) pos++             val raw = src.substring(start, pos)@@ -467,7 +538,10 @@ class Expression private constructor(private val root: Node) {         }          /** A trailing name is a function call, or a unit from the registry (case-sensitive). */-        private fun parseFunctionOrUnit(raw: String, name: String): Node {+        private fun parseFunctionOrUnit(+            raw: String,+            name: String,+        ): Node {             if (peek() != '(') {                 // Not a function call: try the unit registry (case-sensitively, so `mm`                 // and `Mm` differ) before giving up.@@ -486,7 +560,10 @@ class Expression private constructor(private val root: Node) {             val args = mutableListOf<Node>()             if (peek() == ')') return args             args.add(parseExpr())-            while (peek() == ',') { pos++; args.add(parseExpr()) }+            while (peek() == ',') {+                pos+++                args.add(parseExpr())+            }             return args         }     }@@ -511,11 +588,18 @@ private fun gamma(x: Double): Double { }  /** Lanczos series coefficients for g = 7 (nine-term expansion). */-private val LANCZOS_COEFFICIENTS = doubleArrayOf(-    0.99999999999980993, 676.5203681218851, -1259.1392167224028,-    771.32342877765313, -176.61502916214059, 12.507343278686905,-    -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7,-)+private val LANCZOS_COEFFICIENTS =+    doubleArrayOf(+        0.99999999999980993,+        676.5203681218851,+        -1259.1392167224028,+        771.32342877765313,+        -176.61502916214059,+        12.507343278686905,+        -0.13857109526572012,+        9.9843695780195716e-6,+        1.5056327351493116e-7,+    )  /** Smallest factor in the exact iterative factorial product. */ private const val FACTORIAL_FIRST_FACTOR = 2.0@@ -543,23 +627,39 @@ private fun exactFactorial(n: Int): Double {  * odd-integer root of a negative number is real (root(3, -8) = -2, exactly what  * `cbrt` already returns); even and non-integer roots of negatives stay NaN.  */-private fun realRoot(n: Double, x: Double): Double =-    if (x < 0 && n == floor(n) && n % 2 != 0.0) -((-x).pow(1.0 / n)) else x.pow(1.0 / n)--private fun combinations(n: Double, r: Double): Double =-    factorial(n) / (factorial(r) * factorial(n - r))--private fun permutations(n: Double, r: Double): Double =-    factorial(n) / factorial(n - r)--private fun gcd(a: Double, b: Double): Double {+private fun realRoot(+    n: Double,+    x: Double,+): Double = if (x < 0 && n == floor(n) && n % 2 != 0.0) -((-x).pow(1.0 / n)) else x.pow(1.0 / n)++private fun combinations(+    n: Double,+    r: Double,+): Double = factorial(n) / (factorial(r) * factorial(n - r))++private fun permutations(+    n: Double,+    r: Double,+): Double = factorial(n) / factorial(n - r)++private fun gcd(+    a: Double,+    b: Double,+): Double {     var x = abs(round(a)).toLong()     var y = abs(round(b)).toLong()-    while (y != 0L) { val t = y; y = x % y; x = t }+    while (y != 0L) {+        val t = y+        y = x % y+        x = t+    }     return x.toDouble() } -private fun lcm(a: Double, b: Double): Double {+private fun lcm(+    a: Double,+    b: Double,+): Double {     val g = gcd(a, b)     return if (g == 0.0) 0.0 else abs(round(a) * round(b)) / g }
calculator/src/main/java/com/vayunmathur/calculator/domain/Formatting.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/domain/Formatting.kt b/calculator/src/main/java/com/vayunmathur/calculator/domain/Formatting.ktindex afcbed8dac..a52e47fc17 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/domain/Formatting.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/domain/Formatting.kt@@ -49,10 +49,16 @@ fun formatResultToken(value: Double): String =     if (value.isFinite()) formatResult(value).replace('e', 'E') else formatResult(value)  /** The magnitude of [q] expressed in [unit] (handling affine temperature and deltas). */-fun displayValueIn(q: Quantity, unit: UnitDef): Double =+fun displayValueIn(+    q: Quantity,+    unit: UnitDef,+): Double =     if (q.dimension == Dimension.TEMPERATURE) {-        if (q.tempOffsetK != null) unit.fromBase(q.baseValue) // absolute-        else q.value / unit.factorToBase // delta: degree-size only, no offset+        if (q.tempOffsetK != null) {+            unit.fromBase(q.baseValue) // absolute+        } else {+            q.value / unit.factorToBase // delta: degree-size only, no offset+        }     } else {         unit.fromBase(q.value)     }@@ -63,7 +69,11 @@ fun displayValueIn(q: Quantity, unit: UnitDef): Double =  * 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 {+fun formatQuantity(+    q: Quantity,+    unit: UnitDef?,+    useToken: Boolean = false,+): String {     if (q.instant) return formatInstant(q.value, useToken)     if (q.isDimensionless || unit == null) {         return if (useToken) formatResultToken(q.value) else formatResult(q.value)@@ -79,7 +89,10 @@ fun formatQuantity(q: Quantity, unit: UnitDef?, useToken: Boolean = false): Stri  * otherwise a localized string — a date alone at midnight, or a date-and-time otherwise. The  * midnight check is what makes `date + duration` show a time only once one is actually present.  */-fun formatInstant(epochSeconds: Double, useToken: Boolean = false): String {+fun formatInstant(+    epochSeconds: Double,+    useToken: Boolean = false,+): String {     if (useToken) return "#" + epochSecondsToken(epochSeconds)     // A user-typed `#<digits>` token can name an epoch far outside the     // range java.time.Instant supports (or overflow to Infinity, whose@@ -87,15 +100,17 @@ fun formatInstant(epochSeconds: Double, useToken: Boolean = false): String {     // DateTimeException. This renders during composition / preview, where     // only ExpressionError is caught, so fall back to the token form     // instead of crashing.-    val zoned = runCatching {-        Instant.ofEpochSecond(epochSeconds.toLong()).atZone(ZoneId.systemDefault())-    }.getOrElse { return "#" + epochSeconds.toLong() }+    val zoned =+        runCatching {+            Instant.ofEpochSecond(epochSeconds.toLong()).atZone(ZoneId.systemDefault())+        }.getOrElse { return "#" + epochSeconds.toLong() }     val atMidnight = zoned.hour == 0 && zoned.minute == 0 && zoned.second == 0-    val formatter = if (atMidnight) {-        DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)-    } else {-        DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM, FormatStyle.SHORT)-    }+    val formatter =+        if (atMidnight) {+            DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)+        } else {+            DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM, FormatStyle.SHORT)+        }     return zoned.format(formatter) } 
calculator/src/main/java/com/vayunmathur/calculator/domain/GraphAnalysis.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/domain/GraphAnalysis.kt b/calculator/src/main/java/com/vayunmathur/calculator/domain/GraphAnalysis.ktindex 76ad51683e..e3df13e520 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/domain/GraphAnalysis.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/domain/GraphAnalysis.kt@@ -7,7 +7,10 @@ import kotlin.math.hypot import kotlin.math.sin  /** A point in graph (not screen) coordinates. */-data class GraphPoint(val x: Double, val y: Double)+data class GraphPoint(+    val x: Double,+    val y: Double,+)  /** The kinds of notable point the grapher can find. */ enum class FeatureKind {@@ -50,7 +53,6 @@ class SampledCurve(  * Cartesian; polar features keep their (sub-pixel) polyline estimate.  */ object GraphAnalysis {-     /** Turns of θ a polar curve is swept for when it never starts retracing itself. */     private const val POLAR_TURNS = 12 @@ -80,8 +82,16 @@ object GraphAnalysis {      private const val REFINE_ITERS = 80 -    private fun evalOrNaN(e: Expression, v: Double, angle: AngleMode): Double =-        try { e.eval(v, angle) } catch (ignored: ExpressionError) { Double.NaN }+    private fun evalOrNaN(+        e: Expression,+        v: Double,+        angle: AngleMode,+    ): Double =+        try {+            e.eval(v, angle)+        } catch (ignored: ExpressionError) {+            Double.NaN+        }      // ---- Sampling ---- @@ -136,10 +146,19 @@ object GraphAnalysis {     }      /** One halved-until-short polar step: the probe that survived refinement, and its step. */-    private class PolarProbe(val theta: Double, val r: Double, val point: GraphPoint?)+    private class PolarProbe(+        val theta: Double,+        val r: Double,+        val point: GraphPoint?,+    )      /** The outcome of refining one polar step: where it landed and the step it kept. */-    private class PolarAdvance(val theta: Double, val r: Double, val point: GraphPoint?, val step: Double)+    private class PolarAdvance(+        val theta: Double,+        val r: Double,+        val point: GraphPoint?,+        val step: Double,+    )      /**      * Polar sampling, driven by the viewport rather than by a fixed count: each step reaches@@ -161,16 +180,23 @@ object GraphAnalysis {         private val pxPerUnit = if (xMax > xMin) columns.coerceAtLeast(2) / (xMax - xMin) else 1.0          // Nothing further from the origin than the farthest corner can be on screen.-        private val visibleRadius = maxOf(-            hypot(xMin, yMin), hypot(xMin, yMax), hypot(xMax, yMin), hypot(xMax, yMax),-        )+        private val visibleRadius =+            maxOf(+                hypot(xMin, yMin),+                hypot(xMin, yMax),+                hypot(xMax, yMin),+                hypot(xMax, yMax),+            )         private val visibleRadiusPx = (visibleRadius * pxPerUnit).coerceAtLeast(1.0)         private val thetaMax = 2 * PI * polarTurns(expr)          // Detail has to stop somewhere, or a tight spiral would sample without end.         private val budgetStep = thetaMax / POLAR_SAMPLE_BUDGET -        fun scan(current: MutableList<GraphPoint>, breakRun: () -> Unit) {+        fun scan(+            current: MutableList<GraphPoint>,+            breakRun: () -> Unit,+        ) {             var theta = 0.0             var r = evalOrNaN(expr, 0.0, AngleMode.RADIANS)             var here = if (r.isFinite()) GraphPoint(r, 0.0) else null@@ -195,7 +221,12 @@ object GraphAnalysis {         }          /** Probe first, then halve until the segment is short enough on screen. */-        private fun refineStep(theta: Double, step: Double, here: GraphPoint?, r: Double): PolarAdvance {+        private fun refineStep(+            theta: Double,+            step: Double,+            here: GraphPoint?,+            r: Double,+        ): PolarAdvance {             var refined = step             var probe = probe(theta, refined)             while (segmentTooLong(here, probe.point, probe.r, r, refined)) {@@ -221,17 +252,20 @@ object GraphAnalysis {         }          /** How far apart two samples may land: a pixel on screen, looser further out. */-        private fun tolerancePx(radiusPx: Double) =-            POLAR_CHORD_PX + (radiusPx - visibleRadiusPx).coerceAtLeast(0.0) / 2+        private fun tolerancePx(radiusPx: Double) = POLAR_CHORD_PX + (radiusPx - visibleRadiusPx).coerceAtLeast(0.0) / 2 -        private fun probe(theta: Double, step: Double): PolarProbe {+        private fun probe(+            theta: Double,+            step: Double,+        ): PolarProbe {             val nextTheta = (theta + step).coerceAtMost(thetaMax)             val nextR = evalOrNaN(expr, nextTheta, AngleMode.RADIANS)-            val next = if (nextR.isFinite()) {-                GraphPoint(nextR * cos(nextTheta), nextR * sin(nextTheta))-            } else {-                null-            }+            val next =+                if (nextR.isFinite()) {+                    GraphPoint(nextR * cos(nextTheta), nextR * sin(nextTheta))+                } else {+                    null+                }             return PolarProbe(nextTheta, nextR, next)         }     }@@ -243,7 +277,11 @@ object GraphAnalysis {      * dwarf anything that could be on screen, so the zero crossing at the base of every rose      * petal is never mistaken for one.      */-    private fun crossesPole(prev: Double, current: Double, visibleRadius: Double): Boolean {+    private fun crossesPole(+        prev: Double,+        current: Double,+        visibleRadius: Double,+    ): Boolean {         if (!prev.isFinite() || !current.isFinite()) return false         if ((prev < 0.0) == (current < 0.0)) return false         return minOf(abs(prev), abs(current)) > POLE_FACTOR * visibleRadius@@ -352,13 +390,21 @@ object GraphAnalysis {         out: MutableList<GraphFeature>,     ) {         if (straddles(a.y, b.y)) {-            val x = if (curve.polar) interpolateZero(a.y, b.y, a.x, b.x)-            else refineZero({ evalOrNaN(curve.expr, it, angle) }, a.x, b.x)+            val x =+                if (curve.polar) {+                    interpolateZero(a.y, b.y, a.x, b.x)+                } else {+                    refineZero({ evalOrNaN(curve.expr, it, angle) }, a.x, b.x)+                }             out.add(GraphFeature(GraphPoint(x, 0.0), FeatureKind.ROOT, listOf(curve.id)))         }         if (!straddles(a.x, b.x)) return-        val y = if (curve.polar) interpolateZero(a.x, b.x, a.y, b.y)-        else evalOrNaN(curve.expr, 0.0, angle)+        val y =+            if (curve.polar) {+                interpolateZero(a.x, b.x, a.y, b.y)+            } else {+                evalOrNaN(curve.expr, 0.0, angle)+            }         if (y.isFinite()) {             out.add(GraphFeature(GraphPoint(0.0, y), FeatureKind.Y_INTERCEPT, listOf(curve.id)))         }@@ -395,13 +441,14 @@ object GraphAnalysis {         val isMin = p.y < run[i - 1].y && p.y < run[i + 1].y         if (!isMax && !isMin) return null         val kind = if (isMax) FeatureKind.MAXIMUM else FeatureKind.MINIMUM-        val point = if (curve.polar) {-            p-        } else {-            val x = refineExtremum({ evalOrNaN(curve.expr, it, angle) }, run[i - 1].x, run[i + 1].x, isMax)-            val y = evalOrNaN(curve.expr, x, angle)-            if (y.isFinite()) GraphPoint(x, y) else p-        }+        val point =+            if (curve.polar) {+                p+            } else {+                val x = refineExtremum({ evalOrNaN(curve.expr, it, angle) }, run[i - 1].x, run[i + 1].x, isMax)+                val y = evalOrNaN(curve.expr, x, angle)+                if (y.isFinite()) GraphPoint(x, y) else p+            }         return GraphFeature(point, kind, listOf(curve.id))     } @@ -552,20 +599,32 @@ object GraphAnalysis {      * viewport centred on the origin makes samples land exactly on the nice crossing points,      * so the product is `0`, not negative, and the crossing was skipped every time.      */-    private fun straddles(a: Double, b: Double): Boolean {+    private fun straddles(+        a: Double,+        b: Double,+    ): Boolean {         if (!a.isFinite() || !b.isFinite()) return false         return (a <= 0.0 && b >= 0.0) || (a >= 0.0 && b <= 0.0)     }      /** Linear interpolation of the parameter where `va → vb` crosses zero. */-    private fun interpolateZero(va: Double, vb: Double, pa: Double, pb: Double): Double {+    private fun interpolateZero(+        va: Double,+        vb: Double,+        pa: Double,+        pb: Double,+    ): Double {         val d = vb - va         if (d == 0.0) return pa         return pa + (pb - pa) * (-va / d)     }      /** Bisection for `f(x) = 0` on a bracketing interval, tolerant of exact zeros. */-    private fun refineZero(f: (Double) -> Double, lo0: Double, hi0: Double): Double {+    private fun refineZero(+        f: (Double) -> Double,+        lo0: Double,+        hi0: Double,+    ): Double {         var lo = lo0         var hi = hi0         var flo = f(lo)@@ -577,13 +636,23 @@ object GraphAnalysis {             val mid = (lo + hi) / 2             val fmid = f(mid)             if (fmid == 0.0 || !fmid.isFinite()) return mid-            if (straddles(flo, fmid)) hi = mid else { lo = mid; flo = fmid }+            if (straddles(flo, fmid)) {+                hi = mid+            } else {+                lo = mid+                flo = fmid+            }         }         return (lo + hi) / 2     }      /** Ternary search for the extremum of a unimodal bracket. */-    private fun refineExtremum(f: (Double) -> Double, lo0: Double, hi0: Double, wantMax: Boolean): Double {+    private fun refineExtremum(+        f: (Double) -> Double,+        lo0: Double,+        hi0: Double,+        wantMax: Boolean,+    ): Double {         var lo = lo0         var hi = hi0         repeat(REFINE_ITERS) {@@ -600,10 +669,17 @@ object GraphAnalysis {      // ---- Geometry ---- -    private fun distance(a: GraphPoint, b: GraphPoint) = hypot(a.x - b.x, a.y - b.y)+    private fun distance(+        a: GraphPoint,+        b: GraphPoint,+    ) = hypot(a.x - b.x, a.y - b.y)      /** Shortest distance from [p] to the segment `a→b`. */-    private fun segmentDistance(p: GraphPoint, a: GraphPoint, b: GraphPoint): Double {+    private fun segmentDistance(+        p: GraphPoint,+        a: GraphPoint,+        b: GraphPoint,+    ): Double {         val dx = b.x - a.x         val dy = b.y - a.y         val lenSq = dx * dx + dy * dy@@ -613,7 +689,12 @@ object GraphAnalysis {     }      /** Where segments `p1→p2` and `q1→q2` cross, or null if they don't. */-    private fun segmentIntersection(p1: GraphPoint, p2: GraphPoint, q1: GraphPoint, q2: GraphPoint): GraphPoint? {+    private fun segmentIntersection(+        p1: GraphPoint,+        p2: GraphPoint,+        q1: GraphPoint,+        q2: GraphPoint,+    ): GraphPoint? {         val rx = p2.x - p1.x         val ry = p2.y - p1.y         val sx = q2.x - q1.x
calculator/src/main/java/com/vayunmathur/calculator/domain/UnitRegistry.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/domain/Units.kt b/calculator/src/main/java/com/vayunmathur/calculator/domain/UnitRegistry.ktsimilarity index 74%rename from calculator/src/main/java/com/vayunmathur/calculator/domain/Units.ktrename to calculator/src/main/java/com/vayunmathur/calculator/domain/UnitRegistry.ktindex d5acef06a1..7a69a92a11 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/domain/Units.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/domain/UnitRegistry.kt@@ -10,15 +10,11 @@ import kotlin.math.PI  * 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 single source of unit truth+ *  * 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") @@ -154,17 +150,18 @@ object UnitRegistry {     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)+    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> =@@ -183,63 +180,171 @@ object UnitRegistry {      /** Display names for every ISO 4217 code the rate source returns; unknown codes fall back      * to the code itself. */-    private val CURRENCY_NAMES: Map<String, String> = mapOf(-        "AED" to "UAE Dirham", "AFN" to "Afghan Afghani", "ALL" to "Albanian Lek",-        "AMD" to "Armenian Dram", "ANG" to "Netherlands Antillean Guilder", "AOA" to "Angolan Kwanza",-        "ARS" to "Argentine Peso", "AUD" to "Australian Dollar", "AWG" to "Aruban Florin",-        "AZN" to "Azerbaijani Manat", "BAM" to "Bosnia-Herzegovina Convertible Mark",-        "BBD" to "Barbadian Dollar", "BDT" to "Bangladeshi Taka", "BGN" to "Bulgarian Lev",-        "BHD" to "Bahraini Dinar", "BIF" to "Burundian Franc", "BMD" to "Bermudan Dollar",-        "BND" to "Brunei Dollar", "BOB" to "Bolivian Boliviano", "BRL" to "Brazilian Real",-        "BSD" to "Bahamian Dollar", "BTN" to "Bhutanese Ngultrum", "BWP" to "Botswanan Pula",-        "BYN" to "Belarusian Ruble", "BZD" to "Belize Dollar", "CAD" to "Canadian Dollar",-        "CDF" to "Congolese Franc", "CHF" to "Swiss Franc", "CLP" to "Chilean Peso",-        "CNY" to "Chinese Yuan", "COP" to "Colombian Peso", "CRC" to "Costa Rican Colon",-        "CUP" to "Cuban Peso", "CVE" to "Cape Verdean Escudo", "CZK" to "Czech Koruna",-        "DJF" to "Djiboutian Franc", "DKK" to "Danish Krone", "DOP" to "Dominican Peso",-        "DZD" to "Algerian Dinar", "EGP" to "Egyptian Pound", "ERN" to "Eritrean Nakfa",-        "ETB" to "Ethiopian Birr", "EUR" to "Euro", "FJD" to "Fijian Dollar",-        "FKP" to "Falkland Islands Pound", "FOK" to "Faroese Krona", "GBP" to "British Pound",-        "GEL" to "Georgian Lari", "GGP" to "Guernsey Pound", "GHS" to "Ghanaian Cedi",-        "GIP" to "Gibraltar Pound", "GMD" to "Gambian Dalasi", "GNF" to "Guinean Franc",-        "GTQ" to "Guatemalan Quetzal", "GYD" to "Guyanaese Dollar", "HKD" to "Hong Kong Dollar",-        "HNL" to "Honduran Lempira", "HRK" to "Croatian Kuna", "HTG" to "Haitian Gourde",-        "HUF" to "Hungarian Forint", "IDR" to "Indonesian Rupiah", "ILS" to "Israeli Shekel",-        "IMP" to "Manx Pound", "INR" to "Indian Rupee", "IQD" to "Iraqi Dinar",-        "IRR" to "Iranian Rial", "ISK" to "Icelandic Krona", "JEP" to "Jersey Pound",-        "JMD" to "Jamaican Dollar", "JOD" to "Jordanian Dinar", "JPY" to "Japanese Yen",-        "KES" to "Kenyan Shilling", "KGS" to "Kyrgystani Som", "KHR" to "Cambodian Riel",-        "KID" to "Kiribati Dollar", "KMF" to "Comorian Franc", "KRW" to "South Korean Won",-        "KWD" to "Kuwaiti Dinar", "KYD" to "Cayman Islands Dollar", "KZT" to "Kazakhstani Tenge",-        "LAK" to "Laotian Kip", "LBP" to "Lebanese Pound", "LKR" to "Sri Lankan Rupee",-        "LRD" to "Liberian Dollar", "LSL" to "Lesotho Loti", "LYD" to "Libyan Dinar",-        "MAD" to "Moroccan Dirham", "MDL" to "Moldovan Leu", "MGA" to "Malagasy Ariary",-        "MKD" to "Macedonian Denar", "MMK" to "Myanmar Kyat", "MNT" to "Mongolian Tugrik",-        "MOP" to "Macanese Pataca", "MRU" to "Mauritanian Ouguiya", "MUR" to "Mauritian Rupee",-        "MVR" to "Maldivian Rufiyaa", "MWK" to "Malawian Kwacha", "MXN" to "Mexican Peso",-        "MYR" to "Malaysian Ringgit", "MZN" to "Mozambican Metical", "NAD" to "Namibian Dollar",-        "NGN" to "Nigerian Naira", "NIO" to "Nicaraguan Cordoba", "NOK" to "Norwegian Krone",-        "NPR" to "Nepalese Rupee", "NZD" to "New Zealand Dollar", "OMR" to "Omani Rial",-        "PAB" to "Panamanian Balboa", "PEN" to "Peruvian Sol", "PGK" to "Papua New Guinean Kina",-        "PHP" to "Philippine Peso", "PKR" to "Pakistani Rupee", "PLN" to "Polish Zloty",-        "PYG" to "Paraguayan Guarani", "QAR" to "Qatari Riyal", "RON" to "Romanian Leu",-        "RSD" to "Serbian Dinar", "RUB" to "Russian Ruble", "RWF" to "Rwandan Franc",-        "SAR" to "Saudi Riyal", "SBD" to "Solomon Islands Dollar", "SCR" to "Seychellois Rupee",-        "SDG" to "Sudanese Pound", "SEK" to "Swedish Krona", "SGD" to "Singapore Dollar",-        "SHP" to "St. Helena Pound", "SLE" to "Sierra Leonean Leone", "SOS" to "Somali Shilling",-        "SRD" to "Surinamese Dollar", "SSP" to "South Sudanese Pound",-        "STN" to "Sao Tome & Principe Dobra", "SYP" to "Syrian Pound", "SZL" to "Swazi Lilangeni",-        "THB" to "Thai Baht", "TJS" to "Tajikistani Somoni", "TMT" to "Turkmenistani Manat",-        "TND" to "Tunisian Dinar", "TOP" to "Tongan Pa'anga", "TRY" to "Turkish Lira",-        "TTD" to "Trinidad & Tobago Dollar", "TVD" to "Tuvaluan Dollar", "TWD" to "Taiwan Dollar",-        "TZS" to "Tanzanian Shilling", "UAH" to "Ukrainian Hryvnia", "UGX" to "Ugandan Shilling",-        "USD" to "US Dollar", "UYU" to "Uruguayan Peso", "UZS" to "Uzbekistani Som",-        "VES" to "Venezuelan Bolivar", "VND" to "Vietnamese Dong", "VUV" to "Vanuatu Vatu",-        "WST" to "Samoan Tala", "XAF" to "Central African CFA Franc", "XCD" to "East Caribbean Dollar",-        "XCG" to "Caribbean Guilder", "XDR" to "Special Drawing Rights",-        "XOF" to "West African CFA Franc", "XPF" to "CFP Franc", "YER" to "Yemeni Rial",-        "ZAR" to "South African Rand", "ZMW" to "Zambian Kwacha", "ZWL" to "Zimbabwean Dollar",-    )+    private val CURRENCY_NAMES: Map<String, String> =+        mapOf(+            "AED" to "UAE Dirham",+            "AFN" to "Afghan Afghani",+            "ALL" to "Albanian Lek",+            "AMD" to "Armenian Dram",+            "ANG" to "Netherlands Antillean Guilder",+            "AOA" to "Angolan Kwanza",+            "ARS" to "Argentine Peso",+            "AUD" to "Australian Dollar",+            "AWG" to "Aruban Florin",+            "AZN" to "Azerbaijani Manat",+            "BAM" to "Bosnia-Herzegovina Convertible Mark",+            "BBD" to "Barbadian Dollar",+            "BDT" to "Bangladeshi Taka",+            "BGN" to "Bulgarian Lev",+            "BHD" to "Bahraini Dinar",+            "BIF" to "Burundian Franc",+            "BMD" to "Bermudan Dollar",+            "BND" to "Brunei Dollar",+            "BOB" to "Bolivian Boliviano",+            "BRL" to "Brazilian Real",+            "BSD" to "Bahamian Dollar",+            "BTN" to "Bhutanese Ngultrum",+            "BWP" to "Botswanan Pula",+            "BYN" to "Belarusian Ruble",+            "BZD" to "Belize Dollar",+            "CAD" to "Canadian Dollar",+            "CDF" to "Congolese Franc",+            "CHF" to "Swiss Franc",+            "CLP" to "Chilean Peso",+            "CNY" to "Chinese Yuan",+            "COP" to "Colombian Peso",+            "CRC" to "Costa Rican Colon",+            "CUP" to "Cuban Peso",+            "CVE" to "Cape Verdean Escudo",+            "CZK" to "Czech Koruna",+            "DJF" to "Djiboutian Franc",+            "DKK" to "Danish Krone",+            "DOP" to "Dominican Peso",+            "DZD" to "Algerian Dinar",+            "EGP" to "Egyptian Pound",+            "ERN" to "Eritrean Nakfa",+            "ETB" to "Ethiopian Birr",+            "EUR" to "Euro",+            "FJD" to "Fijian Dollar",+            "FKP" to "Falkland Islands Pound",+            "FOK" to "Faroese Krona",+            "GBP" to "British Pound",+            "GEL" to "Georgian Lari",+            "GGP" to "Guernsey Pound",+            "GHS" to "Ghanaian Cedi",+            "GIP" to "Gibraltar Pound",+            "GMD" to "Gambian Dalasi",+            "GNF" to "Guinean Franc",+            "GTQ" to "Guatemalan Quetzal",+            "GYD" to "Guyanaese Dollar",+            "HKD" to "Hong Kong Dollar",+            "HNL" to "Honduran Lempira",+            "HRK" to "Croatian Kuna",+            "HTG" to "Haitian Gourde",+            "HUF" to "Hungarian Forint",+            "IDR" to "Indonesian Rupiah",+            "ILS" to "Israeli Shekel",+            "IMP" to "Manx Pound",+            "INR" to "Indian Rupee",+            "IQD" to "Iraqi Dinar",+            "IRR" to "Iranian Rial",+            "ISK" to "Icelandic Krona",+            "JEP" to "Jersey Pound",+            "JMD" to "Jamaican Dollar",+            "JOD" to "Jordanian Dinar",+            "JPY" to "Japanese Yen",+            "KES" to "Kenyan Shilling",+            "KGS" to "Kyrgystani Som",+            "KHR" to "Cambodian Riel",+            "KID" to "Kiribati Dollar",+            "KMF" to "Comorian Franc",+            "KRW" to "South Korean Won",+            "KWD" to "Kuwaiti Dinar",+            "KYD" to "Cayman Islands Dollar",+            "KZT" to "Kazakhstani Tenge",+            "LAK" to "Laotian Kip",+            "LBP" to "Lebanese Pound",+            "LKR" to "Sri Lankan Rupee",+            "LRD" to "Liberian Dollar",+            "LSL" to "Lesotho Loti",+            "LYD" to "Libyan Dinar",+            "MAD" to "Moroccan Dirham",+            "MDL" to "Moldovan Leu",+            "MGA" to "Malagasy Ariary",+            "MKD" to "Macedonian Denar",+            "MMK" to "Myanmar Kyat",+            "MNT" to "Mongolian Tugrik",+            "MOP" to "Macanese Pataca",+            "MRU" to "Mauritanian Ouguiya",+            "MUR" to "Mauritian Rupee",+            "MVR" to "Maldivian Rufiyaa",+            "MWK" to "Malawian Kwacha",+            "MXN" to "Mexican Peso",+            "MYR" to "Malaysian Ringgit",+            "MZN" to "Mozambican Metical",+            "NAD" to "Namibian Dollar",+            "NGN" to "Nigerian Naira",+            "NIO" to "Nicaraguan Cordoba",+            "NOK" to "Norwegian Krone",+            "NPR" to "Nepalese Rupee",+            "NZD" to "New Zealand Dollar",+            "OMR" to "Omani Rial",+            "PAB" to "Panamanian Balboa",+            "PEN" to "Peruvian Sol",+            "PGK" to "Papua New Guinean Kina",+            "PHP" to "Philippine Peso",+            "PKR" to "Pakistani Rupee",+            "PLN" to "Polish Zloty",+            "PYG" to "Paraguayan Guarani",+            "QAR" to "Qatari Riyal",+            "RON" to "Romanian Leu",+            "RSD" to "Serbian Dinar",+            "RUB" to "Russian Ruble",+            "RWF" to "Rwandan Franc",+            "SAR" to "Saudi Riyal",+            "SBD" to "Solomon Islands Dollar",+            "SCR" to "Seychellois Rupee",+            "SDG" to "Sudanese Pound",+            "SEK" to "Swedish Krona",+            "SGD" to "Singapore Dollar",+            "SHP" to "St. Helena Pound",+            "SLE" to "Sierra Leonean Leone",+            "SOS" to "Somali Shilling",+            "SRD" to "Surinamese Dollar",+            "SSP" to "South Sudanese Pound",+            "STN" to "Sao Tome & Principe Dobra",+            "SYP" to "Syrian Pound",+            "SZL" to "Swazi Lilangeni",+            "THB" to "Thai Baht",+            "TJS" to "Tajikistani Somoni",+            "TMT" to "Turkmenistani Manat",+            "TND" to "Tunisian Dinar",+            "TOP" to "Tongan Pa'anga",+            "TRY" to "Turkish Lira",+            "TTD" to "Trinidad & Tobago Dollar",+            "TVD" to "Tuvaluan Dollar",+            "TWD" to "Taiwan Dollar",+            "TZS" to "Tanzanian Shilling",+            "UAH" to "Ukrainian Hryvnia",+            "UGX" to "Ugandan Shilling",+            "USD" to "US Dollar",+            "UYU" to "Uruguayan Peso",+            "UZS" to "Uzbekistani Som",+            "VES" to "Venezuelan Bolivar",+            "VND" to "Vietnamese Dong",+            "VUV" to "Vanuatu Vatu",+            "WST" to "Samoan Tala",+            "XAF" to "Central African CFA Franc",+            "XCD" to "East Caribbean Dollar",+            "XCG" to "Caribbean Guilder",+            "XDR" to "Special Drawing Rights",+            "XOF" to "West African CFA Franc",+            "XPF" to "CFP Franc",+            "YER" to "Yemeni Rial",+            "ZAR" to "South African Rand",+            "ZMW" to "Zambian Kwacha",+            "ZWL" to "Zimbabwean Dollar",+        )      /**      * Build the converter's live "Currency" category from [rates] (units of the currency per@@ -254,20 +359,21 @@ object UnitRegistry {         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),-            )-        }+        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> {-        return listOf(+    private fun buildCategories(): List<UnitCategory> =+        listOf(             BasicUnitCategories.lengthCategory(),             BasicUnitCategories.massCategory(),             BasicUnitCategories.timeCategory(),@@ -289,10 +395,6 @@ object UnitRegistry {             amountCategory(),             angleCategory(),         )-    }---      private fun temperatureCategory(): UnitCategory {         val d = Dimension@@ -564,8 +666,8 @@ object UnitRegistry {         )     } -    private fun angleCategory(): UnitCategory {-        return UnitCategory(+    private fun angleCategory(): UnitCategory =+        UnitCategory(             "Angle",             listOf(                 UnitDef("rad", "rad", "Radian", Dimension.NONE, 1.0),@@ -577,5 +679,4 @@ object UnitRegistry {             ),             inEquations = false,         )-    } }
calculator/src/main/java/com/vayunmathur/calculator/domain/UnitsModel.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/domain/UnitsModel.kt b/calculator/src/main/java/com/vayunmathur/calculator/domain/UnitsModel.ktindex a5fab2d6d6..a0ae8665c2 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/domain/UnitsModel.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/domain/UnitsModel.kt@@ -11,16 +11,21 @@ enum class BaseDim { LENGTH, MASS, TIME, CURRENT, TEMPERATURE, AMOUNT, LUMINOUS,  * 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>) {-+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}" } @@ -29,9 +34,14 @@ class Dimension private constructor(val exponents: Map<BaseDim, Int>) {         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> {+        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@@ -105,9 +115,13 @@ class Quantity(     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 {+    private fun addOrSub(+        other: Quantity,+        sign: Double,+    ): Quantity {         if (dimension != other.dimension) {             throw ExpressionError("Cannot add or subtract incompatible units")         }@@ -129,7 +143,10 @@ class Quantity(         return Quantity(value + sign * other.value, dimension, null)     } -    private fun addOrSubInstant(other: Quantity, sign: Double): Quantity {+    private fun addOrSubInstant(+        other: Quantity,+        sign: Double,+    ): Quantity {         if (instant && other.instant) {             if (sign > 0) throw ExpressionError("Cannot add two dates together")             return Quantity(value - other.value, Dimension.TIME) // date − date = duration
calculator/src/main/java/com/vayunmathur/calculator/network/CurrencyApi.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/network/CurrencyApi.kt b/calculator/src/main/java/com/vayunmathur/calculator/network/CurrencyApi.ktindex f37e34db70..593ae08b06 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/network/CurrencyApi.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/network/CurrencyApi.kt@@ -11,7 +11,6 @@ import kotlinx.serialization.Serializable  * converter needs — see [UnitRegistry.currencyCategory].  */ object CurrencyApi {-     private const val URL = "https://api.maproj.org/api/currency/rates"      /** The server's hourly copy of the same JSON on R2 (read first). */
calculator/src/main/java/com/vayunmathur/calculator/platform/CalculatorTab.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/platform/CalculatorTab.kt b/calculator/src/main/java/com/vayunmathur/calculator/platform/CalculatorTab.ktindex 7e6d754793..ee9ba8fc1c 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/platform/CalculatorTab.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/platform/CalculatorTab.kt@@ -1,5 +1,10 @@ package com.vayunmathur.calculator.platform +import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableDoubleStateOf+import androidx.compose.runtime.mutableStateListOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue import com.vayunmathur.calculator.domain.AngleMode import com.vayunmathur.calculator.domain.Expression import com.vayunmathur.calculator.domain.ExpressionError@@ -11,12 +16,6 @@ import com.vayunmathur.calculator.domain.formatQuantity import com.vayunmathur.calculator.domain.formatResult import com.vayunmathur.calculator.domain.formatResultToken -import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableStateListOf-import androidx.compose.runtime.mutableDoubleStateOf-import androidx.compose.runtime.mutableStateOf-import androidx.compose.runtime.setValue- /**  * The keypad tab: input, live preview, history, memory and output-unit selection.  *@@ -60,16 +59,17 @@ class CalculatorTab {      * underlying `mutableStateOf` reads are tracked normally.      */     val uiState: CalculatorUiState-        get() = CalculatorUiState(-            input = input,-            preview = preview,-            memory = memory,-            angleMode = angleMode,-            history = history,-            unitOptions = unitOptions,-            selectedUnit = selectedUnit,-            unitCategories = UnitRegistry.categories,-        )+        get() =+            CalculatorUiState(+                input = input,+                preview = preview,+                memory = memory,+                angleMode = angleMode,+                history = history,+                unitOptions = unitOptions,+                selectedUnit = selectedUnit,+                unitCategories = UnitRegistry.categories,+            )      fun updateInput(value: String) {         input = value@@ -89,21 +89,23 @@ class CalculatorTab {     /** Evaluate the current input, push it to history, store `ans`, show the result. */     fun evaluate() {         if (input.isBlank()) return-        val quantity = try {-            Expression.parse(input).evalQuantity(angle = angleMode, ans = lastAnswer)-        } catch (ignored: ExpressionError) {-            return // leave input untouched; the preview already flagged the problem-        }+        val quantity =+            try {+                Expression.parse(input).evalQuantity(angle = angleMode, ans = lastAnswer)+            } catch (ignored: ExpressionError) {+                return // leave input untouched; the preview already flagged the problem+            }         // Non-finite results (NaN, 1/0 = ∞) have no re-parsable token form:         // recording one would replace the input with "∞"/"Undefined" and         // strand it there. Like NaN, they stay a live preview only.         if (!quantity.baseValue.isFinite()) return         val isInstant = quantity.instant-        val unit = if (quantity.isDimensionless || isInstant) {-            null-        } else {-            selectedUnit ?: UnitRegistry.defaultUnitFor(quantity.dimension)-        }+        val unit =+            if (quantity.isDimensionless || isInstant) {+                null+            } else {+                selectedUnit ?: UnitRegistry.defaultUnitFor(quantity.dimension)+            }         val display = formatQuantity(quantity, unit)         // The token form re-parses, so the result can seed the next calculation.         val token = formatQuantity(quantity, unit, useToken = true)@@ -124,28 +126,48 @@ class CalculatorTab {     }      // Memory register operations. M+/M- fold the current preview (or input) into memory.-    fun memoryClear() { memory = 0.0 }+    fun memoryClear() {+        memory = 0.0+    }+     fun memoryRecall() = append(formatResultToken(memory))-    fun memoryAdd() { currentValue()?.let { memory += it } }-    fun memorySubtract() { currentValue()?.let { memory -= it } } -    /** Re-derive [preview], [unitOptions] and [selectedUnit] from the current [input]. */-    fun refresh() = recomputePreview()+    fun memoryAdd() {+        currentValue()?.let { memory += it }+    } -    private fun currentValue(): Double? = try {-        Expression.parse(input.ifBlank { "0" }).eval(angle = angleMode, ans = lastAnswer)-            .takeIf { !it.isNaN() }-    } catch (ignored: ExpressionError) { null }+    fun memorySubtract() {+        currentValue()?.let { memory -= it }+    }      /** 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() }+    fun refresh() = recomputePreview()++    private fun currentValue(): Double? =+        try {+            Expression+                .parse(input.ifBlank { "0" })+                .eval(angle = angleMode, ans = lastAnswer)+                .takeIf { !it.isNaN() }         } catch (ignored: ExpressionError) {             null         }++    /** 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 (ignored: ExpressionError) {+                null+            }         previewQuantity = quantity         if (quantity == null || quantity.isDimensionless) {             unitOptions = emptyList()@@ -166,16 +188,27 @@ class CalculatorTab { }  /** Adapts [CalculatorTab] to the [CalculatorActions] interface for ViewModel delegation. */-internal fun calculatorActionAdapter(tab: CalculatorTab): CalculatorActions = object : CalculatorActions {-    override fun append(text: String) = tab.append(text)-    override fun insertInstant(epochSeconds: Long) = tab.insertInstant(epochSeconds)-    override fun clear() = tab.clear()-    override fun backspace() = tab.backspace()-    override fun evaluate() = tab.evaluate()-    override fun memoryClear() = tab.memoryClear()-    override fun memoryRecall() = tab.memoryRecall()-    override fun memoryAdd() = tab.memoryAdd()-    override fun memorySubtract() = tab.memorySubtract()-    override fun useHistory(entry: HistoryEntry) = tab.useHistory(entry)-    override fun selectOutputUnit(token: String) = tab.selectOutputUnit(token)-}+internal fun calculatorActionAdapter(tab: CalculatorTab): CalculatorActions =+    object : CalculatorActions {+        override fun append(text: String) = tab.append(text)++        override fun insertInstant(epochSeconds: Long) = tab.insertInstant(epochSeconds)++        override fun clear() = tab.clear()++        override fun backspace() = tab.backspace()++        override fun evaluate() = tab.evaluate()++        override fun memoryClear() = tab.memoryClear()++        override fun memoryRecall() = tab.memoryRecall()++        override fun memoryAdd() = tab.memoryAdd()++        override fun memorySubtract() = tab.memorySubtract()++        override fun useHistory(entry: HistoryEntry) = tab.useHistory(entry)++        override fun selectOutputUnit(token: String) = tab.selectOutputUnit(token)+    }
calculator/src/main/java/com/vayunmathur/calculator/platform/CalculatorUiContract.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/platform/CalculatorUiContract.kt b/calculator/src/main/java/com/vayunmathur/calculator/platform/CalculatorUiContract.ktindex 69826f637b..1b3e8ed287 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/platform/CalculatorUiContract.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/platform/CalculatorUiContract.kt@@ -10,18 +10,21 @@ import com.vayunmathur.calculator.domain.UnitDef  *  * Screens take a state value plus an actions interface rather than the ViewModel itself,  * so they can be rendered by a `@Preview` — which is what the store listing images are- * generated from. It lives in `util` rather than `ui` so the dependency runs one way:- * `ui` depends on `util`, and the ViewModel implements these interfaces.- */--/**+ * generated from. It lives in `platform` alongside the ViewModel rather than `ui` so the+ * dependency runs one way: `ui` depends on `platform`, and the ViewModel implements+ * these interfaces.+ *  * One evaluated expression, kept for the history sheet. [result] is the pretty  * display form (thin space, unit symbols like `°C`/`µm`, localised dates);  * [resultToken] is the same value in the parser's ASCII token form, which is  * what tapping the entry seeds the input with — the display form does not  * re-parse. Defaults to [result] so plain numeric entries need no second form.  */-data class HistoryEntry(val expression: String, val result: String, val resultToken: String = result)+data class HistoryEntry(+    val expression: String,+    val result: String,+    val resultToken: String = result,+)  /** How far the graph can be zoomed out and in, in pixels per unit. */ private const val MIN_GRAPH_SCALE = 2.0@@ -46,20 +49,36 @@ data class GraphViewport(     val centerY: Double = 0.0,     val scale: Double = 60.0, ) {-    fun graphX(screenX: Float, widthPx: Float): Double = centerX + (screenX - widthPx / 2) / scale+    fun graphX(+        screenX: Float,+        widthPx: Float,+    ): Double = centerX + (screenX - widthPx / 2) / scale -    fun graphY(screenY: Float, heightPx: Float): Double = centerY + (heightPx / 2 - screenY) / scale+    fun graphY(+        screenY: Float,+        heightPx: Float,+    ): Double = centerY + (heightPx / 2 - screenY) / scale -    fun screenX(graphX: Double, widthPx: Float): Float = ((graphX - centerX) * scale + widthPx / 2).toFloat()+    fun screenX(+        graphX: Double,+        widthPx: Float,+    ): Float = ((graphX - centerX) * scale + widthPx / 2).toFloat() -    fun screenY(graphY: Double, heightPx: Float): Float = (heightPx / 2 - (graphY - centerY) * scale).toFloat()+    fun screenY(+        graphY: Double,+        heightPx: Float,+    ): Float = (heightPx / 2 - (graphY - centerY) * scale).toFloat() -    fun bounds(widthPx: Float, heightPx: Float): GraphBounds = GraphBounds(-        xMin = graphX(0f, widthPx),-        xMax = graphX(widthPx, widthPx),-        yMin = graphY(heightPx, heightPx),-        yMax = graphY(0f, heightPx),-    )+    fun bounds(+        widthPx: Float,+        heightPx: Float,+    ): GraphBounds =+        GraphBounds(+            xMin = graphX(0f, widthPx),+            xMax = graphX(widthPx, widthPx),+            yMin = graphY(heightPx, heightPx),+            yMax = graphY(0f, heightPx),+        )      /**      * The viewport after a transform gesture: zoom about the centroid, so the graph point@@ -115,16 +134,26 @@ data class GraphUiState(  */ interface CalculatorActions {     fun append(text: String) {}+     /** Insert an absolute date/datetime (epoch seconds) chosen from a picker. */     fun insertInstant(epochSeconds: Long) {}+     fun clear() {}+     fun backspace() {}+     fun evaluate() {}+     fun toggleAngleMode() {}+     fun memoryClear() {}+     fun memoryRecall() {}+     fun memoryAdd() {}+     fun memorySubtract() {}+     fun useHistory(entry: HistoryEntry) {}      /** Show the result in the compatible unit identified by [token]. */@@ -139,20 +168,34 @@ interface CalculatorActions { /** Graph callbacks. Same no-op-default arrangement as [CalculatorActions]. */ interface GraphActions {     fun toggleAngleMode() {}+     fun addFunction() {}-    fun updateFunction(id: Long, text: String) {}++    fun updateFunction(+        id: Long,+        text: String,+    ) {}+     fun toggleFunction(id: Long) {}+     fun togglePolar(id: Long) {}+     fun removeFunction(id: Long) {}      /** Report the canvas size so tap handling can convert pixels to graph units. */-    fun setViewSize(widthPx: Float, heightPx: Float) {}+    fun setViewSize(+        widthPx: Float,+        heightPx: Float,+    ) {}      /** Pan/zoom result from a transform gesture. */     fun setViewport(viewport: GraphViewport) {}      /** Reveal or dismiss the notable point nearest [at], within [radius] graph units. */-    fun tapGraph(at: GraphPoint, radius: Double) {}+    fun tapGraph(+        at: GraphPoint,+        radius: Double,+    ) {}      /** No-op GraphActions for previews and tests. */     companion object {@@ -179,10 +222,15 @@ data class UnitConverterUiState( /** 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() {}+     /** Re-fetch live currency exchange rates after a failure. */     fun retryCurrency() {} 
calculator/src/main/java/com/vayunmathur/calculator/platform/CalculatorViewModel.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/platform/CalculatorViewModel.kt b/calculator/src/main/java/com/vayunmathur/calculator/platform/CalculatorViewModel.ktindex 79bc44108b..6f1fa0c4d4 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/platform/CalculatorViewModel.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/platform/CalculatorViewModel.kt@@ -1,9 +1,5 @@ package com.vayunmathur.calculator.platform -import com.vayunmathur.calculator.domain.AngleMode-import com.vayunmathur.calculator.domain.FeatureKind-import com.vayunmathur.calculator.domain.GraphPoint- import android.app.Application import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf@@ -11,6 +7,9 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.graphics.Color import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope+import com.vayunmathur.calculator.domain.AngleMode+import com.vayunmathur.calculator.domain.FeatureKind+import com.vayunmathur.calculator.domain.GraphPoint  /** One plotted curve on the graph screen — Cartesian `y = f(x)` or polar `r = f(θ)`. */ data class GraphFunction(@@ -49,7 +48,6 @@ class CalculatorViewModel(     CalculatorActions by calculatorActionAdapter(calculator),     GraphActions by graphActionAdapter(graph),     UnitConverterActions by converterActionAdapter(converter) {-     /**      * Java-visible single-arg constructor for AndroidViewModelFactory: it looks up      * `CalculatorViewModel(Application)` via reflection, which Kotlin's default-argument
calculator/src/main/java/com/vayunmathur/calculator/platform/GraphTab.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/platform/GraphTab.kt b/calculator/src/main/java/com/vayunmathur/calculator/platform/GraphTab.ktindex 7ac33edb51..8a953b59a3 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/platform/GraphTab.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/platform/GraphTab.kt@@ -1,18 +1,16 @@ package com.vayunmathur.calculator.platform -import com.vayunmathur.calculator.domain.AngleMode-import com.vayunmathur.calculator.domain.Expression-import com.vayunmathur.calculator.domain.GraphAnalysis-import com.vayunmathur.calculator.domain.GraphPoint-import com.vayunmathur.calculator.domain.SampledCurve- import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableDoubleStateOf import androidx.compose.runtime.mutableFloatStateOf-import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.setValue import androidx.compose.ui.graphics.Color+import com.vayunmathur.calculator.domain.AngleMode+import com.vayunmathur.calculator.domain.Expression+import com.vayunmathur.calculator.domain.GraphAnalysis+import com.vayunmathur.calculator.domain.GraphPoint+import com.vayunmathur.calculator.domain.SampledCurve import kotlin.math.hypot  /**@@ -25,9 +23,10 @@ class GraphTab {     /** The trig mode sampling uses; synced from the ViewModel whenever it changes. */     var angleMode: AngleMode = AngleMode.RADIANS -    val functions = mutableStateListOf(-        GraphFunction(id = 0, text = "x", color = GraphTabColors[0]),-    )+    val functions =+        mutableStateListOf(+            GraphFunction(id = 0, text = "x", color = GraphTabColors[0]),+        )     private var nextId = 1L      fun addFunction() {@@ -35,7 +34,10 @@ class GraphTab {         functions.add(GraphFunction(id = nextId++, text = "", color = color))     } -    fun updateFunction(id: Long, text: String) {+    fun updateFunction(+        id: Long,+        text: String,+    ) {         dropMarkersFor(id)         mutate(id) { it.copy(text = text) }     }@@ -56,7 +58,10 @@ class GraphTab {         dropMarkersFor(id)     } -    private inline fun mutate(id: Long, transform: (GraphFunction) -> GraphFunction) {+    private inline fun mutate(+        id: Long,+        transform: (GraphFunction) -> GraphFunction,+    ) {         val index = functions.indexOfFirst { it.id == id }         if (index >= 0) functions[index] = transform(functions[index])     }@@ -73,14 +78,18 @@ class GraphTab {      /** Snapshot of everything the graph screen draws. */     val uiState: GraphUiState-        get() = GraphUiState(-            functions = functions,-            markers = markers,-            angleMode = angleMode,-            viewport = GraphViewport(centerX, centerY, scale),-        )--    fun setViewSize(widthPx: Float, heightPx: Float) {+        get() =+            GraphUiState(+                functions = functions,+                markers = markers,+                angleMode = angleMode,+                viewport = GraphViewport(centerX, centerY, scale),+            )++    fun setViewSize(+        widthPx: Float,+        heightPx: Float,+    ) {         viewWidthPx = widthPx         viewHeightPx = heightPx     }@@ -96,15 +105,19 @@ class GraphTab {      * marker removes it; touching anywhere else reveals the nearest notable point in range,      * across every curve on screen — Cartesian, polar, and crossings between the two.      */-    fun tapGraph(at: GraphPoint, radius: Double) {+    fun tapGraph(+        at: GraphPoint,+        radius: Double,+    ) {         val hit = markers.minByOrNull { hypot(it.point.x - at.x, it.point.y - at.y) }         if (hit != null && hypot(hit.point.x - at.x, hit.point.y - at.y) <= radius) {             markers.remove(hit)             return         }-        val feature = GraphAnalysis-            .featuresNear(sampleCurves(viewWidthPx, viewHeightPx), at, radius, angleMode)-            .firstOrNull() ?: return+        val feature =+            GraphAnalysis+                .featuresNear(sampleCurves(viewWidthPx, viewHeightPx), at, radius, angleMode)+                .firstOrNull() ?: return         markers.add(GraphMarker(feature.point, feature.kind, feature.curveIds))     } @@ -112,7 +125,10 @@ class GraphTab {      * 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.      */-    private fun sampleCurves(widthPx: Float, heightPx: Float): List<SampledCurve> {+    private fun sampleCurves(+        widthPx: Float,+        heightPx: Float,+    ): List<SampledCurve> {         if (widthPx <= 0f || heightPx <= 0f) return emptyList()         val (xMin, xMax, yMin, yMax) = GraphViewport(centerX, centerY, scale).bounds(widthPx, heightPx)         return functions.filter { it.enabled && it.text.isNotBlank() }.mapNotNull { fn ->@@ -125,19 +141,41 @@ class GraphTab { }  /** Distinct, colour-blind-friendly curve colours, reused cyclically. */-internal val GraphTabColors = listOf(-    Color(0xFF4285F4), Color(0xFFEA4335), Color(0xFF34A853),-    Color(0xFFFF9800), Color(0xFF9C27B0), Color(0xFF00BCD4),-)+internal val GraphTabColors =+    listOf(+        Color(0xFF4285F4),+        Color(0xFFEA4335),+        Color(0xFF34A853),+        Color(0xFFFF9800),+        Color(0xFF9C27B0),+        Color(0xFF00BCD4),+    )  /** Adapts [GraphTab] to the [GraphActions] interface for ViewModel delegation. */-internal fun graphActionAdapter(tab: GraphTab): GraphActions = object : GraphActions {-    override fun addFunction() = tab.addFunction()-    override fun updateFunction(id: Long, text: String) = tab.updateFunction(id, text)-    override fun toggleFunction(id: Long) = tab.toggleFunction(id)-    override fun togglePolar(id: Long) = tab.togglePolar(id)-    override fun removeFunction(id: Long) = tab.removeFunction(id)-    override fun setViewSize(widthPx: Float, heightPx: Float) = tab.setViewSize(widthPx, heightPx)-    override fun setViewport(viewport: GraphViewport) = tab.setViewport(viewport)-    override fun tapGraph(at: GraphPoint, radius: Double) = tab.tapGraph(at, radius)-}+internal fun graphActionAdapter(tab: GraphTab): GraphActions =+    object : GraphActions {+        override fun addFunction() = tab.addFunction()++        override fun updateFunction(+            id: Long,+            text: String,+        ) = tab.updateFunction(id, text)++        override fun toggleFunction(id: Long) = tab.toggleFunction(id)++        override fun togglePolar(id: Long) = tab.togglePolar(id)++        override fun removeFunction(id: Long) = tab.removeFunction(id)++        override fun setViewSize(+            widthPx: Float,+            heightPx: Float,+        ) = tab.setViewSize(widthPx, heightPx)++        override fun setViewport(viewport: GraphViewport) = tab.setViewport(viewport)++        override fun tapGraph(+            at: GraphPoint,+            radius: Double,+        ) = tab.tapGraph(at, radius)+    }
calculator/src/main/java/com/vayunmathur/calculator/platform/UnitConverterTab.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/platform/UnitConverterTab.kt b/calculator/src/main/java/com/vayunmathur/calculator/platform/UnitConverterTab.ktindex df0806c9a8..453229fb3c 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/platform/UnitConverterTab.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/platform/UnitConverterTab.kt@@ -1,18 +1,15 @@ package com.vayunmathur.calculator.platform -import com.vayunmathur.calculator.network.CurrencyRatesDto--import com.vayunmathur.calculator.network.CurrencyApi--import com.vayunmathur.calculator.domain.UnitCategory-import com.vayunmathur.calculator.domain.UnitRegistry-import com.vayunmathur.calculator.domain.formatResult- import android.app.Application import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue+import com.vayunmathur.calculator.domain.UnitCategory+import com.vayunmathur.calculator.domain.UnitRegistry+import com.vayunmathur.calculator.domain.formatResult+import com.vayunmathur.calculator.network.CurrencyApi+import com.vayunmathur.calculator.network.CurrencyRatesDto import com.vayunmathur.calculator.widget.UnitsGlanceWidget import com.vayunmathur.library.util.DataStoreUtils import com.vayunmathur.library.widgets.updateWidget@@ -50,7 +47,10 @@ class UnitConverterTab(     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,+        UnitRegistry.categories[0]+            .units+            .getOrElse(1) { UnitRegistry.categories[0].units[0] }+            .token,     )         private set     var converterValueText by mutableStateOf("1")@@ -147,7 +147,10 @@ class UnitConverterTab(         refreshUnitsWidget()     } -    private fun persist(key: String, value: String) {+    private fun persist(+        key: String,+        value: String,+    ) {         scope?.launch { dataStore.setString(key, value) }     } @@ -166,7 +169,10 @@ class UnitConverterTab(         rememberUnits()     } -    fun setConverterInput(text: String) { converterValueText = text }+    fun setConverterInput(text: String) {+        converterValueText = text+    }+     fun swapUnits() {         val categories = converterCategories         val swappedInput = convert(categories[converterCategoryIndex.coerceIn(categories.indices)])@@ -198,8 +204,7 @@ class UnitConverterTab(                             applyRememberedUnits(category)                         }                     }-                }-                .onFailure { currencyError = "Couldn't load exchange rates" }+                }.onFailure { currencyError = "Couldn't load exchange rates" }             currencyLoading = false         }     }@@ -236,9 +241,14 @@ class UnitConverterTab( internal fun converterActionAdapter(tab: UnitConverterTab): UnitConverterActions =     object : UnitConverterActions {         override fun selectCategory(index: Int) = tab.selectCategory(index)+         override fun setFrom(token: String) = tab.setFrom(token)+         override fun setTo(token: String) = tab.setTo(token)+         override fun setConverterInput(text: String) = tab.setConverterInput(text)+         override fun swapUnits() = tab.swapUnits()+         override fun retryCurrency() = tab.retryCurrency()     }
calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorDialogs.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorDialogs.kt b/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorDialogs.ktindex 98632f8070..4a0990a39b 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorDialogs.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorDialogs.kt@@ -30,10 +30,9 @@ import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.vayunmathur.calculator.R+import com.vayunmathur.calculator.domain.UnitCategory import com.vayunmathur.calculator.platform.CalculatorActions import com.vayunmathur.calculator.platform.CalculatorUiState-import com.vayunmathur.calculator.domain.UnitCategory-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.ModalBottomSheet@@ -45,10 +44,14 @@ import java.time.Instant import java.time.LocalDate import java.time.ZoneId import java.time.ZoneOffset+import com.vayunmathur.library.ui.R as UiR  @OptIn(ExperimentalMaterial3Api::class) @Composable-internal fun DatePickerModal(onDismiss: () -> Unit, onConfirm: (Long) -> Unit) {+internal fun DatePickerModal(+    onDismiss: () -> Unit,+    onConfirm: (Long) -> Unit,+) {     val dateState = rememberDatePickerState()     DatePickerDialog(         onDismissRequest = onDismiss,@@ -65,7 +68,10 @@ internal fun DatePickerModal(onDismiss: () -> Unit, onConfirm: (Long) -> Unit) {  @OptIn(ExperimentalMaterial3Api::class) @Composable-internal fun TimePickerModal(onDismiss: () -> Unit, onConfirm: (Int, Int) -> Unit) {+internal fun TimePickerModal(+    onDismiss: () -> Unit,+    onConfirm: (Int, Int) -> Unit,+) {     val timeState = rememberTimePickerState()     AlertDialog(         onDismissRequest = onDismiss,@@ -83,22 +89,41 @@ internal fun TimePickerModal(onDismiss: () -> Unit, onConfirm: (Int, Int) -> Uni /** The system date picker returns UTC midnight of the chosen day; reinterpret that calendar day  * at local midnight so the stored instant reads back as that date. */ internal fun localMidnightSeconds(utcDateMillis: Long): Long =-    Instant.ofEpochMilli(utcDateMillis).atZone(ZoneOffset.UTC).toLocalDate()-        .atStartOfDay(ZoneId.systemDefault()).toEpochSecond()+    Instant+        .ofEpochMilli(utcDateMillis)+        .atZone(ZoneOffset.UTC)+        .toLocalDate()+        .atStartOfDay(ZoneId.systemDefault())+        .toEpochSecond()  /** Combine a picked calendar day (UTC midnight millis) with a local time-of-day into an instant. */-internal fun combineDateTimeSeconds(utcDateMillis: Long, hour: Int, minute: Int): Long =-    Instant.ofEpochMilli(utcDateMillis).atZone(ZoneOffset.UTC).toLocalDate()-        .atTime(hour, minute).atZone(ZoneId.systemDefault()).toEpochSecond()+internal fun combineDateTimeSeconds(+    utcDateMillis: Long,+    hour: Int,+    minute: Int,+): Long =+    Instant+        .ofEpochMilli(utcDateMillis)+        .atZone(ZoneOffset.UTC)+        .toLocalDate()+        .atTime(hour, minute)+        .atZone(ZoneId.systemDefault())+        .toEpochSecond()  /**  * A time-of-day picked with no date: today at that local time. Kept absolute (an instant)  * rather than a duration so 2 AM never casts to 2 hours — `5 AM + 2 AM` errors, matching the  * engine's rule that two instants only subtract.  */-internal fun todayAtTimeSeconds(hour: Int, minute: Int): Long =-    LocalDate.now(ZoneId.systemDefault()).atTime(hour, minute)-        .atZone(ZoneId.systemDefault()).toEpochSecond()+internal fun todayAtTimeSeconds(+    hour: Int,+    minute: Int,+): Long =+    LocalDate+        .now(ZoneId.systemDefault())+        .atTime(hour, minute)+        .atZone(ZoneId.systemDefault())+        .toEpochSecond()  @OptIn(ExperimentalLayoutApi::class) @Composable@@ -112,15 +137,16 @@ internal fun UnitPickerSheet(     // (empty units mark it as such below), so it lives here rather than in UnitRegistry — the     // parser, output selector and widget never see it.     val absoluteTimeName = stringResource(R.string.absolute_time)-    val categories = remember(state.unitCategories, absoluteTimeName) {-        val list = state.unitCategories.filter { it.inEquations }.toMutableList()-        val timeIndex = list.indexOfFirst { it.name == "Time" }-        list.add(-            if (timeIndex >= 0) timeIndex + 1 else list.size,-            UnitCategory(absoluteTimeName, emptyList(), inEquations = false),-        )-        list-    }+    val categories =+        remember(state.unitCategories, absoluteTimeName) {+            val list = state.unitCategories.filter { it.inEquations }.toMutableList()+            val timeIndex = list.indexOfFirst { it.name == "Time" }+            list.add(+                if (timeIndex >= 0) timeIndex + 1 else list.size,+                UnitCategory(absoluteTimeName, emptyList(), inEquations = false),+            )+            list+        }     var categoryIndex by remember { mutableIntStateOf(0) }     // Which absolute-time picker (if any) is open. DtDate/DtTime are the two steps of the     // combined date-and-time flow.@@ -163,11 +189,16 @@ internal fun UnitPickerSheet(                                     .fillMaxWidth()                                     .verticalScroll(rememberScrollState())                                     .padding(16.dp),-                                horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(8.dp),+                                horizontalArrangement =+                                    androidx.compose.foundation.layout.Arrangement+                                        .spacedBy(8.dp),                             ) {                                 category.units.forEach { unit ->                                     AssistChip(-                                        onClick = { actions.append(unit.token); onDismiss() },+                                        onClick = {+                                            actions.append(unit.token)+                                            onDismiss()+                                        },                                         label = { Text(unit.symbol) },                                     )                                 }@@ -180,24 +211,28 @@ internal fun UnitPickerSheet(     }      when (absPicker) {-        AbsoluteTimePicker.Date -> DatePickerModal(onDismiss = { absPicker = AbsoluteTimePicker.None }) { millis ->-            actions.insertInstant(localMidnightSeconds(millis))-            onDismiss()-        }-        AbsoluteTimePicker.DtDate -> DatePickerModal(onDismiss = { absPicker = AbsoluteTimePicker.None }) { millis ->-            dtDateMillis = millis-            absPicker = AbsoluteTimePicker.DtTime-        }+        AbsoluteTimePicker.Date ->+            DatePickerModal(onDismiss = { absPicker = AbsoluteTimePicker.None }) { millis ->+                actions.insertInstant(localMidnightSeconds(millis))+                onDismiss()+            }+        AbsoluteTimePicker.DtDate ->+            DatePickerModal(onDismiss = { absPicker = AbsoluteTimePicker.None }) { millis ->+                dtDateMillis = millis+                absPicker = AbsoluteTimePicker.DtTime+            }         // Time-of-day with no date: today at that time, kept absolute so 2 AM never casts         // to 2 hours — `5 AM + 2 AM` errors like any other instant + instant.-        AbsoluteTimePicker.Time -> TimePickerModal(onDismiss = { absPicker = AbsoluteTimePicker.None }) { hour, minute ->-            actions.insertInstant(todayAtTimeSeconds(hour, minute))-            onDismiss()-        }-        AbsoluteTimePicker.DtTime -> TimePickerModal(onDismiss = { absPicker = AbsoluteTimePicker.None }) { hour, minute ->-            dtDateMillis?.let { actions.insertInstant(combineDateTimeSeconds(it, hour, minute)) }-            onDismiss()-        }+        AbsoluteTimePicker.Time ->+            TimePickerModal(onDismiss = { absPicker = AbsoluteTimePicker.None }) { hour, minute ->+                actions.insertInstant(todayAtTimeSeconds(hour, minute))+                onDismiss()+            }+        AbsoluteTimePicker.DtTime ->+            TimePickerModal(onDismiss = { absPicker = AbsoluteTimePicker.None }) { hour, minute ->+                dtDateMillis?.let { actions.insertInstant(combineDateTimeSeconds(it, hour, minute)) }+                onDismiss()+            }         AbsoluteTimePicker.None -> {}     } }@@ -211,13 +246,21 @@ internal enum class AbsoluteTimePicker { None, Date, Time, DtDate, DtTime }  * `#<epoch>` instants into the keypad input.  */ @Composable-private fun AbsoluteTimePickers(onPick: (AbsoluteTimePicker) -> Unit, modifier: Modifier = Modifier) {+private fun AbsoluteTimePickers(+    onPick: (AbsoluteTimePicker) -> Unit,+    modifier: Modifier = Modifier,+) {     FlowRow(         modifier,-        horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(8.dp),+        horizontalArrangement =+            androidx.compose.foundation.layout.Arrangement+                .spacedBy(8.dp),     ) {         AssistChip(onClick = { onPick(AbsoluteTimePicker.Date) }, label = { Text(stringResource(R.string.key_date)) })         AssistChip(onClick = { onPick(AbsoluteTimePicker.Time) }, label = { Text(stringResource(R.string.key_time)) })-        AssistChip(onClick = { onPick(AbsoluteTimePicker.DtDate) }, label = { Text(stringResource(R.string.key_datetime)) })+        AssistChip(+            onClick = { onPick(AbsoluteTimePicker.DtDate) },+            label = { Text(stringResource(R.string.key_datetime)) },+        )     } }
calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorKeypad.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorKeypad.kt b/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorKeypad.ktindex 6569e0d83a..5c95227535 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorKeypad.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorKeypad.kt@@ -58,23 +58,30 @@ internal class Key( )  @Composable-internal fun RowScope.KeyButton(key: Key, actions: CalculatorActions, second: Boolean, onToggleSecond: () -> Unit) {+internal fun RowScope.KeyButton(+    key: Key,+    actions: CalculatorActions,+    second: Boolean,+    onToggleSecond: () -> Unit,+) {     val showSecond = second && key.second != null     val label = if (showSecond) key.second else key.label     val secondActive = key.emphasis == KeyEmphasis.Toggle && second     // A light key tick on every press. Scoped to KeyButton so only the keypad keys tick —     // the toolbar, dialogs and unit chips stay silent.     val haptics = rememberHaptics()-    val colors = when (key.emphasis) {-        KeyEmphasis.Digit -> ButtonDefaults.filledTonalButtonColors()-        KeyEmphasis.Operator -> ButtonDefaults.buttonColors(-            containerColor = MaterialTheme.colorScheme.secondaryContainer,-            contentColor = MaterialTheme.colorScheme.onSecondaryContainer,-        )-        KeyEmphasis.Primary -> ButtonDefaults.buttonColors()-        KeyEmphasis.Function -> ButtonDefaults.textButtonColors()-        KeyEmphasis.Toggle -> if (secondActive) ButtonDefaults.buttonColors() else ButtonDefaults.textButtonColors()-    }+    val colors =+        when (key.emphasis) {+            KeyEmphasis.Digit -> ButtonDefaults.filledTonalButtonColors()+            KeyEmphasis.Operator ->+                ButtonDefaults.buttonColors(+                    containerColor = MaterialTheme.colorScheme.secondaryContainer,+                    contentColor = MaterialTheme.colorScheme.onSecondaryContainer,+                )+            KeyEmphasis.Primary -> ButtonDefaults.buttonColors()+            KeyEmphasis.Function -> ButtonDefaults.textButtonColors()+            KeyEmphasis.Toggle -> if (secondActive) ButtonDefaults.buttonColors() else ButtonDefaults.textButtonColors()+        }     Button(         onClick = {             haptics.keyPress()@@ -160,7 +167,11 @@ internal fun buildCalculatorRows(angleMode: AngleMode): List<List<Key>> {  * layouts share one implementation. Past calculations stack above the current input,  * newest directly above it, each ringed by dividers. */ @Composable-internal fun DisplayColumn(state: CalculatorUiState, actions: CalculatorActions, modifier: Modifier = Modifier) {+internal fun DisplayColumn(+    state: CalculatorUiState,+    actions: CalculatorActions,+    modifier: Modifier = Modifier,+) {     val verticalScroll = rememberScrollState()     // New evaluations prepend to history; keep the current equation pinned in view.     LaunchedEffect(state.history.size) { verticalScroll.scrollTo(verticalScroll.maxValue) }@@ -182,8 +193,12 @@ internal fun DisplayColumn(state: CalculatorUiState, actions: CalculatorActions,             }         }         Text(-            com.vayunmathur.calculator.domain.renderInputForDisplay(state.input).ifEmpty { "0" }-                .replace("*", "×").replace("/", "÷").replace("-", "−"),+            com.vayunmathur.calculator.domain+                .renderInputForDisplay(state.input)+                .ifEmpty { "0" }+                .replace("*", "×")+                .replace("/", "÷")+                .replace("-", "−"),             modifier = Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()),             textAlign = TextAlign.End,             fontSize = 38.sp,@@ -215,12 +230,17 @@ internal fun DisplayColumn(state: CalculatorUiState, actions: CalculatorActions,  /** One past calculation in the inline history stack: tapping reuses its result. */ @Composable-private fun HistoryRow(entry: HistoryEntry, actions: CalculatorActions, modifier: Modifier = Modifier) {-    val historyDescription = stringResource(-        R.string.history_entry_content_description,-        entry.expression,-        entry.result,-    )+private fun HistoryRow(+    entry: HistoryEntry,+    actions: CalculatorActions,+    modifier: Modifier = Modifier,+) {+    val historyDescription =+        stringResource(+            R.string.history_entry_content_description,+            entry.expression,+            entry.result,+        )     Column(         modifier             .fillMaxWidth()@@ -251,7 +271,10 @@ private fun HistoryRow(entry: HistoryEntry, actions: CalculatorActions, modifier  * layouts share one implementation. */ @OptIn(ExperimentalLayoutApi::class) @Composable-private fun UnitOptionsRow(state: CalculatorUiState, actions: CalculatorActions) {+private fun UnitOptionsRow(+    state: CalculatorUiState,+    actions: CalculatorActions,+) {     Column(Modifier.fillMaxWidth().padding(top = 8.dp)) {         Text(             stringResource(R.string.convert_to),
calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorLandscape.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorLandscape.kt b/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorLandscape.ktindex 2548d7eed6..cbd155f584 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorLandscape.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorLandscape.kt@@ -16,9 +16,9 @@ import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp+import com.vayunmathur.calculator.domain.renderInputForDisplay import com.vayunmathur.calculator.platform.CalculatorActions import com.vayunmathur.calculator.platform.CalculatorUiState-import com.vayunmathur.calculator.domain.renderInputForDisplay import com.vayunmathur.library.ui.Button import com.vayunmathur.library.ui.ButtonDefaults import com.vayunmathur.library.ui.MaterialTheme@@ -31,10 +31,16 @@ import com.vayunmathur.library.ui.rememberHaptics  * stack, unit chips, large type — assumes portrait height and would eat the keypad's rows here.  */ @Composable-internal fun LandscapeDisplay(state: CalculatorUiState, modifier: Modifier = Modifier) {-    val equation = renderInputForDisplay(state.input)-        .ifEmpty { "0" }-        .replace("*", "×").replace("/", "÷").replace("-", "−")+internal fun LandscapeDisplay(+    state: CalculatorUiState,+    modifier: Modifier = Modifier,+) {+    val equation =+        renderInputForDisplay(state.input)+            .ifEmpty { "0" }+            .replace("*", "×")+            .replace("/", "÷")+            .replace("-", "−")     Column(modifier.padding(horizontal = 16.dp, vertical = 4.dp), horizontalAlignment = Alignment.End) {         Text(             equation,@@ -115,16 +121,18 @@ private fun RowScope.LandscapeKeyButton(     val secondActive = key.emphasis == KeyEmphasis.Toggle && second     // A light key tick on every press, matching KeyButton.     val haptics = rememberHaptics()-    val colors = when (key.emphasis) {-        KeyEmphasis.Digit -> ButtonDefaults.filledTonalButtonColors()-        KeyEmphasis.Operator -> ButtonDefaults.buttonColors(-            containerColor = MaterialTheme.colorScheme.secondaryContainer,-            contentColor = MaterialTheme.colorScheme.onSecondaryContainer,-        )-        KeyEmphasis.Primary -> ButtonDefaults.buttonColors()-        KeyEmphasis.Function -> ButtonDefaults.textButtonColors()-        KeyEmphasis.Toggle -> if (secondActive) ButtonDefaults.buttonColors() else ButtonDefaults.textButtonColors()-    }+    val colors =+        when (key.emphasis) {+            KeyEmphasis.Digit -> ButtonDefaults.filledTonalButtonColors()+            KeyEmphasis.Operator ->+                ButtonDefaults.buttonColors(+                    containerColor = MaterialTheme.colorScheme.secondaryContainer,+                    contentColor = MaterialTheme.colorScheme.onSecondaryContainer,+                )+            KeyEmphasis.Primary -> ButtonDefaults.buttonColors()+            KeyEmphasis.Function -> ButtonDefaults.textButtonColors()+            KeyEmphasis.Toggle -> if (secondActive) ButtonDefaults.buttonColors() else ButtonDefaults.textButtonColors()+        }     Button(         onClick = {             haptics.keyPress()
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 d2700be941..077db42442 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorPage.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorPage.kt@@ -1,33 +1,12 @@ package com.vayunmathur.calculator.ui -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.foundation.layout.widthIn 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.Modifier-import androidx.compose.ui.unit.dp-import com.vayunmathur.calculator.platform.CalculatorActions-import com.vayunmathur.calculator.platform.CalculatorUiState import com.vayunmathur.calculator.platform.CalculatorViewModel-import com.vayunmathur.library.ui.AppBarAlignment-import com.vayunmathur.library.ui.AppScaffold-import com.vayunmathur.library.ui.HorizontalDivider-import com.vayunmathur.library.ui.IconButton-import com.vayunmathur.library.ui.IconRuler-import com.vayunmathur.library.ui.VerticalDivider-import com.vayunmathur.library.ui.isCompactHeight-import com.vayunmathur.library.ui.isExpandedWidth  /** Binds [CalculatorViewModel] to the stateless [CalculatorScreen]. */ @Composable fun CalculatorPage(viewModel: CalculatorViewModel) {     CalculatorScreen(state = viewModel.calculatorUiState, actions = viewModel) }-
calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorScreen.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorScreen.kt b/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorScreen.ktindex 5be9b377eb..932a3bf485 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorScreen.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorScreen.kt@@ -14,7 +14,6 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.vayunmathur.calculator.platform.CalculatorActions import com.vayunmathur.calculator.platform.CalculatorUiState-import com.vayunmathur.calculator.platform.CalculatorViewModel import com.vayunmathur.library.ui.AppBarAlignment import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.HorizontalDivider@@ -85,7 +84,13 @@ fun CalculatorScreen(                 Row(Modifier.fillMaxSize().padding(padding).padding(16.dp)) {                     DisplayColumn(state, actions, Modifier.weight(1f).fillMaxSize())                     VerticalDivider()-                    KeypadColumn(rows, actions, second, { second = !second }, Modifier.weight(1f).widthIn(max = 560.dp).fillMaxSize())+                    KeypadColumn(+                        rows,+                        actions,+                        second,+                        { second = !second },+                        Modifier.weight(1f).widthIn(max = 560.dp).fillMaxSize(),+                    )                 }             }             else -> {
calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorWidgetSettingsActivity.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorWidgetSettingsActivity.kt b/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorWidgetSettingsActivity.ktindex feef575526..446ebc6999 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorWidgetSettingsActivity.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorWidgetSettingsActivity.kt@@ -38,7 +38,6 @@ import kotlinx.coroutines.launch  * be styled differently, and each takes effect as it is changed rather than on a Done button.  */ class CalculatorWidgetSettingsActivity : ComponentActivity() {-     private var appWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID      override fun onCreate(savedInstanceState: Bundle?) {@@ -117,7 +116,7 @@ class CalculatorWidgetSettingsActivity : ComponentActivity() {     private suspend fun readTransparent(): Boolean {         val glanceId = glanceId() ?: return false         return getAppWidgetState(this, PreferencesGlanceStateDefinition, glanceId)[-            CalculatorTransparentKey+            CalculatorTransparentKey,         ] == true     } @@ -130,7 +129,8 @@ class CalculatorWidgetSettingsActivity : ComponentActivity() {     }      /** Null while the launcher has an id Glance has not bound a widget to yet. */-    private suspend fun glanceId(): GlanceId? = runCatching {-        GlanceAppWidgetManager(this).getGlanceIdBy(appWidgetId)-    }.getOrNull()+    private suspend fun glanceId(): GlanceId? =+        runCatching {+            GlanceAppWidgetManager(this).getGlanceIdBy(appWidgetId)+        }.getOrNull() }
calculator/src/main/java/com/vayunmathur/calculator/ui/GraphPage.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/ui/GraphPage.kt b/calculator/src/main/java/com/vayunmathur/calculator/ui/GraphPage.ktindex 90e466a202..32d3b696db 100644--- a/calculator/src/main/java/com/vayunmathur/calculator/ui/GraphPage.kt+++ b/calculator/src/main/java/com/vayunmathur/calculator/ui/GraphPage.kt@@ -1,7 +1,5 @@ package com.vayunmathur.calculator.ui -import androidx.compose.ui.res.stringResource-import com.vayunmathur.calculator.R import androidx.compose.foundation.Canvas import androidx.compose.foundation.background import androidx.compose.foundation.border@@ -14,7 +12,6 @@ import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer-import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding@@ -37,24 +34,23 @@ import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.layout.onSizeChanged+import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.drawText import androidx.compose.ui.text.rememberTextMeasurer import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp-import com.vayunmathur.calculator.domain.AngleMode-import com.vayunmathur.calculator.platform.CalculatorViewModel+import com.vayunmathur.calculator.R import com.vayunmathur.calculator.domain.Expression import com.vayunmathur.calculator.domain.FeatureKind import com.vayunmathur.calculator.domain.GraphAnalysis+import com.vayunmathur.calculator.domain.GraphPoint+import com.vayunmathur.calculator.domain.formatResult+import com.vayunmathur.calculator.platform.CalculatorViewModel import com.vayunmathur.calculator.platform.GraphActions import com.vayunmathur.calculator.platform.GraphFunction import com.vayunmathur.calculator.platform.GraphUiState-import com.vayunmathur.calculator.domain.GraphPoint-import com.vayunmathur.calculator.domain.formatResult-import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.AssistChip-import com.vayunmathur.library.ui.HorizontalDivider import com.vayunmathur.library.ui.IconAdd import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.IconClose@@ -64,9 +60,6 @@ import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.OutlinedTextField import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.ToggleButton-import com.vayunmathur.library.ui.VerticalDivider-import com.vayunmathur.library.ui.isCompactHeight-import com.vayunmathur.library.ui.isExpandedWidth import kotlin.math.abs import kotlin.math.ceil import kotlin.math.floor@@ -79,12 +72,15 @@ fun GraphPage(viewModel: CalculatorViewModel) {     GraphScreen(state = viewModel.graphUiState, actions = viewModel) } - /** How close a touch has to land, in dp, for a notable point to be revealed. */ private val TouchSlop = 28.dp  @Composable-internal fun GraphCanvas(state: GraphUiState, actions: GraphActions, modifier: Modifier) {+internal fun GraphCanvas(+    state: GraphUiState,+    actions: GraphActions,+    modifier: Modifier,+) {     val axisColor = MaterialTheme.colorScheme.onSurface     val gridColor = MaterialTheme.colorScheme.outlineVariant     val labelColor = MaterialTheme.colorScheme.onSurfaceVariant@@ -99,18 +95,21 @@ internal fun GraphCanvas(state: GraphUiState, actions: GraphActions, modifier: M      // Colour lookup for markers, and the localised kind names, resolved outside the draw

Diff truncated.