Modern Apps git

← Modern-Apps.git

new app: calculator

Commit
e17328067514124f955b6623aeeda50ff588cda2
Author
Vayun Mathur <[email protected]>
When
2026-07-30 20:55 UTC (4 months ago)
Parents
ffb1605

Diff

calculator/build.gradle.kts
diff --git a/calculator/build.gradle.kts b/calculator/build.gradle.ktsnew file mode 100644index 0000000000..f6880a802c--- /dev/null+++ b/calculator/build.gradle.kts@@ -0,0 +1,19 @@+plugins {+    id("common-conventions-app")+    id("common-conventions-metadata")+    alias(libs.plugins.ksp)+}++launcherIcon {+    symbol = "calculate"+}++android {+    defaultConfig {+        applicationId = "com.vayunmathur.calculator"+    }+}++dependencies {+    implementation(libs.androidx.datastore.preferences)+}
calculator/src/main/AndroidManifest.xml
diff --git a/calculator/src/main/AndroidManifest.xml b/calculator/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..baf0cf9707--- /dev/null+++ b/calculator/src/main/AndroidManifest.xml@@ -0,0 +1,24 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++    <application+        android:allowBackup="true"+        android:dataExtractionRules="@xml/data_extraction_rules"+        android:icon="@mipmap/ic_launcher"+        android:label="@string/app_name"+        android:roundIcon="@mipmap/ic_launcher"+        android:supportsRtl="true"+        android:theme="@style/Theme.General">+        <activity+            android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"+            android:name=".MainActivity"+            android:exported="true"+            android:theme="@style/Theme.General">+            <intent-filter>+                <action android:name="android.intent.action.MAIN" />+                <category android:name="android.intent.category.LAUNCHER" />+            </intent-filter>+        </activity>+    </application>++</manifest>
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.ktnew file mode 100644index 0000000000..f61fb59cfa--- /dev/null+++ b/calculator/src/main/java/com/vayunmathur/calculator/MainActivity.kt@@ -0,0 +1,65 @@+package com.vayunmathur.calculator++import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.activity.enableEdgeToEdge+import androidx.activity.viewModels+import androidx.compose.runtime.Composable+import com.vayunmathur.calculator.ui.CalculatorPage+import com.vayunmathur.calculator.ui.GraphPage+import com.vayunmathur.calculator.util.CalculatorViewModel+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.ui.IconCalculate+import com.vayunmathur.library.ui.IconFunctions+import com.vayunmathur.library.util.BottomBarItem+import com.vayunmathur.library.util.BottomNavBar+import com.vayunmathur.library.util.MainNavigation+import com.vayunmathur.library.util.NavKey+import com.vayunmathur.library.util.rememberNavBackStack+import kotlinx.serialization.Serializable++class MainActivity : ComponentActivity() {+    private val viewModel: CalculatorViewModel by viewModels()++    override fun onCreate(savedInstanceState: Bundle?) {+        super.onCreate(savedInstanceState)+        enableEdgeToEdge()+        setContent {+            DynamicTheme {+                Navigation(viewModel)+            }+        }+    }+}++@Serializable+sealed interface Route : NavKey {+    @Serializable+    data object Calculator : Route++    @Serializable+    data object Graph : Route+}++@Composable+fun Navigation(viewModel: CalculatorViewModel) {+    val backStack = rememberNavBackStack<Route>(Route.Calculator)+    val current = backStack.last()+    MainNavigation(+        backStack,+        bottomBar = {+            BottomNavBar(+                backStack,+                listOf(+                    BottomBarItem("Calculator", Route.Calculator) { IconCalculate() },+                    BottomBarItem("Graph", Route.Graph) { IconFunctions() },+                ),+                current,+            )+        },+    ) {+        entry<Route.Calculator> { CalculatorPage(viewModel) }+        entry<Route.Graph> { GraphPage(viewModel) }+    }+}
calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorPage.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorPage.kt b/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorPage.ktnew file mode 100644index 0000000000..c46bc309c5--- /dev/null+++ b/calculator/src/main/java/com/vayunmathur/calculator/ui/CalculatorPage.kt@@ -0,0 +1,244 @@+package com.vayunmathur.calculator.ui++import androidx.compose.foundation.horizontalScroll+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.RowScope+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import com.vayunmathur.calculator.util.AngleMode+import com.vayunmathur.calculator.util.CalculatorViewModel+import com.vayunmathur.library.ui.AlertDialog+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.ButtonDefaults+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.CenterAlignedTopAppBar+import com.vayunmathur.library.ui.HorizontalDivider+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconHistory+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Scaffold+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton++private enum class KeyEmphasis { Digit, Operator, Primary, Function, Toggle }++/**+ * A keypad key. [second]/[secondPress] give an alternate label+action shown when the+ * "2nd" modifier is active (e.g. sin → sin⁻¹). [weight] lets a key span extra columns.+ */+private class Key(+    val label: String,+    val emphasis: KeyEmphasis = KeyEmphasis.Digit,+    val weight: Float = 1f,+    val second: String? = null,+    val onPress: (CalculatorViewModel) -> Unit,+    val secondPress: ((CalculatorViewModel) -> Unit)? = null,+)++@Composable+private fun RowScope.KeyButton(key: Key, viewModel: CalculatorViewModel, 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+    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 = {+            when {+                key.emphasis == KeyEmphasis.Toggle -> onToggleSecond()+                showSecond -> key.secondPress?.invoke(viewModel)+                else -> key.onPress(viewModel)+            }+        },+        modifier = Modifier.weight(key.weight).height(50.dp).padding(2.dp),+        shape = RoundedCornerShape(16.dp),+        colors = colors,+        contentPadding = PaddingValues(0.dp),+    ) {+        Text(label, fontSize = if (label.length >= 4) 13.sp else 18.sp, maxLines = 1)+    }+}++@Composable+fun CalculatorPage(viewModel: CalculatorViewModel) {+    var showHistory by remember { mutableStateOf(false) }+    var second by remember { mutableStateOf(false) }++    fun ins(text: String): (CalculatorViewModel) -> Unit = { it.append(text) }++    val rows: List<List<Key>> = listOf(+        listOf(+            Key("2nd", KeyEmphasis.Toggle) {},+            Key("π", KeyEmphasis.Function, second = "φ", onPress = ins("π"), secondPress = ins("phi")),+            Key("e", KeyEmphasis.Function, second = "τ", onPress = ins("e"), secondPress = ins("tau")),+            Key("!", KeyEmphasis.Function) { it.append("!") },+            Key("AC", KeyEmphasis.Operator) { it.clear() },+        ),+        listOf(+            Key("sin", KeyEmphasis.Function, second = "sin⁻¹", onPress = ins("sin("), secondPress = ins("asin(")),+            Key("cos", KeyEmphasis.Function, second = "cos⁻¹", onPress = ins("cos("), secondPress = ins("acos(")),+            Key("tan", KeyEmphasis.Function, second = "tan⁻¹", onPress = ins("tan("), secondPress = ins("atan(")),+            Key("ln", KeyEmphasis.Function, second = "eˣ", onPress = ins("ln("), secondPress = ins("e^(")),+            Key("log", KeyEmphasis.Function, second = "10ˣ", onPress = ins("log("), secondPress = ins("10^(")),+        ),+        listOf(+            Key("^", KeyEmphasis.Function, second = "x²", onPress = ins("^"), secondPress = ins("^2")),+            Key("√", KeyEmphasis.Function, second = "∛", onPress = ins("√("), secondPress = ins("cbrt(")),+            Key("(", KeyEmphasis.Function) { it.append("(") },+            Key(")", KeyEmphasis.Function) { it.append(")") },+            Key(",", KeyEmphasis.Function, second = "EE", onPress = ins(","), secondPress = ins("E")),+        ),+        listOf(+            Key("MC", KeyEmphasis.Function) { it.memoryClear() },+            Key("MR", KeyEmphasis.Function) { it.memoryRecall() },+            Key("M+", KeyEmphasis.Function) { it.memoryAdd() },+            Key("M-", KeyEmphasis.Function) { it.memorySubtract() },+            Key(if (viewModel.angleMode == AngleMode.DEGREES) "DEG" else "RAD", KeyEmphasis.Function) { it.toggleAngleMode() },+        ),+        listOf(+            Key("7") { it.append("7") },+            Key("8") { it.append("8") },+            Key("9") { it.append("9") },+            Key("÷", KeyEmphasis.Operator) { it.append("/") },+            Key("⌫", KeyEmphasis.Operator) { it.backspace() },+        ),+        listOf(+            Key("4") { it.append("4") },+            Key("5") { it.append("5") },+            Key("6") { it.append("6") },+            Key("×", KeyEmphasis.Operator) { it.append("*") },+            Key("%", KeyEmphasis.Operator) { it.append("%") },+        ),+        listOf(+            Key("1") { it.append("1") },+            Key("2") { it.append("2") },+            Key("3") { it.append("3") },+            Key("−", KeyEmphasis.Operator) { it.append("-") },+            Key("nCr", KeyEmphasis.Function, second = "nPr", onPress = ins("nCr("), secondPress = ins("nPr(")),+        ),+        listOf(+            Key("ans", KeyEmphasis.Function) { it.append("ans") },+            Key("0") { it.append("0") },+            Key(".") { it.append(".") },+            Key("+", KeyEmphasis.Operator) { it.append("+") },+            Key("=", KeyEmphasis.Primary) { it.evaluate() },+        ),+    )++    Scaffold(+        topBar = {+            CenterAlignedTopAppBar(+                title = { Text("Calculator") },+                actions = { IconButton({ showHistory = true }) { IconHistory() } },+            )+        },+    ) { padding ->+        Column(Modifier.fillMaxSize().padding(padding)) {+            // ---- Display ----+            Column(+                Modifier.fillMaxWidth().weight(1f).padding(horizontal = 20.dp),+                verticalArrangement = Arrangement.Bottom,+                horizontalAlignment = Alignment.End,+            ) {+                if (viewModel.memory != 0.0) {+                    Text("M", color = MaterialTheme.colorScheme.primary, fontSize = 14.sp)+                }+                Text(+                    viewModel.input.ifEmpty { "0" }+                        .replace("*", "×").replace("/", "÷").replace("-", "−"),+                    modifier = Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()),+                    textAlign = TextAlign.End,+                    fontSize = 38.sp,+                    maxLines = 1,+                    softWrap = false,+                )+                Text(+                    viewModel.preview,+                    modifier = Modifier.fillMaxWidth().padding(top = 6.dp),+                    textAlign = TextAlign.End,+                    fontSize = 24.sp,+                    maxLines = 1,+                    softWrap = false,+                    color = MaterialTheme.colorScheme.onSurfaceVariant,+                )+            }++            HorizontalDivider()++            // ---- Keypad ----+            Column(Modifier.fillMaxWidth().padding(4.dp)) {+                rows.forEach { row ->+                    Row(Modifier.fillMaxWidth()) {+                        row.forEach { key -> KeyButton(key, viewModel, second) { second = !second } }+                    }+                }+            }+        }+    }++    if (showHistory) HistoryDialog(viewModel) { showHistory = false }+}++@Composable+private fun HistoryDialog(viewModel: CalculatorViewModel, onDismiss: () -> Unit) {+    AlertDialog(+        onDismissRequest = onDismiss,+        title = { Text("History") },+        text = {+            if (viewModel.history.isEmpty()) {+                Text("No calculations yet.")+            } else {+                LazyColumn(Modifier.height(320.dp)) {+                    items(viewModel.history) { entry ->+                        Card(+                            onClick = { viewModel.useHistory(entry); onDismiss() },+                            modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp),+                        ) {+                            Column(Modifier.padding(12.dp)) {+                                Text(+                                    entry.expression,+                                    color = MaterialTheme.colorScheme.onSurfaceVariant,+                                    fontSize = 14.sp,+                                )+                                Text("= ${entry.result}", fontSize = 20.sp)+                            }+                        }+                    }+                }+            }+        },+        confirmButton = { TextButton(onDismiss) { Text("Close") } },+        dismissButton = {+            if (viewModel.history.isNotEmpty()) {+                TextButton({ viewModel.clearHistory(); onDismiss() }) { Text("Clear") }+            }+        },+    )+}
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.ktnew file mode 100644index 0000000000..ae19cdd2aa--- /dev/null+++ b/calculator/src/main/java/com/vayunmathur/calculator/ui/GraphPage.kt@@ -0,0 +1,308 @@+package com.vayunmathur.calculator.ui++import androidx.compose.foundation.Canvas+import androidx.compose.foundation.background+import androidx.compose.foundation.gestures.detectTransformGestures+import androidx.compose.foundation.horizontalScroll+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.heightIn+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.Color+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.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.util.AnalysisKind+import com.vayunmathur.calculator.util.AngleMode+import com.vayunmathur.calculator.util.CalculatorViewModel+import com.vayunmathur.calculator.util.Expression+import com.vayunmathur.calculator.util.formatResult+import com.vayunmathur.library.ui.AlertDialog+import com.vayunmathur.library.ui.AssistChip+import com.vayunmathur.library.ui.FilterChip+import com.vayunmathur.library.ui.HorizontalDivider+import com.vayunmathur.library.ui.IconAdd+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconClose+import com.vayunmathur.library.ui.IconVisibilityOff+import com.vayunmathur.library.ui.IconVisible+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedTextField+import com.vayunmathur.library.ui.Scaffold+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.ui.TopAppBar+import kotlin.math.PI+import kotlin.math.abs+import kotlin.math.ceil+import kotlin.math.cos+import kotlin.math.floor+import kotlin.math.log10+import kotlin.math.pow+import kotlin.math.sin++@Composable+fun GraphPage(viewModel: CalculatorViewModel) {+    var showResults by remember { mutableStateOf(false) }+    Scaffold(+        topBar = {+            TopAppBar(+                title = { Text("Graph") },+                actions = {+                    AssistChip(+                        onClick = { viewModel.toggleAngleMode() },+                        label = { Text(if (viewModel.angleMode == AngleMode.DEGREES) "DEG" else "RAD") },+                        modifier = Modifier.padding(end = 12.dp),+                    )+                },+            )+        },+    ) { padding ->+        Column(Modifier.fillMaxSize().padding(padding)) {+            AnalysisBar(viewModel) { showResults = true }+            GraphCanvas(viewModel, Modifier.fillMaxWidth().weight(1f))+            HorizontalDivider()+            FunctionEditors(viewModel)+        }+    }+    if (showResults) {+        AlertDialog(+            onDismissRequest = { showResults = false },+            title = { Text("Analysis") },+            text = {+                LazyColumn(Modifier.heightIn(max = 320.dp)) {+                    items(viewModel.analysisSummary) { line -> Text(line, modifier = Modifier.padding(vertical = 3.dp)) }+                }+            },+            confirmButton = { TextButton({ showResults = false }) { Text("Done") } },+            dismissButton = { TextButton({ viewModel.clearAnalysis(); showResults = false }) { Text("Clear markers") } },+        )+    }+}++/** Horizontally-scrolling row of numeric-analysis actions over the visible window. */+@Composable+private fun AnalysisBar(viewModel: CalculatorViewModel, onResults: () -> Unit) {+    Row(+        Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).padding(horizontal = 8.dp, vertical = 4.dp),+        horizontalArrangement = Arrangement.spacedBy(8.dp),+        verticalAlignment = Alignment.CenterVertically,+    ) {+        AnalysisKind.entries.forEach { kind ->+            val short = when (kind) {+                AnalysisKind.ROOTS -> "Roots"+                AnalysisKind.MINIMA -> "Min"+                AnalysisKind.MAXIMA -> "Max"+                AnalysisKind.INTERSECTIONS -> "Intersect"+                AnalysisKind.Y_INTERCEPT -> "y-int"+            }+            AssistChip(onClick = { viewModel.runAnalysis(kind); onResults() }, label = { Text(short) })+        }+        AssistChip(onClick = { viewModel.clearAnalysis() }, label = { Text("Clear") })+    }+}++@Composable+private fun GraphCanvas(viewModel: CalculatorViewModel, modifier: Modifier) {+    val axisColor = MaterialTheme.colorScheme.onSurface+    val gridColor = MaterialTheme.colorScheme.outlineVariant+    val labelColor = MaterialTheme.colorScheme.onSurfaceVariant+    val surface = MaterialTheme.colorScheme.surface+    val textMeasurer = rememberTextMeasurer()++    // Compile each function once per edit; null means it doesn't parse yet.+    val compiled = viewModel.functions.map { fn ->+        fn to if (fn.enabled && fn.text.isNotBlank()) runCatching { Expression.parse(fn.text) }.getOrNull() else null+    }++    Canvas(+        modifier+            .background(surface)+            .onSizeChanged {+                viewModel.viewWidthPx = it.width.toFloat()+                viewModel.viewHeightPx = it.height.toFloat()+            }+            .pointerInput(Unit) {+                detectTransformGestures { centroid, pan, zoom, _ ->+                    val oldScale = viewModel.scale+                    val newScale = (viewModel.scale * zoom).coerceIn(2.0, 400000.0)+                    val gx = viewModel.centerX + (centroid.x - size.width / 2) / oldScale+                    val gy = viewModel.centerY + (size.height / 2 - centroid.y) / oldScale+                    viewModel.scale = newScale+                    viewModel.centerX = gx - (centroid.x - size.width / 2) / newScale+                    viewModel.centerY = gy - (size.height / 2 - centroid.y) / newScale+                    viewModel.centerX -= pan.x / newScale+                    viewModel.centerY += pan.y / newScale+                }+            },+    ) {+        val w = size.width+        val h = size.height+        val scale = viewModel.scale+        val cx = viewModel.centerX+        val cy = viewModel.centerY+        fun px(gx: Double) = ((gx - cx) * scale + w / 2).toFloat()+        fun py(gy: Double) = (h / 2 - (gy - cy) * scale).toFloat()++        val minX = cx - (w / 2) / scale+        val maxX = cx + (w / 2) / scale+        val minY = cy - (h / 2) / scale+        val maxY = cy + (h / 2) / scale+        val step = niceStep((w / 2) / scale)++        // ---- Grid + tick labels ----+        var gx = ceil(minX / step) * step+        while (gx <= maxX) {+            val x = px(gx)+            drawLine(gridColor, Offset(x, 0f), Offset(x, h), strokeWidth = 1f)+            if (abs(gx) > step / 2) {+                val layout = textMeasurer.measure(formatResult(gx), TextStyle(color = labelColor, fontSize = 10.sp))+                drawText(layout, topLeft = Offset(x + 3f, (py(0.0) + 4f).coerceIn(0f, h - layout.size.height)))+            }+            gx += step+        }+        var gy = ceil(minY / step) * step+        while (gy <= maxY) {+            val y = py(gy)+            drawLine(gridColor, Offset(0f, y), Offset(w, y), strokeWidth = 1f)+            if (abs(gy) > step / 2) {+                val layout = textMeasurer.measure(formatResult(gy), TextStyle(color = labelColor, fontSize = 10.sp))+                drawText(layout, topLeft = Offset((px(0.0) + 3f).coerceIn(0f, w - layout.size.width), y + 3f))+            }+            gy += step+        }++        // ---- Axes ----+        drawLine(axisColor, Offset(px(0.0), 0f), Offset(px(0.0), h), strokeWidth = 2.5f)+        drawLine(axisColor, Offset(0f, py(0.0)), Offset(w, py(0.0)), strokeWidth = 2.5f)++        // ---- Curves ----+        val jumpLimit = h * 4+        for ((fn, expr) in compiled) {+            if (expr == null) continue+            val path = Path()+            var penDown = false+            var prevSy = 0f+            if (fn.polar) {+                // r = f(θ): sample θ over [0, 2π] in radians (polar is inherently radian).+                val samples = 2000+                var k = 0+                while (k <= samples) {+                    val theta = 2 * PI * k / samples+                    val r = runCatching { expr.eval(theta, AngleMode.RADIANS) }.getOrNull()+                    if (r == null || r.isNaN() || r.isInfinite()) { penDown = false } else {+                        val sx = px(r * cos(theta)); val sy = py(r * sin(theta))+                        if (!penDown) { path.moveTo(sx, sy); penDown = true } else path.lineTo(sx, sy)+                    }+                    k+++                }+            } else {+                // y = f(x): one sample per horizontal pixel; break at undefined points / asymptotes.+                var pxCol = 0+                while (pxCol <= w.toInt()) {+                    val graphX = cx + (pxCol - w / 2) / scale+                    val yVal = runCatching { expr.eval(graphX, viewModel.angleMode) }.getOrNull()+                    if (yVal == null || yVal.isNaN() || yVal.isInfinite()) { penDown = false } else {+                        val sy = py(yVal)+                        if (!penDown) { path.moveTo(pxCol.toFloat(), sy); penDown = true }+                        else if (abs(sy - prevSy) > jumpLimit) path.moveTo(pxCol.toFloat(), sy)+                        else path.lineTo(pxCol.toFloat(), sy)+                        prevSy = sy+                    }+                    pxCol+++                }+            }+            drawPath(path, fn.color, style = Stroke(width = 3f))+        }++        // ---- Analysis markers ----+        for (p in viewModel.analysisPoints) {+            val cxp = px(p.x); val cyp = py(p.y)+            if (cxp < -20 || cxp > w + 20 || cyp < -20 || cyp > h + 20) continue+            drawCircle(surface, radius = 7f, center = Offset(cxp, cyp))+            drawCircle(p.color, radius = 7f, center = Offset(cxp, cyp), style = Stroke(width = 3f))+            val layout = textMeasurer.measure(p.label, TextStyle(color = p.color, fontSize = 11.sp))+            drawText(layout, topLeft = Offset((cxp + 8f).coerceAtMost(w - layout.size.width), cyp - layout.size.height - 4f))+        }+    }+}++@Composable+private fun FunctionEditors(viewModel: CalculatorViewModel) {+    LazyColumn(Modifier.fillMaxWidth().heightIn(max = 240.dp).padding(horizontal = 12.dp)) {+        items(viewModel.functions, key = { it.id }) { fn ->+            val error = fn.text.isNotBlank() && runCatching { Expression.parse(fn.text) }.isFailure+            Column(Modifier.fillMaxWidth().padding(vertical = 4.dp)) {+                Row(verticalAlignment = Alignment.CenterVertically) {+                    Box(Modifier.size(16.dp).clip(CircleShape).background(fn.color))+                    OutlinedTextField(+                        value = fn.text,+                        onValueChange = { viewModel.updateFunction(fn.id, it) },+                        modifier = Modifier.weight(1f).padding(horizontal = 8.dp),+                        prefix = { Text(if (fn.polar) "r = " else "y = ") },+                        singleLine = true,+                        isError = error,+                        placeholder = { Text(if (fn.polar) "f(θ)" else "f(x)") },+                    )+                    IconButton({ viewModel.toggleFunction(fn.id) }) {+                        if (fn.enabled) IconVisible() else IconVisibilityOff()+                    }+                    IconButton({ viewModel.removeFunction(fn.id) }) { IconClose() }+                }+                FilterChip(+                    selected = fn.polar,+                    onClick = { viewModel.togglePolar(fn.id) },+                    label = { Text(if (fn.polar) "Polar r(θ)" else "Cartesian y(x)") },+                    modifier = Modifier.padding(start = 24.dp),+                )+            }+        }+        item {+            Row(Modifier.fillMaxWidth().padding(vertical = 6.dp), horizontalArrangement = Arrangement.Center) {+                AssistChip(+                    onClick = { viewModel.addFunction() },+                    label = { Text("Add function") },+                    leadingIcon = { IconAdd() },+                )+            }+        }+    }+}++/** Chooses a "nice" axis step (1, 2 or 5 × 10ⁿ) near [target] units. */+private fun niceStep(target: Double): Double {+    if (target <= 0 || target.isNaN() || target.isInfinite()) return 1.0+    val magnitude = 10.0.pow(floor(log10(target)))+    val normalized = target / magnitude+    val nice = when {+        normalized < 1.5 -> 1.0+        normalized < 3.5 -> 2.0+        normalized < 7.5 -> 5.0+        else -> 10.0+    }+    return nice * magnitude+}
calculator/src/main/java/com/vayunmathur/calculator/util/CalculatorViewModel.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/util/CalculatorViewModel.kt b/calculator/src/main/java/com/vayunmathur/calculator/util/CalculatorViewModel.ktnew file mode 100644index 0000000000..46104bdc3b--- /dev/null+++ b/calculator/src/main/java/com/vayunmathur/calculator/util/CalculatorViewModel.kt@@ -0,0 +1,220 @@+package com.vayunmathur.calculator.util++import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateListOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.compose.ui.graphics.Color+import androidx.lifecycle.ViewModel++/** One plotted curve on the graph screen — Cartesian `y = f(x)` or polar `r = f(θ)`. */+data class GraphFunction(+    val id: Long,+    val text: String = "",+    val color: Color,+    val enabled: Boolean = true,+    val polar: Boolean = false,+)++/** A point found by graph analysis (root, extremum, intersection…), drawn + listed. */+data class AnalysisPoint(+    val x: Double,+    val y: Double,+    val label: String,+    val color: Color,+)++/** The kinds of numeric analysis the graph screen can run over the visible window. */+enum class AnalysisKind(val title: String) {+    ROOTS("Roots (x-intercepts)"),+    MINIMA("Minima"),+    MAXIMA("Maxima"),+    INTERSECTIONS("Intersections"),+    Y_INTERCEPT("y-intercepts"),+}++/**+ * Holds all calculator state at the Activity scope so it survives switching between the+ * Calculator and Graph tabs (which reset the nav back stack).+ */+class CalculatorViewModel : ViewModel() {++    // ---- Shared ----+    var angleMode by mutableStateOf(AngleMode.RADIANS)+        private set++    fun toggleAngleMode() {+        angleMode = if (angleMode == AngleMode.RADIANS) AngleMode.DEGREES else AngleMode.RADIANS+    }++    // ---- Calculator tab ----+    var input by mutableStateOf("")+        private set++    /** Live-evaluated preview of [input]; empty when blank or invalid. */+    var preview by mutableStateOf("")+        private set++    /** The last successfully computed value, exposed to expressions as `ans`. */+    var lastAnswer by mutableStateOf(0.0)+        private set++    /** The single memory register (M+ / M- / MR / MC). */+    var memory by mutableStateOf(0.0)+        private set++    val history = mutableStateListOf<HistoryEntry>()++    data class HistoryEntry(val expression: String, val result: String)++    fun updateInput(value: String) {+        input = value+        preview = computePreview(value)+    }++    fun append(text: String) = updateInput(input + text)++    fun backspace() {+        if (input.isNotEmpty()) updateInput(input.dropLast(1))+    }++    fun clear() = updateInput("")++    /** Evaluate the current input, push it to history, store `ans`, show the result. */+    fun evaluate() {+        if (input.isBlank()) return+        val value = try {+            Expression.parse(input).eval(angle = angleMode, ans = lastAnswer)+        } catch (e: ExpressionError) {+            return // leave input untouched; the preview already flagged the problem+        }+        if (value.isNaN()) return+        val result = formatResult(value)+        history.add(0, HistoryEntry(input, result))+        lastAnswer = value+        updateInput(result)+    }++    fun useHistory(entry: HistoryEntry) = updateInput(entry.result)++    fun clearHistory() = history.clear()++    // Memory register operations. M+/M- fold the current preview (or input) into memory.+    fun memoryClear() { memory = 0.0 }+    fun memoryRecall() = append(formatResult(memory))+    fun memoryAdd() { currentValue()?.let { memory += it } }+    fun memorySubtract() { currentValue()?.let { memory -= it } }++    private fun currentValue(): Double? = try {+        Expression.parse(input.ifBlank { "0" }).eval(angle = angleMode, ans = lastAnswer)+            .takeIf { !it.isNaN() }+    } catch (e: ExpressionError) { null }++    private fun computePreview(value: String): String {+        if (value.isBlank()) return ""+        return try {+            val r = Expression.parse(value).eval(angle = angleMode, ans = lastAnswer)+            if (r.isNaN()) "" else formatResult(r)+        } catch (e: ExpressionError) {+            ""+        }+    }++    // ---- Graph tab ----+    val functions = mutableStateListOf(+        GraphFunction(id = 0, text = "x", color = FunctionColors[0]),+    )+    private var nextId = 1L++    fun addFunction() {+        val color = FunctionColors[functions.size % FunctionColors.size]+        functions.add(GraphFunction(id = nextId++, text = "", color = color))+    }++    fun updateFunction(id: Long, text: String) = mutate(id) { it.copy(text = text) }+    fun toggleFunction(id: Long) = mutate(id) { it.copy(enabled = !it.enabled) }+    fun togglePolar(id: Long) = mutate(id) { it.copy(polar = !it.polar) }++    fun removeFunction(id: Long) {+        functions.removeAll { it.id == id }+        if (functions.isEmpty()) addFunction()+        clearAnalysis()+    }++    private inline fun mutate(id: Long, transform: (GraphFunction) -> GraphFunction) {+        val index = functions.indexOfFirst { it.id == id }+        if (index >= 0) functions[index] = transform(functions[index])+    }++    // ---- Viewport (hoisted here so it survives tab switches and analysis can read it) ----+    var centerX by mutableStateOf(0.0)+    var centerY by mutableStateOf(0.0)+    var scale by mutableStateOf(60.0) // pixels per unit+    var viewWidthPx by mutableStateOf(0f)+    var viewHeightPx by mutableStateOf(0f)++    val analysisPoints = mutableStateListOf<AnalysisPoint>()+    var analysisSummary by mutableStateOf<List<String>>(emptyList())+        private set++    fun clearAnalysis() {+        analysisPoints.clear()+        analysisSummary = emptyList()+    }++    /**+     * Run [kind] over the currently visible x-range for the enabled Cartesian functions+     * (polar curves are skipped — the analyses are Cartesian). Populates [analysisPoints]+     * (drawn on the graph) and [analysisSummary] (shown in a dialog).+     */+    fun runAnalysis(kind: AnalysisKind) {+        analysisPoints.clear()+        if (viewWidthPx <= 0f) { analysisSummary = listOf("Open the graph first."); return }+        val xMin = centerX - (viewWidthPx / 2) / scale+        val xMax = centerX + (viewWidthPx / 2) / scale++        val cartesian = functions.filter { it.enabled && !it.polar && it.text.isNotBlank() }+            .mapNotNull { fn -> runCatching { fn to Expression.parse(fn.text) }.getOrNull() }++        val summary = mutableListOf<String>()+        when (kind) {+            AnalysisKind.INTERSECTIONS -> {+                for (i in cartesian.indices) for (j in i + 1 until cartesian.size) {+                    val (fa, ea) = cartesian[i]+                    val (_, eb) = cartesian[j]+                    for (x in GraphAnalysis.intersections(ea, eb, angleMode, xMin, xMax)) {+                        val y = ea.eval(x, angleMode)+                        analysisPoints.add(AnalysisPoint(x, y, "(${fmt(x)}, ${fmt(y)})", fa.color))+                        summary.add("Intersection: (${fmt(x)}, ${fmt(y)})")+                    }+                }+            }+            else -> for ((fn, expr) in cartesian) {+                val xs = when (kind) {+                    AnalysisKind.ROOTS -> GraphAnalysis.roots(expr, angleMode, xMin, xMax)+                    AnalysisKind.MINIMA -> GraphAnalysis.extrema(expr, angleMode, xMin, xMax, wantMax = false)+                    AnalysisKind.MAXIMA -> GraphAnalysis.extrema(expr, angleMode, xMin, xMax, wantMax = true)+                    AnalysisKind.Y_INTERCEPT -> if (0.0 in xMin..xMax) listOf(0.0) else emptyList()+                    AnalysisKind.INTERSECTIONS -> emptyList()+                }+                for (x in xs) {+                    val y = expr.eval(x, angleMode)+                    if (y.isNaN() || y.isInfinite()) continue+                    analysisPoints.add(AnalysisPoint(x, y, "(${fmt(x)}, ${fmt(y)})", fn.color))+                    summary.add("${kind.title.removeSuffix("s")}: (${fmt(x)}, ${fmt(y)})")+                }+            }+        }+        analysisSummary = if (summary.isEmpty()) listOf("None found in the visible window.") else summary+    }++    private fun fmt(v: Double) = formatResult(v)++    companion object {+        /** Distinct, colour-blind-friendly curve colours, reused cyclically. */+        val FunctionColors = listOf(+            Color(0xFF4285F4), Color(0xFFEA4335), Color(0xFF34A853),+            Color(0xFFFF9800), Color(0xFF9C27B0), Color(0xFF00BCD4),+        )+    }+}
calculator/src/main/java/com/vayunmathur/calculator/util/Expression.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/util/Expression.kt b/calculator/src/main/java/com/vayunmathur/calculator/util/Expression.ktnew file mode 100644index 0000000000..ab2fbdcf9c--- /dev/null+++ b/calculator/src/main/java/com/vayunmathur/calculator/util/Expression.kt@@ -0,0 +1,373 @@+package com.vayunmathur.calculator.util++import kotlin.math.E+import kotlin.math.PI+import kotlin.math.abs+import kotlin.math.acos+import kotlin.math.acosh+import kotlin.math.asin+import kotlin.math.asinh+import kotlin.math.atan+import kotlin.math.atan2+import kotlin.math.atanh+import kotlin.math.cbrt+import kotlin.math.ceil+import kotlin.math.cos+import kotlin.math.cosh+import kotlin.math.exp+import kotlin.math.floor+import kotlin.math.ln+import kotlin.math.log10+import kotlin.math.log2+import kotlin.math.pow+import kotlin.math.round+import kotlin.math.sign+import kotlin.math.sin+import kotlin.math.sinh+import kotlin.math.sqrt+import kotlin.math.tan+import kotlin.math.tanh++/** Whether trigonometric functions interpret/return angles in degrees or radians. */+enum class AngleMode { RADIANS, DEGREES }++/** Thrown when an expression cannot be tokenised or parsed. */+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)++/**+ * A parsed, reusable mathematical expression. Parsing happens once (via [parse]); the+ * tree can be [eval]'d many times with different values of the free variable (`x` for+ * Cartesian graphs, `θ`/`t` for polar), which keeps graphing and analysis cheap.+ *+ * Supported: `+ - * / ^ %`, unary minus, postfix `!` (factorial, via the gamma+ * function), implicit multiplication (`2x`, `3(x+1)`, `2sin(x)`), `|x|` bars,+ * scientific notation (`1.5E3`), the constants `pi`/`π`/`e`/`tau`/`phi`, the free+ * variable (`x`/`t`/`θ`/`theta`), `ans` (previous answer), a large unary-function+ * 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) {++    /** Evaluate for a given free-variable value, [angle] mode and [ans]. */+    fun eval(variable: Double = 0.0, angle: AngleMode = AngleMode.RADIANS, ans: Double = 0.0): Double =+        root.eval(EvalContext(variable, angle, ans))++    companion object {+        fun parse(input: String): Expression = Expression(Parser(input).parse())+    }++    // ---- AST ----++    internal sealed interface Node {+        fun eval(ctx: EvalContext): Double+    }++    private class Num(val value: Double) : Node {+        override fun eval(ctx: EvalContext) = value+    }++    private object Var : Node {+        override fun eval(ctx: EvalContext) = ctx.variable+    }++    private object Ans : Node {+        override fun eval(ctx: EvalContext) = ctx.ans+    }++    private class Neg(val operand: Node) : Node {+        override fun eval(ctx: EvalContext) = -operand.eval(ctx)+    }++    private class Fact(val operand: Node) : Node {+        override fun eval(ctx: EvalContext) = factorial(operand.eval(ctx))+    }++    private class Binary(val op: Char, val left: Node, val right: Node) : Node {+        override fun eval(ctx: EvalContext): Double {+            val a = left.eval(ctx)+            val b = right.eval(ctx)+            return when (op) {+                '+' -> a + b+                '-' -> a - b+                '*' -> a * b+                '/' -> a / b+                '%' -> a % b+                '^' -> a.pow(b)+                else -> throw ExpressionError("Unknown operator '$op'")+            }+        }+    }++    private class Call(val name: String, val args: List<Node>) : Node {+        override fun eval(ctx: EvalContext): Double {+            val a = args.map { it.eval(ctx) }+            fun one(): Double {+                if (a.size != 1) throw ExpressionError("$name expects 1 argument")+                return a[0]+            }+            fun toRad(v: Double) = if (ctx.angle == AngleMode.DEGREES) v * PI / 180.0 else v+            fun fromRad(v: Double) = if (ctx.angle == AngleMode.DEGREES) v * 180.0 / PI else v+            return when (name) {+                "sin" -> sin(toRad(one()))+                "cos" -> cos(toRad(one()))+                "tan" -> tan(toRad(one()))+                "asin" -> fromRad(asin(one()))+                "acos" -> fromRad(acos(one()))+                "atan" -> fromRad(atan(one()))+                "sec" -> 1.0 / cos(toRad(one()))+                "csc" -> 1.0 / sin(toRad(one()))+                "cot" -> 1.0 / tan(toRad(one()))+                "sinh" -> sinh(one())+                "cosh" -> cosh(one())+                "tanh" -> tanh(one())+                "asinh" -> asinh(one())+                "acosh" -> acosh(one())+                "atanh" -> atanh(one())+                "sqrt", "√" -> sqrt(one())+                "cbrt" -> cbrt(one())+                "exp" -> exp(one())+                "ln" -> ln(one())+                "log2" -> log2(one())+                "log" -> if (a.size == 2) ln(a[1]) / ln(a[0]) else log10(one())+                "abs" -> abs(one())+                "floor" -> floor(one())+                "ceil" -> ceil(one())+                "round" -> round(one())+                "sign" -> sign(one())+                "gamma" -> gamma(one())+                "fact" -> factorial(one())+                "root" -> { require2(a); a[1].pow(1.0 / a[0]) }+                "mod" -> { require2(a); a[0] % a[1] }+                "atan2" -> { require2(a); fromRad(atan2(a[0], a[1])) }+                "ncr" -> { require2(a); combinations(a[0], a[1]) }+                "npr" -> { require2(a); permutations(a[0], a[1]) }+                "gcd" -> { require2(a); gcd(a[0], a[1]) }+                "lcm" -> { require2(a); lcm(a[0], a[1]) }+                "max" -> a.max()+                "min" -> a.min()+                else -> throw ExpressionError("Unknown function '$name'")+            }+        }++        private fun require2(a: List<Double>) {+            if (a.size != 2) throw ExpressionError("$name expects 2 arguments")+        }+    }++    /**+     * Recursive-descent parser. Precedence (low → high):+     * expr → term (('+'|'-') term)*+     * term → factor (('*'|'/'|'%'|implicit) factor)*+     * factor → ('+'|'-') factor | power+     * power → postfix ('^' factor)?          (right associative)+     * postfix → primary ('!')*                (factorial)+     * primary → number | const | var | ans | func '(' args ')' | '(' expr ')' | '|' expr '|'+     */+    private class Parser(input: String) {+        private val src = input+        private var pos = 0++        fun parse(): Node {+            val node = parseExpr()+            skipSpaces()+            if (pos < src.length) throw ExpressionError("Unexpected '${src[pos]}'")+            return node+        }++        private fun skipSpaces() {+            while (pos < src.length && src[pos].isWhitespace()) pos+++        }++        private fun peek(): Char? {+            skipSpaces()+            return if (pos < src.length) src[pos] else null+        }++        private fun parseExpr(): Node {+            var left = parseTerm()+            while (true) {+                val c = peek() ?: break+                if (c == '+' || c == '-') {+                    pos+++                    left = Binary(c, left, parseTerm())+                } else break+            }+            return left+        }++        private fun parseTerm(): Node {+            var left = parseFactor()+            while (true) {+                val c = peek() ?: break+                when (c) {+                    '*', '/', '%' -> { pos++; left = Binary(c, left, parseFactor()) }+                    // Implicit multiplication: value directly followed by a group/name.+                    '(', '|' -> left = Binary('*', left, parseFactor())+                    else -> if (c.isLetter() || c == '√' || c == 'π' || c == 'θ') {+                        left = Binary('*', left, parseFactor())+                    } else break+                }+            }+            return left+        }++        private fun parseFactor(): Node {+            val c = peek()+            if (c == '+') { pos++; return parseFactor() }+            if (c == '-') { pos++; return Neg(parseFactor()) }+            return parsePower()+        }++        private fun parsePower(): Node {+            val base = parsePostfix()+            if (peek() == '^') {+                pos+++                return Binary('^', base, parseFactor()) // right associative; -x^2 = -(x^2)+            }+            return base+        }++        private fun parsePostfix(): Node {+            var node = parsePrimary()+            while (peek() == '!') { pos++; node = Fact(node) }+            return node+        }++        private fun parsePrimary(): Node {+            val c = peek() ?: throw ExpressionError("Unexpected end of expression")+            when {+                c == '(' -> {+                    pos+++                    val inner = parseExpr()+                    if (peek() != ')') throw ExpressionError("Missing ')'")+                    pos+++                    return inner+                }+                c == '|' -> {+                    pos+++                    val inner = parseExpr()+                    if (peek() != '|') throw ExpressionError("Missing '|'")+                    pos+++                    return Call("abs", listOf(inner))+                }+                c.isDigit() || c == '.' -> return parseNumber()+                c.isLetter() || c == '√' || c == 'π' || c == 'θ' -> return parseIdentifier()+                else -> throw ExpressionError("Unexpected '$c'")+            }+        }++        private fun parseNumber(): Node {+            skipSpaces()+            val start = pos+            var seenDot = false+            while (pos < src.length) {+                val ch = src[pos]+                if (ch.isDigit()) pos+++                else if (ch == '.' && !seenDot) { seenDot = true; pos++ }+                else break+            }+            // Scientific notation: uppercase 'E' only (lowercase 'e' is Euler's constant).+            if (pos < src.length && src[pos] == 'E') {+                val save = pos+                pos+++                if (pos < src.length && (src[pos] == '+' || src[pos] == '-')) pos+++                if (pos < src.length && src[pos].isDigit()) {+                    while (pos < src.length && src[pos].isDigit()) pos+++                } else {+                    pos = save // not an exponent after all+                }+            }+            val text = src.substring(start, pos)+            val value = text.toDoubleOrNull() ?: throw ExpressionError("Invalid number '$text'")+            return Num(value)+        }++        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 }+            val start = pos+            while (pos < src.length && (src[pos].isLetterOrDigit() || src[pos] == '_')) pos+++            val name = src.substring(start, pos).lowercase()+            return when (name) {+                "x", "t", "theta" -> Var+                "ans" -> Ans+                "pi" -> Num(PI)+                "tau" -> Num(2 * PI)+                "e" -> Num(E)+                "phi" -> Num((1 + sqrt(5.0)) / 2)+                else -> {+                    if (peek() == '(') {+                        pos+++                        val args = parseArgs()+                        if (peek() != ')') throw ExpressionError("Missing ')' after $name")+                        pos+++                        Call(name, args)+                    } else {+                        throw ExpressionError("Unknown symbol '$name'")+                    }+                }+            }+        }++        private fun parseArgs(): List<Node> {+            val args = mutableListOf<Node>()+            if (peek() == ')') return args+            args.add(parseExpr())+            while (peek() == ',') { pos++; args.add(parseExpr()) }+            return args+        }+    }+}++// ---- Special functions shared by the AST ----++/** Lanczos approximation of the gamma function (valid across the reals except poles). */+private fun gamma(x: Double): Double {+    val g = 7.0+    val c = doubleArrayOf(+        0.99999999999980993, 676.5203681218851, -1259.1392167224028,+        771.32342877765313, -176.61502916214059, 12.507343278686905,+        -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7,+    )+    if (x < 0.5) return PI / (sin(PI * x) * gamma(1 - x))+    val z = x - 1+    var a = c[0]+    val t = z + g + 0.5+    for (i in 1 until c.size) a += c[i] / (z + i)+    return sqrt(2 * PI) * t.pow(z + 0.5) * exp(-t) * a+}++/** Factorial via gamma so non-integers work too; exact for small non-negative integers. */+private fun factorial(n: Double): Double {+    if (n < 0 && n == floor(n)) return Double.NaN // poles at negative integers+    if (n == floor(n) && n <= 170) {+        var result = 1.0+        var i = 2+        while (i <= n.toInt()) { result *= i; i++ }+        return result+    }+    return gamma(n + 1)+}++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 }+    return x.toDouble()+}++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/util/Formatting.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/util/Formatting.kt b/calculator/src/main/java/com/vayunmathur/calculator/util/Formatting.ktnew file mode 100644index 0000000000..dff62731b0--- /dev/null+++ b/calculator/src/main/java/com/vayunmathur/calculator/util/Formatting.kt@@ -0,0 +1,28 @@+package com.vayunmathur.calculator.util++import java.math.BigDecimal+import java.math.MathContext+import kotlin.math.abs++/**+ * Formats a computed [Double] for display: trims floating-point noise, uses plain+ * decimal notation for "normal" magnitudes and scientific notation for very large or+ * very small values, and reports non-finite results as human-readable errors.+ */+fun formatResult(value: Double): String {+    if (value.isNaN()) return "Undefined"+    if (value.isInfinite()) return if (value > 0) "∞" else "-∞"+    if (value == 0.0) return "0"++    val magnitude = abs(value)+    // Round to 12 significant digits to hide binary-floating-point artefacts+    // (e.g. 0.1 + 0.2 → 0.30000000000000004).+    val rounded = BigDecimal(value).round(MathContext(12)).stripTrailingZeros()++    return if (magnitude >= 1e12 || magnitude < 1e-6) {+        // Scientific notation, e.g. 1.23e+15.+        rounded.toString().replace("E", "e")+    } else {+        rounded.toPlainString()+    }+}
calculator/src/main/java/com/vayunmathur/calculator/util/GraphAnalysis.kt
diff --git a/calculator/src/main/java/com/vayunmathur/calculator/util/GraphAnalysis.kt b/calculator/src/main/java/com/vayunmathur/calculator/util/GraphAnalysis.ktnew file mode 100644index 0000000000..7599c99d36--- /dev/null+++ b/calculator/src/main/java/com/vayunmathur/calculator/util/GraphAnalysis.kt@@ -0,0 +1,132 @@+package com.vayunmathur.calculator.util++import kotlin.math.abs++/**+ * Numeric analysis of graphed functions over the visible x-window: roots (x-intercepts),+ * local minima/maxima, and intersections between two curves. All methods sample the range+ * densely, bracket features by sign/slope changes, then refine — good enough for an+ * on-device grapher without a symbolic engine.+ */+object GraphAnalysis {++    private const val SAMPLES = 1000+    private const val REFINE_ITERS = 60++    private fun evalOrNaN(e: Expression, x: Double, angle: AngleMode): Double =+        try { e.eval(x, angle) } catch (ex: ExpressionError) { Double.NaN }++    /** x-values where `f(x) = 0` in `[xMin, xMax]`, via sign-change bracketing + bisection. */+    fun roots(e: Expression, angle: AngleMode, xMin: Double, xMax: Double): List<Double> {+        val out = ArrayList<Double>()+        val step = (xMax - xMin) / SAMPLES+        var prevX = xMin+        var prevY = evalOrNaN(e, prevX, angle)+        var i = 1+        while (i <= SAMPLES) {+            val x = xMin + i * step+            val y = evalOrNaN(e, x, angle)+            if (prevY.isFinite() && y.isFinite()) {+                if (prevY == 0.0) addUnique(out, prevX)+                // A sign change that isn't a discontinuity jump brackets a root.+                else if (prevY * y < 0 && abs(y - prevY) < 1e6) {+                    addUnique(out, bisect(e, angle, prevX, x))+                }+            }+            prevX = x; prevY = y; i+++        }+        return out+    }++    /** Local minima (or maxima if [wantMax]) in `[xMin, xMax]`, via slope-sign changes. */+    fun extrema(e: Expression, angle: AngleMode, xMin: Double, xMax: Double, wantMax: Boolean): List<Double> {+        val out = ArrayList<Double>()+        val step = (xMax - xMin) / SAMPLES+        var a = xMin+        var fa = evalOrNaN(e, a, angle)+        var b = xMin + step+        var fb = evalOrNaN(e, b, angle)+        var i = 2+        while (i <= SAMPLES) {+            val c = xMin + i * step+            val fc = evalOrNaN(e, c, angle)+            if (fa.isFinite() && fb.isFinite() && fc.isFinite()) {+                val isMax = fb > fa && fb > fc+                val isMin = fb < fa && fb < fc+                if ((wantMax && isMax) || (!wantMax && isMin)) {+                    addUnique(out, ternary(e, angle, a, c, wantMax))+                }+            }+            a = b; fa = fb; b = c; fb = fc; i+++        }+        return out+    }++    /** x-values where `f(x) = g(x)` — the roots of `f - g`. */+    fun intersections(f: Expression, g: Expression, angle: AngleMode, xMin: Double, xMax: Double): List<Double> {+        val out = ArrayList<Double>()+        val step = (xMax - xMin) / SAMPLES+        fun diff(x: Double): Double {+            val a = evalOrNaN(f, x, angle); val b = evalOrNaN(g, x, angle)+            return a - b+        }+        var prevX = xMin+        var prevY = diff(prevX)+        var i = 1+        while (i <= SAMPLES) {+            val x = xMin + i * step+            val y = diff(x)+            if (prevY.isFinite() && y.isFinite() && prevY * y < 0 && abs(y - prevY) < 1e6) {+                out.add(bisectDiff(f, g, angle, prevX, x))+            }+            prevX = x; prevY = y; i+++        }+        return out+    }++    // --- refinement ---++    private fun bisect(e: Expression, angle: AngleMode, lo0: Double, hi0: Double): Double {+        var lo = lo0; var hi = hi0+        var flo = evalOrNaN(e, lo, angle)+        repeat(REFINE_ITERS) {+            val mid = (lo + hi) / 2+            val fmid = evalOrNaN(e, mid, angle)+            if (fmid == 0.0 || !fmid.isFinite()) return mid+            if (flo * fmid < 0) hi = mid else { lo = mid; flo = fmid }+        }+        return (lo + hi) / 2+    }++    private fun bisectDiff(f: Expression, g: Expression, angle: AngleMode, lo0: Double, hi0: Double): Double {+        var lo = lo0; var hi = hi0+        fun d(x: Double) = evalOrNaN(f, x, angle) - evalOrNaN(g, x, angle)+        var flo = d(lo)+        repeat(REFINE_ITERS) {+            val mid = (lo + hi) / 2+            val fmid = d(mid)+            if (fmid == 0.0 || !fmid.isFinite()) return mid+            if (flo * fmid < 0) hi = mid else { lo = mid; flo = fmid }+        }+        return (lo + hi) / 2+    }++    /** Ternary search for the extremum of a unimodal bracket `[lo, hi]`. */+    private fun ternary(e: Expression, angle: AngleMode, lo0: Double, hi0: Double, wantMax: Boolean): Double {+        var lo = lo0; var hi = hi0+        repeat(REFINE_ITERS) {+            val m1 = lo + (hi - lo) / 3+            val m2 = hi - (hi - lo) / 3+            val f1 = evalOrNaN(e, m1, angle)+            val f2 = evalOrNaN(e, m2, angle)+            val keepLeft = if (wantMax) f1 > f2 else f1 < f2+            if (keepLeft) hi = m2 else lo = m1+        }+        return (lo + hi) / 2+    }++    /** Add [x] unless a near-duplicate is already present (features found twice by sampling). */+    private fun addUnique(list: MutableList<Double>, x: Double) {+        if (list.none { abs(it - x) < 1e-4 * (1 + abs(x)) }) list.add(x)+    }+}
calculator/src/main/res/values/strings.xml
diff --git a/calculator/src/main/res/values/strings.xml b/calculator/src/main/res/values/strings.xmlnew file mode 100644index 0000000000..91b584c887--- /dev/null+++ b/calculator/src/main/res/values/strings.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+    <string name="app_name">Calculator</string>+</resources>