measure: migrate to canonical structure
- Commit
28e84088648a6dd946d42635c7e0f9bf6ebb3cc1- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-15 19:47 UTC (3 months ago)
- Parents
0373333
Diff
measure/src/main/java/com/vayunmathur/measure/ui/ArMeasureContent.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/ui/ArMeasureContent.kt b/measure/src/main/java/com/vayunmathur/measure/ui/ArMeasureContent.ktnew file mode 100644index 0000000000..f4295713ae--- /dev/null+++ b/measure/src/main/java/com/vayunmathur/measure/ui/ArMeasureContent.kt@@ -0,0 +1,241 @@+package com.vayunmathur.measure.ui++import androidx.compose.foundation.Canvas+import androidx.compose.foundation.background+import androidx.compose.foundation.gestures.detectTapGestures+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.padding+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+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.geometry.Size+import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.layout.onSizeChanged+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconSettings+import com.vayunmathur.library.ui.IconUndo+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.Text+import com.vayunmathur.measure.data.model.TrackingQuality+import com.vayunmathur.measure.domain.MeasureNative+import com.vayunmathur.measure.domain.Units+import com.vayunmathur.measure.platform.ArMeasureActions+import com.vayunmathur.measure.platform.ArMeasureUiState++@Composable+fun ArMeasureContent(+ state: ArMeasureUiState,+ actions: ArMeasureActions,+ screenPoints: List<Offset> = emptyList(),+ onCanvasSized: (Size) -> Unit = {},+ onTap: (Float, Float) -> Unit = { _, _ -> },+ cameraContent: @Composable () -> Unit = {},+ onOpenSettings: () -> Unit = {},+ bottomBar: @Composable () -> Unit = {},+) {+ AppScaffold(+ title = "Measure",+ actions = { IconButton(onClick = onOpenSettings) { IconSettings() } },+ bottomBar = bottomBar,+ ) { padding ->+ Box(Modifier.fillMaxSize().padding(padding)) {++ if (!MeasureNative.available) {+ UnavailableNotice(+ "AR measuring needs the native tracking engine, which isn't available " ++ "on this device."+ )+ return@Box+ }+ if (!state.cameraPermissionGranted) {+ UnavailableNotice("Camera access is needed to measure in AR.")+ return@Box+ }++ cameraContent()++ ArOverlay(+ state = state,+ screenPoints = screenPoints,+ onCanvasSized = onCanvasSized,+ onTap = onTap,+ modifier = Modifier.fillMaxSize(),+ )++ Column(+ modifier = Modifier.align(Alignment.TopCenter).padding(12.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.spacedBy(6.dp),+ ) {+ TrackingBanner(state.quality, state.hasPlane)+ }++ Column(+ modifier = Modifier.align(Alignment.BottomCenter).padding(16.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ ReadoutCard(state)+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ OutlinedButton(+ onClick = { actions.undoAnchor() },+ enabled = state.anchors.isNotEmpty(),+ ) { IconUndo() }+ OutlinedButton(+ onClick = { actions.closePolygon() },+ enabled = state.anchors.size >= 3 && !state.polygonClosed,+ ) { Text("Close shape") }+ OutlinedButton(+ onClick = { actions.clearAnchors() },+ enabled = state.anchors.isNotEmpty(),+ ) { Text("Clear") }+ }+ }+ }+ }+}++/**+ * Coaching banner.+ *+ * While initialising this is not decoration — monocular visual-inertial tracking cannot+ * recover metric scale from rotation alone, so the user genuinely has to translate the+ * device before any distance exists. Saying so plainly is more useful than a spinner.+ */+@Composable+private fun TrackingBanner(quality: TrackingQuality, hasPlane: Boolean) {+ val (message, color) = when (quality) {+ TrackingQuality.Initialising ->+ "Move the phone sideways and turn it slightly to start tracking" to+ MaterialTheme.colorScheme.tertiaryContainer++ TrackingQuality.Limited ->+ "Tracking is weak — move slowly and keep texture in view" to+ MaterialTheme.colorScheme.tertiaryContainer++ TrackingQuality.Lost ->+ "Tracking lost — point at a textured surface to recover" to+ MaterialTheme.colorScheme.errorContainer++ TrackingQuality.Good ->+ (if (hasPlane) "Ready — tap to place points" else "Ready — no surface found yet") to+ MaterialTheme.colorScheme.primaryContainer+ }+ Box(+ Modifier+ .clip(RoundedCornerShape(12.dp))+ .background(color)+ .padding(horizontal = 14.dp, vertical = 8.dp)+ ) {+ Text(message, style = MaterialTheme.typography.bodyMedium)+ }+}++@Composable+private fun ReadoutCard(state: ArMeasureUiState) {+ if (state.distanceM == null && state.areaM2 == null) return+ Box(+ Modifier+ .clip(RoundedCornerShape(12.dp))+ .background(MaterialTheme.colorScheme.surface.copy(alpha = 0.85f))+ .padding(horizontal = 16.dp, vertical = 10.dp)+ ) {+ Column(horizontalAlignment = Alignment.CenterHorizontally) {+ state.distanceM?.let {+ Text(+ Units.formatLength(it, state.unitSystem),+ style = MaterialTheme.typography.headlineSmall,+ )+ }+ state.areaM2?.let {+ Text(+ "Area ${Units.formatArea(it, state.unitSystem)}",+ style = MaterialTheme.typography.bodyMedium,+ )+ }+ state.perimeterM?.let {+ Text(+ "Perimeter ${Units.formatLength(it, state.unitSystem)}",+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ }+ }+}++/**+ * Anchor and edge overlay.+ *+ * Anchors are drawn from screen positions the engine projected from their world+ * coordinates, so this layer holds no projection maths and stays previewable.+ */+@Composable+private fun ArOverlay(+ state: ArMeasureUiState,+ screenPoints: List<Offset>,+ onCanvasSized: (Size) -> Unit,+ onTap: (Float, Float) -> Unit,+ modifier: Modifier = Modifier,+) {+ val primary = MaterialTheme.colorScheme.primary+ val onPrimary = MaterialTheme.colorScheme.onPrimary+ val measurable = state.quality == TrackingQuality.Good ||+ state.quality == TrackingQuality.Limited++ Canvas(+ modifier+ .onSizeChanged { onCanvasSized(Size(it.width.toFloat(), it.height.toFloat())) }+ .pointerInput(measurable) {+ if (!measurable) return@pointerInput+ detectTapGestures { pos ->+ onTap(pos.x / size.width, pos.y / size.height)+ }+ }+ ) {+ // Reticle at the centre, showing where a tap would land.+ if (measurable) {+ val c = Offset(size.width / 2f, size.height / 2f)+ drawCircle(primary.copy(alpha = 0.9f), 6f, c)+ drawCircle(primary.copy(alpha = 0.4f), 22f, c, style = Stroke(2f))+ }++ for (i in 0 until screenPoints.size - 1) {+ drawLine(primary, screenPoints[i], screenPoints[i + 1], 4f)+ }+ if (state.polygonClosed && screenPoints.size >= 3) {+ drawLine(primary, screenPoints.last(), screenPoints.first(), 4f)+ }+ for (p in screenPoints) {+ drawCircle(primary, 12f, p)+ drawCircle(onPrimary, 5f, p)+ }+ }+}++@Composable+private fun UnavailableNotice(message: String) {+ Column(+ modifier = Modifier.fillMaxSize().padding(32.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.Center,+ ) {+ Text("AR measure unavailable", style = MaterialTheme.typography.titleMedium)+ Text(+ message,+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+}
measure/src/main/java/com/vayunmathur/measure/ui/ArMeasurePage.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/ui/ArMeasurePage.kt b/measure/src/main/java/com/vayunmathur/measure/ui/ArMeasurePage.ktindex d25fa28d79..1e11718314 100644--- a/measure/src/main/java/com/vayunmathur/measure/ui/ArMeasurePage.kt+++ b/measure/src/main/java/com/vayunmathur/measure/ui/ArMeasurePage.kt@@ -4,16 +4,6 @@ import android.Manifest import android.content.pm.PackageManager import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts-import androidx.compose.foundation.Canvas-import androidx.compose.foundation.background-import androidx.compose.foundation.gestures.detectTapGestures-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.padding-import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState@@ -22,31 +12,16 @@ import androidx.compose.runtime.mutableLongStateOf 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.geometry.Size-import androidx.compose.ui.graphics.drawscope.Stroke-import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.platform.LocalContext-import androidx.compose.ui.unit.dp import androidx.core.content.ContextCompat-import com.vayunmathur.library.ui.AppScaffold-import com.vayunmathur.library.ui.IconButton-import com.vayunmathur.library.ui.IconSettings-import com.vayunmathur.library.ui.IconUndo-import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.OutlinedButton-import com.vayunmathur.library.ui.Text+import androidx.compose.foundation.layout.fillMaxSize import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.measure.Route-import com.vayunmathur.measure.data.model.TrackingQuality import com.vayunmathur.measure.domain.MeasureNative-import com.vayunmathur.measure.domain.Units-import com.vayunmathur.measure.platform.ArMeasureActions-import com.vayunmathur.measure.platform.ArMeasureUiState import com.vayunmathur.measure.platform.MeasureViewModel import com.vayunmathur.measure.platform.trackingQualityFrom import com.vayunmathur.measure.ui.components.MeasureBottomBar@@ -161,211 +136,3 @@ private fun rememberCameraPermission(onResult: (Boolean) -> Unit): Boolean { } private const val PROJECTION_INTERVAL_MS = 33L--@Composable-fun ArMeasureContent(- state: ArMeasureUiState,- actions: ArMeasureActions,- screenPoints: List<Offset> = emptyList(),- onCanvasSized: (Size) -> Unit = {},- onTap: (Float, Float) -> Unit = { _, _ -> },- cameraContent: @Composable () -> Unit = {},- onOpenSettings: () -> Unit = {},- bottomBar: @Composable () -> Unit = {},-) {- AppScaffold(- title = "Measure",- actions = { IconButton(onClick = onOpenSettings) { IconSettings() } },- bottomBar = bottomBar,- ) { padding ->- Box(Modifier.fillMaxSize().padding(padding)) {-- if (!MeasureNative.available) {- UnavailableNotice(- "AR measuring needs the native tracking engine, which isn't available " +- "on this device."- )- return@Box- }- if (!state.cameraPermissionGranted) {- UnavailableNotice("Camera access is needed to measure in AR.")- return@Box- }-- cameraContent()-- ArOverlay(- state = state,- screenPoints = screenPoints,- onCanvasSized = onCanvasSized,- onTap = onTap,- modifier = Modifier.fillMaxSize(),- )-- Column(- modifier = Modifier.align(Alignment.TopCenter).padding(12.dp),- horizontalAlignment = Alignment.CenterHorizontally,- verticalArrangement = Arrangement.spacedBy(6.dp),- ) {- TrackingBanner(state.quality, state.hasPlane)- }-- Column(- modifier = Modifier.align(Alignment.BottomCenter).padding(16.dp),- horizontalAlignment = Alignment.CenterHorizontally,- verticalArrangement = Arrangement.spacedBy(8.dp),- ) {- ReadoutCard(state)- Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {- OutlinedButton(- onClick = { actions.undoAnchor() },- enabled = state.anchors.isNotEmpty(),- ) { IconUndo() }- OutlinedButton(- onClick = { actions.closePolygon() },- enabled = state.anchors.size >= 3 && !state.polygonClosed,- ) { Text("Close shape") }- OutlinedButton(- onClick = { actions.clearAnchors() },- enabled = state.anchors.isNotEmpty(),- ) { Text("Clear") }- }- }- }- }-}--/**- * Coaching banner.- *- * While initialising this is not decoration — monocular visual-inertial tracking cannot- * recover metric scale from rotation alone, so the user genuinely has to translate the- * device before any distance exists. Saying so plainly is more useful than a spinner.- */-@Composable-private fun TrackingBanner(quality: TrackingQuality, hasPlane: Boolean) {- val (message, color) = when (quality) {- TrackingQuality.Initialising ->- "Move the phone sideways and turn it slightly to start tracking" to- MaterialTheme.colorScheme.tertiaryContainer-- TrackingQuality.Limited ->- "Tracking is weak — move slowly and keep texture in view" to- MaterialTheme.colorScheme.tertiaryContainer-- TrackingQuality.Lost ->- "Tracking lost — point at a textured surface to recover" to- MaterialTheme.colorScheme.errorContainer-- TrackingQuality.Good ->- (if (hasPlane) "Ready — tap to place points" else "Ready — no surface found yet") to- MaterialTheme.colorScheme.primaryContainer- }- Box(- Modifier- .clip(RoundedCornerShape(12.dp))- .background(color)- .padding(horizontal = 14.dp, vertical = 8.dp)- ) {- Text(message, style = MaterialTheme.typography.bodyMedium)- }-}--@Composable-private fun ReadoutCard(state: ArMeasureUiState) {- if (state.distanceM == null && state.areaM2 == null) return- Box(- Modifier- .clip(RoundedCornerShape(12.dp))- .background(MaterialTheme.colorScheme.surface.copy(alpha = 0.85f))- .padding(horizontal = 16.dp, vertical = 10.dp)- ) {- Column(horizontalAlignment = Alignment.CenterHorizontally) {- state.distanceM?.let {- Text(- Units.formatLength(it, state.unitSystem),- style = MaterialTheme.typography.headlineSmall,- )- }- state.areaM2?.let {- Text(- "Area ${Units.formatArea(it, state.unitSystem)}",- style = MaterialTheme.typography.bodyMedium,- )- }- state.perimeterM?.let {- Text(- "Perimeter ${Units.formatLength(it, state.unitSystem)}",- style = MaterialTheme.typography.bodyMedium,- color = MaterialTheme.colorScheme.onSurfaceVariant,- )- }- }- }-}--/**- * Anchor and edge overlay.- *- * Anchors are drawn from screen positions the engine projected from their world- * coordinates, so this layer holds no projection maths and stays previewable.- */-@Composable-private fun ArOverlay(- state: ArMeasureUiState,- screenPoints: List<Offset>,- onCanvasSized: (Size) -> Unit,- onTap: (Float, Float) -> Unit,- modifier: Modifier = Modifier,-) {- val primary = MaterialTheme.colorScheme.primary- val onPrimary = MaterialTheme.colorScheme.onPrimary- val measurable = state.quality == TrackingQuality.Good ||- state.quality == TrackingQuality.Limited-- Canvas(- modifier- .onSizeChanged { onCanvasSized(Size(it.width.toFloat(), it.height.toFloat())) }- .pointerInput(measurable) {- if (!measurable) return@pointerInput- detectTapGestures { pos ->- onTap(pos.x / size.width, pos.y / size.height)- }- }- ) {- // Reticle at the centre, showing where a tap would land.- if (measurable) {- val c = Offset(size.width / 2f, size.height / 2f)- drawCircle(primary.copy(alpha = 0.9f), 6f, c)- drawCircle(primary.copy(alpha = 0.4f), 22f, c, style = Stroke(2f))- }-- for (i in 0 until screenPoints.size - 1) {- drawLine(primary, screenPoints[i], screenPoints[i + 1], 4f)- }- if (state.polygonClosed && screenPoints.size >= 3) {- drawLine(primary, screenPoints.last(), screenPoints.first(), 4f)- }- for (p in screenPoints) {- drawCircle(primary, 12f, p)- drawCircle(onPrimary, 5f, p)- }- }-}--@Composable-private fun UnavailableNotice(message: String) {- Column(- modifier = Modifier.fillMaxSize().padding(32.dp),- horizontalAlignment = Alignment.CenterHorizontally,- verticalArrangement = Arrangement.Center,- ) {- Text("AR measure unavailable", style = MaterialTheme.typography.titleMedium)- Text(- message,- style = MaterialTheme.typography.bodyMedium,- color = MaterialTheme.colorScheme.onSurfaceVariant,- )- }-}-
measure/src/main/java/com/vayunmathur/measure/ui/CompassContent.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/ui/CompassContent.kt b/measure/src/main/java/com/vayunmathur/measure/ui/CompassContent.ktnew file mode 100644index 0000000000..e466c2c1c5--- /dev/null+++ b/measure/src/main/java/com/vayunmathur/measure/ui/CompassContent.kt@@ -0,0 +1,240 @@+package com.vayunmathur.measure.ui++import androidx.compose.foundation.Canvas+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.aspectRatio+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.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.Path+import androidx.compose.ui.graphics.drawscope.DrawScope+import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.graphics.drawscope.rotate+import androidx.compose.ui.text.TextMeasurer+import androidx.compose.ui.text.TextStyle+import androidx.compose.ui.text.rememberTextMeasurer+import androidx.compose.ui.text.drawText+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconSettings+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.Text+import com.vayunmathur.measure.domain.Units+import com.vayunmathur.measure.platform.CompassActions+import com.vayunmathur.measure.platform.CompassUiState+import kotlin.math.cos+import kotlin.math.sin++@Composable+fun CompassContent(+ state: CompassUiState,+ actions: CompassActions,+ onOpenSettings: () -> Unit = {},+ bottomBar: @Composable () -> Unit = {},+) {+ val heading = if (state.useTrueNorth && state.hasLocation) {+ state.azimuthTrueDeg+ } else {+ state.azimuthMagDeg+ }+ AppScaffold(+ title = "Compass",+ actions = { IconButton(onClick = onOpenSettings) { IconSettings() } },+ bottomBar = bottomBar,+ ) { padding ->+ Column(+ modifier = Modifier.fillMaxSize().padding(padding).padding(16.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.spacedBy(12.dp),+ ) {+ Text(+ "${Units.formatBearing(heading)} ${Units.cardinal(heading)}",+ style = MaterialTheme.typography.displaySmall,+ )+ Text(+ // Without a location fix declination is unknown, so "true north" would+ // be a claim the app cannot back up.+ if (state.useTrueNorth && state.hasLocation) "True north" else "Magnetic north",+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )++ CompassDial(+ headingDeg = heading,+ heldBearingDeg = state.heldBearingDeg,+ // Height-driven so the dial shrinks to fit a landscape window rather+ // than pushing the controls off the bottom.+ modifier = Modifier+ .weight(1f)+ .aspectRatio(1f, matchHeightConstraintsFirst = true)+ .padding(8.dp),+ )++ if (state.accuracy < ACCURACY_HIGH) {+ Text(+ "Compass needs calibration — move the phone in a figure-8",+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.error,+ )+ }+ if (state.tiltWarning) {+ Text(+ "Hold the phone flat for an accurate bearing",+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.error,+ )+ }+ if (state.hasLocation) {+ Text(+ "Declination ${Units.formatAngle(state.declinationDeg)}",+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ } else {+ Text(+ "No location — showing magnetic north only",+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }++ Spacer(Modifier.height(4.dp))+ Column(+ verticalArrangement = Arrangement.spacedBy(8.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ ) {+ OutlinedButton(+ onClick = { actions.setUseTrueNorth(!state.useTrueNorth) },+ enabled = state.hasLocation,+ ) {+ Text(if (state.useTrueNorth) "Show magnetic" else "Show true north")+ }+ OutlinedButton(+ onClick = {+ if (state.heldBearingDeg == null) actions.holdBearing()+ else actions.clearHeldBearing()+ }+ ) {+ Text(if (state.heldBearingDeg == null) "Hold bearing" else "Release bearing")+ }+ }+ }+ }+}++/**+ * Compass rose. The dial rotates opposite the heading so north stays physically north+ * while the fixed top index reads the current bearing.+ */+@Composable+private fun CompassDial(+ headingDeg: Double,+ heldBearingDeg: Double?,+ modifier: Modifier = Modifier,+) {+ val measurer = rememberTextMeasurer()+ val onSurface = MaterialTheme.colorScheme.onSurface+ val variant = MaterialTheme.colorScheme.onSurfaceVariant+ val primary = MaterialTheme.colorScheme.primary+ val error = MaterialTheme.colorScheme.error++ Box(modifier) {+ Canvas(Modifier.fillMaxSize()) {+ val radius = size.minDimension / 2f+ val center = Offset(size.width / 2f, size.height / 2f)++ drawCircle(variant.copy(alpha = 0.3f), radius, center, style = Stroke(2f))++ rotate(-headingDeg.toFloat(), center) {+ drawTicks(center, radius, onSurface, variant)+ drawCardinals(measurer, center, radius, onSurface, error)+ if (heldBearingDeg != null) {+ drawHeldBearing(center, radius, heldBearingDeg.toFloat(), primary)+ }+ }++ // Fixed index at the top: the bearing is whatever sits under it.+ val p = Path().apply {+ moveTo(center.x, center.y - radius - 2f)+ lineTo(center.x - 14f, center.y - radius + 22f)+ lineTo(center.x + 14f, center.y - radius + 22f)+ close()+ }+ drawPath(p, primary)+ }+ }+}++private fun DrawScope.drawTicks(center: Offset, radius: Float, major: Color, minor: Color) {+ for (deg in 0 until 360 step 5) {+ val isMajor = deg % 30 == 0+ val len = if (isMajor) radius * 0.10f else radius * 0.05f+ val rad = Math.toRadians(deg.toDouble() - 90.0)+ val cosA = cos(rad).toFloat()+ val sinA = sin(rad).toFloat()+ drawLine(+ color = if (isMajor) major else minor.copy(alpha = 0.5f),+ start = Offset(center.x + cosA * (radius - len), center.y + sinA * (radius - len)),+ end = Offset(center.x + cosA * radius, center.y + sinA * radius),+ strokeWidth = if (isMajor) 3f else 1.5f,+ )+ }+}++private fun DrawScope.drawCardinals(+ measurer: TextMeasurer,+ center: Offset,+ radius: Float,+ normal: Color,+ northColor: Color,+) {+ val labels = listOf(0 to "N", 90 to "E", 180 to "S", 270 to "W")+ for ((deg, label) in labels) {+ val rad = Math.toRadians(deg.toDouble() - 90.0)+ val r = radius * 0.78f+ val style = TextStyle(+ fontSize = 20.sp,+ color = if (label == "N") northColor else normal,+ )+ val layout = measurer.measure(label, style)+ drawText(+ layout,+ topLeft = Offset(+ center.x + cos(rad).toFloat() * r - layout.size.width / 2f,+ center.y + sin(rad).toFloat() * r - layout.size.height / 2f,+ ),+ )+ }+}++private fun DrawScope.drawHeldBearing(+ center: Offset,+ radius: Float,+ bearingDeg: Float,+ color: Color,+) {+ val rad = Math.toRadians(bearingDeg.toDouble() - 90.0)+ drawLine(+ color = color,+ start = center,+ end = Offset(+ center.x + cos(rad).toFloat() * radius,+ center.y + sin(rad).toFloat() * radius,+ ),+ strokeWidth = 4f,+ )+}++private const val ACCURACY_HIGH = 3
measure/src/main/java/com/vayunmathur/measure/ui/CompassPage.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/ui/CompassPage.kt b/measure/src/main/java/com/vayunmathur/measure/ui/CompassPage.ktindex 9bb4ead1ca..0c5f519ae6 100644--- a/measure/src/main/java/com/vayunmathur/measure/ui/CompassPage.kt+++ b/measure/src/main/java/com/vayunmathur/measure/ui/CompassPage.kt@@ -1,47 +1,12 @@ package com.vayunmathur.measure.ui -import androidx.compose.foundation.Canvas-import androidx.compose.foundation.layout.Arrangement-import androidx.compose.foundation.layout.Box-import androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.Spacer-import androidx.compose.foundation.layout.aspectRatio-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.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue-import androidx.compose.ui.Alignment-import androidx.compose.ui.Modifier-import androidx.compose.ui.geometry.Offset-import androidx.compose.ui.graphics.Color-import androidx.compose.ui.graphics.Path-import androidx.compose.ui.graphics.drawscope.DrawScope-import androidx.compose.ui.graphics.drawscope.Stroke-import androidx.compose.ui.graphics.drawscope.rotate-import androidx.compose.ui.text.TextMeasurer-import androidx.compose.ui.text.TextStyle-import androidx.compose.ui.text.rememberTextMeasurer-import androidx.compose.ui.text.drawText-import androidx.compose.ui.unit.dp-import androidx.compose.ui.unit.sp-import com.vayunmathur.library.ui.AppScaffold-import com.vayunmathur.library.ui.IconButton-import com.vayunmathur.library.ui.IconSettings-import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.OutlinedButton-import com.vayunmathur.library.ui.Text import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.measure.Route-import com.vayunmathur.measure.domain.Units-import com.vayunmathur.measure.platform.CompassActions-import com.vayunmathur.measure.platform.CompassUiState import com.vayunmathur.measure.platform.MeasureViewModel import com.vayunmathur.measure.ui.components.MeasureBottomBar-import kotlin.math.cos-import kotlin.math.sin @Composable fun CompassPage(backStack: NavBackStack<Route>, viewModel: MeasureViewModel) {@@ -53,206 +18,3 @@ fun CompassPage(backStack: NavBackStack<Route>, viewModel: MeasureViewModel) { bottomBar = { MeasureBottomBar(backStack, Route.Compass) }, ) }--@Composable-fun CompassContent(- state: CompassUiState,- actions: CompassActions,- onOpenSettings: () -> Unit = {},- bottomBar: @Composable () -> Unit = {},-) {- val heading = if (state.useTrueNorth && state.hasLocation) {- state.azimuthTrueDeg- } else {- state.azimuthMagDeg- }- AppScaffold(- title = "Compass",- actions = { IconButton(onClick = onOpenSettings) { IconSettings() } },- bottomBar = bottomBar,- ) { padding ->- Column(- modifier = Modifier.fillMaxSize().padding(padding).padding(16.dp),- horizontalAlignment = Alignment.CenterHorizontally,- verticalArrangement = Arrangement.spacedBy(12.dp),- ) {- Text(- "${Units.formatBearing(heading)} ${Units.cardinal(heading)}",- style = MaterialTheme.typography.displaySmall,- )- Text(- // Without a location fix declination is unknown, so "true north" would- // be a claim the app cannot back up.- if (state.useTrueNorth && state.hasLocation) "True north" else "Magnetic north",- style = MaterialTheme.typography.bodyMedium,- color = MaterialTheme.colorScheme.onSurfaceVariant,- )-- CompassDial(- headingDeg = heading,- heldBearingDeg = state.heldBearingDeg,- // Height-driven so the dial shrinks to fit a landscape window rather- // than pushing the controls off the bottom.- modifier = Modifier- .weight(1f)- .aspectRatio(1f, matchHeightConstraintsFirst = true)- .padding(8.dp),- )-- if (state.accuracy < ACCURACY_HIGH) {- Text(- "Compass needs calibration — move the phone in a figure-8",- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.error,- )- }- if (state.tiltWarning) {- Text(- "Hold the phone flat for an accurate bearing",- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.error,- )- }- if (state.hasLocation) {- Text(- "Declination ${Units.formatAngle(state.declinationDeg)}",- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.onSurfaceVariant,- )- } else {- Text(- "No location — showing magnetic north only",- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.onSurfaceVariant,- )- }-- Spacer(Modifier.height(4.dp))- Column(- verticalArrangement = Arrangement.spacedBy(8.dp),- horizontalAlignment = Alignment.CenterHorizontally,- ) {- OutlinedButton(- onClick = { actions.setUseTrueNorth(!state.useTrueNorth) },- enabled = state.hasLocation,- ) {- Text(if (state.useTrueNorth) "Show magnetic" else "Show true north")- }- OutlinedButton(- onClick = {- if (state.heldBearingDeg == null) actions.holdBearing()- else actions.clearHeldBearing()- }- ) {- Text(if (state.heldBearingDeg == null) "Hold bearing" else "Release bearing")- }- }- }- }-}--/**- * Compass rose. The dial rotates opposite the heading so north stays physically north- * while the fixed top index reads the current bearing.- */-@Composable-private fun CompassDial(- headingDeg: Double,- heldBearingDeg: Double?,- modifier: Modifier = Modifier,-) {- val measurer = rememberTextMeasurer()- val onSurface = MaterialTheme.colorScheme.onSurface- val variant = MaterialTheme.colorScheme.onSurfaceVariant- val primary = MaterialTheme.colorScheme.primary- val error = MaterialTheme.colorScheme.error-- Box(modifier) {- Canvas(Modifier.fillMaxSize()) {- val radius = size.minDimension / 2f- val center = Offset(size.width / 2f, size.height / 2f)-- drawCircle(variant.copy(alpha = 0.3f), radius, center, style = Stroke(2f))-- rotate(-headingDeg.toFloat(), center) {- drawTicks(center, radius, onSurface, variant)- drawCardinals(measurer, center, radius, onSurface, error)- if (heldBearingDeg != null) {- drawHeldBearing(center, radius, heldBearingDeg.toFloat(), primary)- }- }-- // Fixed index at the top: the bearing is whatever sits under it.- val p = Path().apply {- moveTo(center.x, center.y - radius - 2f)- lineTo(center.x - 14f, center.y - radius + 22f)- lineTo(center.x + 14f, center.y - radius + 22f)- close()- }- drawPath(p, primary)- }- }-}--private fun DrawScope.drawTicks(center: Offset, radius: Float, major: Color, minor: Color) {- for (deg in 0 until 360 step 5) {- val isMajor = deg % 30 == 0- val len = if (isMajor) radius * 0.10f else radius * 0.05f- val rad = Math.toRadians(deg.toDouble() - 90.0)- val cosA = cos(rad).toFloat()- val sinA = sin(rad).toFloat()- drawLine(- color = if (isMajor) major else minor.copy(alpha = 0.5f),- start = Offset(center.x + cosA * (radius - len), center.y + sinA * (radius - len)),- end = Offset(center.x + cosA * radius, center.y + sinA * radius),- strokeWidth = if (isMajor) 3f else 1.5f,- )- }-}--private fun DrawScope.drawCardinals(- measurer: TextMeasurer,- center: Offset,- radius: Float,- normal: Color,- northColor: Color,-) {- val labels = listOf(0 to "N", 90 to "E", 180 to "S", 270 to "W")- for ((deg, label) in labels) {- val rad = Math.toRadians(deg.toDouble() - 90.0)- val r = radius * 0.78f- val style = TextStyle(- fontSize = 20.sp,- color = if (label == "N") northColor else normal,- )- val layout = measurer.measure(label, style)- drawText(- layout,- topLeft = Offset(- center.x + cos(rad).toFloat() * r - layout.size.width / 2f,- center.y + sin(rad).toFloat() * r - layout.size.height / 2f,- ),- )- }-}--private fun DrawScope.drawHeldBearing(- center: Offset,- radius: Float,- bearingDeg: Float,- color: Color,-) {- val rad = Math.toRadians(bearingDeg.toDouble() - 90.0)- drawLine(- color = color,- start = center,- end = Offset(- center.x + cos(rad).toFloat() * radius,- center.y + sin(rad).toFloat() * radius,- ),- strokeWidth = 4f,- )-}--private const val ACCURACY_HIGH = 3-
measure/src/main/java/com/vayunmathur/measure/ui/DiagnosticsContent.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/ui/DiagnosticsContent.kt b/measure/src/main/java/com/vayunmathur/measure/ui/DiagnosticsContent.ktnew file mode 100644index 0000000000..7d6777e3e8--- /dev/null+++ b/measure/src/main/java/com/vayunmathur/measure/ui/DiagnosticsContent.kt@@ -0,0 +1,80 @@+package com.vayunmathur.measure.ui++import androidx.compose.foundation.layout.Arrangement+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.rememberScrollState+import androidx.compose.foundation.verticalScroll+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.SettingsDivider+import com.vayunmathur.library.ui.SettingsRow+import com.vayunmathur.library.ui.SettingsSection+import com.vayunmathur.library.ui.Text+import com.vayunmathur.measure.platform.DiagnosticsActions+import com.vayunmathur.measure.platform.DiagnosticsUiState++@Composable+fun DiagnosticsContent(+ state: DiagnosticsUiState,+ actions: DiagnosticsActions,+ onBack: () -> Unit = {},+) {+ AppScaffold(title = "Diagnostics", onNavigateBack = onBack) { padding ->+ Column(+ modifier = Modifier.fillMaxSize().padding(padding)+ .verticalScroll(rememberScrollState())+ ) {+ SettingsSection(title = "Engine") {+ DiagRow("Native engine", if (state.nativeEngineAvailable) "loaded" else "unavailable")+ DiagRow("Landmarks", state.landmarkCount.toString())+ DiagRow("Scale confidence", "%.2f".format(state.scaleConfidence))+ }+ SettingsDivider()+ SettingsSection(title = "Tracking") {+ DiagRow("Features detected", state.featureCount.toString())+ DiagRow("Features tracked", state.trackedCount.toString())+ DiagRow("Frame rate", "%.1f Hz".format(state.frameRateHz))+ }+ SettingsDivider()+ SettingsSection(title = "Sensors") {+ DiagRow("IMU rate", "%.0f Hz".format(state.imuRateHz))+ DiagRow(+ "Camera/IMU clock skew",+ "%.1f ms".format(state.timestampSkewMs),+ )+ }+ SettingsDivider()+ SettingsSection(title = "Intrinsics") {+ DiagRow("Focal length", "%.1f px".format(state.focalPx))+ DiagRow(+ "Principal point",+ "%.1f, %.1f".format(state.principalPointPx.first, state.principalPointPx.second),+ )+ }+ SettingsDivider()+ SettingsRow(title = "Reset tracking", onClick = actions::resetTracking)+ }+ }+}++@Composable+private fun DiagRow(label: String, value: String) {+ Row(+ modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),+ horizontalArrangement = Arrangement.SpaceBetween,+ ) {+ Text(label, style = MaterialTheme.typography.bodyMedium)+ Text(+ value,+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+}
measure/src/main/java/com/vayunmathur/measure/ui/DiagnosticsPage.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/ui/DiagnosticsPage.kt b/measure/src/main/java/com/vayunmathur/measure/ui/DiagnosticsPage.ktindex adc415f5a7..699b6b43ee 100644--- a/measure/src/main/java/com/vayunmathur/measure/ui/DiagnosticsPage.kt+++ b/measure/src/main/java/com/vayunmathur/measure/ui/DiagnosticsPage.kt@@ -1,28 +1,10 @@ package com.vayunmathur.measure.ui -import androidx.compose.foundation.layout.Arrangement-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.rememberScrollState-import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue-import androidx.compose.ui.Modifier-import androidx.compose.ui.unit.dp-import com.vayunmathur.library.ui.AppScaffold-import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.SettingsDivider-import com.vayunmathur.library.ui.SettingsRow-import com.vayunmathur.library.ui.SettingsSection-import com.vayunmathur.library.ui.Text import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.measure.Route-import com.vayunmathur.measure.platform.DiagnosticsActions-import com.vayunmathur.measure.platform.DiagnosticsUiState import com.vayunmathur.measure.platform.MeasureViewModel @Composable@@ -34,62 +16,3 @@ fun DiagnosticsPage(backStack: NavBackStack<Route>, viewModel: MeasureViewModel) onBack = { backStack.pop() }, ) }--@Composable-fun DiagnosticsContent(- state: DiagnosticsUiState,- actions: DiagnosticsActions,- onBack: () -> Unit = {},-) {- AppScaffold(title = "Diagnostics", onNavigateBack = onBack) { padding ->- Column(- modifier = Modifier.fillMaxSize().padding(padding)- .verticalScroll(rememberScrollState())- ) {- SettingsSection(title = "Engine") {- DiagRow("Native engine", if (state.nativeEngineAvailable) "loaded" else "unavailable")- DiagRow("Landmarks", state.landmarkCount.toString())- DiagRow("Scale confidence", "%.2f".format(state.scaleConfidence))- }- SettingsDivider()- SettingsSection(title = "Tracking") {- DiagRow("Features detected", state.featureCount.toString())- DiagRow("Features tracked", state.trackedCount.toString())- DiagRow("Frame rate", "%.1f Hz".format(state.frameRateHz))- }- SettingsDivider()- SettingsSection(title = "Sensors") {- DiagRow("IMU rate", "%.0f Hz".format(state.imuRateHz))- DiagRow(- "Camera/IMU clock skew",- "%.1f ms".format(state.timestampSkewMs),- )- }- SettingsDivider()- SettingsSection(title = "Intrinsics") {- DiagRow("Focal length", "%.1f px".format(state.focalPx))- DiagRow(- "Principal point",- "%.1f, %.1f".format(state.principalPointPx.first, state.principalPointPx.second),- )- }- SettingsDivider()- SettingsRow(title = "Reset tracking", onClick = actions::resetTracking)- }- }-}--@Composable-private fun DiagRow(label: String, value: String) {- Row(- modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),- horizontalArrangement = Arrangement.SpaceBetween,- ) {- Text(label, style = MaterialTheme.typography.bodyMedium)- Text(- value,- style = MaterialTheme.typography.bodyMedium,- color = MaterialTheme.colorScheme.onSurfaceVariant,- )- }-}
measure/src/main/java/com/vayunmathur/measure/ui/LevelContent.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/ui/LevelContent.kt b/measure/src/main/java/com/vayunmathur/measure/ui/LevelContent.ktnew file mode 100644index 0000000000..1989fc28d2--- /dev/null+++ b/measure/src/main/java/com/vayunmathur/measure/ui/LevelContent.kt@@ -0,0 +1,196 @@+package com.vayunmathur.measure.ui++import androidx.compose.foundation.Canvas+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.aspectRatio+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.rotate+import androidx.compose.ui.geometry.CornerRadius+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconSettings+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.Text+import com.vayunmathur.measure.domain.Units+import com.vayunmathur.measure.platform.LevelActions+import com.vayunmathur.measure.platform.LevelUiState+import kotlin.math.abs+import kotlin.math.hypot+import kotlin.math.min++@Composable+fun LevelContent(+ state: LevelUiState,+ actions: LevelActions,+ onOpenSettings: () -> Unit = {},+ bottomBar: @Composable () -> Unit = {},+) {+ AppScaffold(+ title = "Level",+ actions = { IconButton(onClick = onOpenSettings) { IconSettings() } },+ bottomBar = bottomBar,+ ) { padding ->+ Column(+ modifier = Modifier.fillMaxSize().padding(padding).padding(16.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.spacedBy(16.dp),+ ) {+ val isLevel = if (state.isFlat) {+ abs(state.pitchDeg) < LEVEL_TOLERANCE_DEG && abs(state.rollDeg) < LEVEL_TOLERANCE_DEG+ } else {+ abs(state.edgeAngleDeg) < LEVEL_TOLERANCE_DEG+ }++ Text(+ if (state.isFlat) {+ "${Units.formatAngle(state.pitchDeg)} / ${Units.formatAngle(state.rollDeg)}"+ } else {+ Units.formatAngle(state.edgeAngleDeg)+ },+ style = MaterialTheme.typography.displaySmall,+ color = if (isLevel) {+ MaterialTheme.colorScheme.primary+ } else {+ MaterialTheme.colorScheme.onSurface+ },+ )+ Text(+ if (state.isFlat) "Surface level" else state.orientation.label,+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )++ if (state.isFlat) {+ SurfaceBubble(+ pitchDeg = state.pitchDeg,+ rollDeg = state.rollDeg,+ // Sized from the leftover height, not the width: a width-driven+ // square is taller than a landscape window and pushes the controls+ // off the bottom.+ modifier = Modifier+ .weight(1f)+ .aspectRatio(1f, matchHeightConstraintsFirst = true)+ .padding(16.dp),+ )+ } else {+ EdgeBubble(+ angleDeg = state.edgeAngleDeg,+ // Keeps the bar horizontal in the real world whether or not the+ // activity rotated with the device.+ uiRotationDeg = state.uiRotationDeg,+ modifier = Modifier.fillMaxWidth().weight(1f),+ )+ }++ OutlinedButton(onClick = {+ if (state.isCalibrated) actions.clearCalibration() else actions.calibrateZero()+ }) {+ Text(if (state.isCalibrated) "Clear calibration" else "Set zero here")+ }+ if (state.isCalibrated) {+ Text(+ "Zeroed against a reference surface",+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ }+ }+}++/** Circular two-axis bubble, used when the phone lies flat. */+@Composable+private fun SurfaceBubble(pitchDeg: Double, rollDeg: Double, modifier: Modifier = Modifier) {+ val outline = MaterialTheme.colorScheme.outline+ val primary = MaterialTheme.colorScheme.primary+ val surfaceVariant = MaterialTheme.colorScheme.surfaceVariant+ val level = abs(pitchDeg) < LEVEL_TOLERANCE_DEG && abs(rollDeg) < LEVEL_TOLERANCE_DEG++ Canvas(modifier) {+ val radius = size.minDimension / 2f+ val center = Offset(size.width / 2f, size.height / 2f)+ drawCircle(surfaceVariant, radius, center)+ drawCircle(outline, radius, center, style = Stroke(2f))+ // Inner ring marks the in-tolerance zone. Sized to the bubble so "inside the+ // ring" and "reads level" agree; a ring scaled to the tolerance angle alone+ // would be a couple of pixels across and useless to aim at.+ val bubbleRadius = min(radius * 0.18f, 44f)+ drawCircle(outline, bubbleRadius * 1.35f, center, style = Stroke(2f))+ drawLine(outline, Offset(center.x - radius, center.y), Offset(center.x + radius, center.y), 1f)+ drawLine(outline, Offset(center.x, center.y - radius), Offset(center.x, center.y + radius), 1f)++ // Bubble floats toward the raised side, like a real spirit level.+ val nx = (rollDeg / MAX_DISPLAY_DEG).coerceIn(-1.0, 1.0).toFloat()+ val ny = (-pitchDeg / MAX_DISPLAY_DEG).coerceIn(-1.0, 1.0).toFloat()+ val mag = hypot(nx, ny).coerceAtMost(1f)+ val norm = hypot(nx, ny)+ val dirX = if (norm > 0f) nx / norm else 0f+ val dirY = if (norm > 0f) ny / norm else 0f+ val travel = radius - bubbleRadius+ val pos = Offset(center.x + dirX * mag * travel, center.y + dirY * mag * travel)++ drawCircle(+ color = if (level) primary else primary.copy(alpha = 0.6f),+ radius = bubbleRadius,+ center = pos,+ )+ }+}++/**+ * Single-axis bubble for a phone stood on any of its four edges.+ *+ * [angleDeg] is already measured against the nearest quarter turn, so this reads the+ * same whether the phone is upright, upside down, or on its side.+ */+@Composable+private fun EdgeBubble(angleDeg: Double, uiRotationDeg: Float, modifier: Modifier = Modifier) {+ val outline = MaterialTheme.colorScheme.outline+ val primary = MaterialTheme.colorScheme.primary+ val surfaceVariant = MaterialTheme.colorScheme.surfaceVariant+ val level = abs(angleDeg) < LEVEL_TOLERANCE_DEG++ Canvas(modifier.rotate(uiRotationDeg)) {+ val barHeight = min(size.height, 90f.coerceAtLeast(size.height * 0.4f))+ val top = (size.height - barHeight) / 2f+ val w = size.width++ drawRoundRect(+ color = surfaceVariant,+ topLeft = Offset(0f, top),+ size = androidx.compose.ui.geometry.Size(w, barHeight),+ cornerRadius = CornerRadius(barHeight / 2f),+ )+ drawLine(outline, Offset(w / 2f, top), Offset(w / 2f, top + barHeight), 2f)++ val bubbleRadius = barHeight * 0.35f+ drawCircle(+ outline,+ bubbleRadius * 1.3f,+ Offset(w / 2f, top + barHeight / 2f),+ style = Stroke(2f),+ )++ val n = (angleDeg / MAX_DISPLAY_DEG).coerceIn(-1.0, 1.0).toFloat()+ val cx = w / 2f + n * (w / 2f - bubbleRadius)+ drawCircle(+ color = if (level) primary else primary.copy(alpha = 0.6f),+ radius = bubbleRadius,+ center = Offset(cx, top + barHeight / 2f),+ )+ }+}++/** Deflection at which the bubble reaches the edge of its travel. */+private const val MAX_DISPLAY_DEG = 15.0+private const val LEVEL_TOLERANCE_DEG = 0.35
measure/src/main/java/com/vayunmathur/measure/ui/LevelPage.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/ui/LevelPage.kt b/measure/src/main/java/com/vayunmathur/measure/ui/LevelPage.ktindex dbb14e85ab..506a4c737d 100644--- a/measure/src/main/java/com/vayunmathur/measure/ui/LevelPage.kt+++ b/measure/src/main/java/com/vayunmathur/measure/ui/LevelPage.kt@@ -1,39 +1,12 @@ package com.vayunmathur.measure.ui -import androidx.compose.foundation.Canvas-import androidx.compose.foundation.layout.Arrangement-import androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.aspectRatio-import androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.foundation.layout.fillMaxWidth-import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue-import androidx.compose.ui.Alignment-import androidx.compose.ui.Modifier-import androidx.compose.ui.draw.rotate-import androidx.compose.ui.geometry.CornerRadius-import androidx.compose.ui.geometry.Offset-import androidx.compose.ui.graphics.drawscope.Stroke-import androidx.compose.ui.unit.dp-import com.vayunmathur.library.ui.AppScaffold-import com.vayunmathur.library.ui.IconButton-import com.vayunmathur.library.ui.IconSettings-import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.OutlinedButton-import com.vayunmathur.library.ui.Text import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.measure.Route-import com.vayunmathur.measure.domain.HeldOrientation-import com.vayunmathur.measure.domain.Units-import com.vayunmathur.measure.platform.LevelActions-import com.vayunmathur.measure.platform.LevelUiState import com.vayunmathur.measure.platform.MeasureViewModel import com.vayunmathur.measure.ui.components.MeasureBottomBar-import kotlin.math.abs-import kotlin.math.hypot-import kotlin.math.min @Composable fun LevelPage(backStack: NavBackStack<Route>, viewModel: MeasureViewModel) {@@ -45,170 +18,3 @@ fun LevelPage(backStack: NavBackStack<Route>, viewModel: MeasureViewModel) { bottomBar = { MeasureBottomBar(backStack, Route.Level) }, ) }--@Composable-fun LevelContent(- state: LevelUiState,- actions: LevelActions,- onOpenSettings: () -> Unit = {},- bottomBar: @Composable () -> Unit = {},-) {- AppScaffold(- title = "Level",- actions = { IconButton(onClick = onOpenSettings) { IconSettings() } },- bottomBar = bottomBar,- ) { padding ->- Column(- modifier = Modifier.fillMaxSize().padding(padding).padding(16.dp),- horizontalAlignment = Alignment.CenterHorizontally,- verticalArrangement = Arrangement.spacedBy(16.dp),- ) {- val isLevel = if (state.isFlat) {- abs(state.pitchDeg) < LEVEL_TOLERANCE_DEG && abs(state.rollDeg) < LEVEL_TOLERANCE_DEG- } else {- abs(state.edgeAngleDeg) < LEVEL_TOLERANCE_DEG- }-- Text(- if (state.isFlat) {- "${Units.formatAngle(state.pitchDeg)} / ${Units.formatAngle(state.rollDeg)}"- } else {- Units.formatAngle(state.edgeAngleDeg)- },- style = MaterialTheme.typography.displaySmall,- color = if (isLevel) {- MaterialTheme.colorScheme.primary- } else {- MaterialTheme.colorScheme.onSurface- },- )- Text(- if (state.isFlat) "Surface level" else state.orientation.label,- style = MaterialTheme.typography.bodyMedium,- color = MaterialTheme.colorScheme.onSurfaceVariant,- )-- if (state.isFlat) {- SurfaceBubble(- pitchDeg = state.pitchDeg,- rollDeg = state.rollDeg,- // Sized from the leftover height, not the width: a width-driven- // square is taller than a landscape window and pushes the controls- // off the bottom.- modifier = Modifier- .weight(1f)- .aspectRatio(1f, matchHeightConstraintsFirst = true)- .padding(16.dp),- )- } else {- EdgeBubble(- angleDeg = state.edgeAngleDeg,- // Keeps the bar horizontal in the real world whether or not the- // activity rotated with the device.- uiRotationDeg = state.uiRotationDeg,- modifier = Modifier.fillMaxWidth().weight(1f),- )- }-- OutlinedButton(onClick = {- if (state.isCalibrated) actions.clearCalibration() else actions.calibrateZero()- }) {- Text(if (state.isCalibrated) "Clear calibration" else "Set zero here")- }- if (state.isCalibrated) {- Text(- "Zeroed against a reference surface",- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.onSurfaceVariant,- )- }- }- }-}--/** Circular two-axis bubble, used when the phone lies flat. */-@Composable-private fun SurfaceBubble(pitchDeg: Double, rollDeg: Double, modifier: Modifier = Modifier) {- val outline = MaterialTheme.colorScheme.outline- val primary = MaterialTheme.colorScheme.primary- val surfaceVariant = MaterialTheme.colorScheme.surfaceVariant- val level = abs(pitchDeg) < LEVEL_TOLERANCE_DEG && abs(rollDeg) < LEVEL_TOLERANCE_DEG-- Canvas(modifier) {- val radius = size.minDimension / 2f- val center = Offset(size.width / 2f, size.height / 2f)- drawCircle(surfaceVariant, radius, center)- drawCircle(outline, radius, center, style = Stroke(2f))- // Inner ring marks the in-tolerance zone. Sized to the bubble so "inside the- // ring" and "reads level" agree; a ring scaled to the tolerance angle alone- // would be a couple of pixels across and useless to aim at.- val bubbleRadius = min(radius * 0.18f, 44f)- drawCircle(outline, bubbleRadius * 1.35f, center, style = Stroke(2f))- drawLine(outline, Offset(center.x - radius, center.y), Offset(center.x + radius, center.y), 1f)- drawLine(outline, Offset(center.x, center.y - radius), Offset(center.x, center.y + radius), 1f)-- // Bubble floats toward the raised side, like a real spirit level.- val nx = (rollDeg / MAX_DISPLAY_DEG).coerceIn(-1.0, 1.0).toFloat()- val ny = (-pitchDeg / MAX_DISPLAY_DEG).coerceIn(-1.0, 1.0).toFloat()- val mag = hypot(nx, ny).coerceAtMost(1f)- val norm = hypot(nx, ny)- val dirX = if (norm > 0f) nx / norm else 0f- val dirY = if (norm > 0f) ny / norm else 0f- val travel = radius - bubbleRadius- val pos = Offset(center.x + dirX * mag * travel, center.y + dirY * mag * travel)-- drawCircle(- color = if (level) primary else primary.copy(alpha = 0.6f),- radius = bubbleRadius,- center = pos,- )- }-}--/**- * Single-axis bubble for a phone stood on any of its four edges.- *- * [angleDeg] is already measured against the nearest quarter turn, so this reads the- * same whether the phone is upright, upside down, or on its side.- */-@Composable-private fun EdgeBubble(angleDeg: Double, uiRotationDeg: Float, modifier: Modifier = Modifier) {- val outline = MaterialTheme.colorScheme.outline- val primary = MaterialTheme.colorScheme.primary- val surfaceVariant = MaterialTheme.colorScheme.surfaceVariant- val level = abs(angleDeg) < LEVEL_TOLERANCE_DEG-- Canvas(modifier.rotate(uiRotationDeg)) {- val barHeight = min(size.height, 90f.coerceAtLeast(size.height * 0.4f))- val top = (size.height - barHeight) / 2f- val w = size.width-- drawRoundRect(- color = surfaceVariant,- topLeft = Offset(0f, top),- size = androidx.compose.ui.geometry.Size(w, barHeight),- cornerRadius = CornerRadius(barHeight / 2f),- )- drawLine(outline, Offset(w / 2f, top), Offset(w / 2f, top + barHeight), 2f)-- val bubbleRadius = barHeight * 0.35f- drawCircle(- outline,- bubbleRadius * 1.3f,- Offset(w / 2f, top + barHeight / 2f),- style = Stroke(2f),- )-- val n = (angleDeg / MAX_DISPLAY_DEG).coerceIn(-1.0, 1.0).toFloat()- val cx = w / 2f + n * (w / 2f - bubbleRadius)- drawCircle(- color = if (level) primary else primary.copy(alpha = 0.6f),- radius = bubbleRadius,- center = Offset(cx, top + barHeight / 2f),- )- }-}--/** Deflection at which the bubble reaches the edge of its travel. */-private const val MAX_DISPLAY_DEG = 15.0-private const val LEVEL_TOLERANCE_DEG = 0.35
measure/src/main/java/com/vayunmathur/measure/ui/RulerContent.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/ui/RulerContent.kt b/measure/src/main/java/com/vayunmathur/measure/ui/RulerContent.ktnew file mode 100644index 0000000000..74320df652--- /dev/null+++ b/measure/src/main/java/com/vayunmathur/measure/ui/RulerContent.kt@@ -0,0 +1,155 @@+package com.vayunmathur.measure.ui++import androidx.compose.foundation.Canvas+import androidx.compose.foundation.gestures.detectDragGestures+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableFloatStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.input.pointer.pointerInput+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.library.ui.AppScaffold+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconSettings+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import com.vayunmathur.measure.data.model.UnitSystem+import com.vayunmathur.measure.domain.Units+import com.vayunmathur.measure.platform.RulerUiState++@Composable+fun RulerContent(+ state: RulerUiState,+ onOpenSettings: () -> Unit = {},+ bottomBar: @Composable () -> Unit = {},+) {+ var markerY by remember { mutableFloatStateOf(0f) }++ AppScaffold(+ title = "Ruler",+ actions = { IconButton(onClick = onOpenSettings) { IconSettings() } },+ bottomBar = bottomBar,+ ) { padding ->+ Column(+ modifier = Modifier.fillMaxSize().padding(padding),+ horizontalAlignment = Alignment.CenterHorizontally,+ ) {+ val fromTopMm = markerY / state.pixelsPerMm++ Text(+ Units.formatLength(fromTopMm / 1000.0, state.unitSystem),+ style = MaterialTheme.typography.headlineMedium,+ modifier = Modifier.padding(top = 8.dp),+ )+ Text(+ "Drag the line; read against either edge",+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ modifier = Modifier.padding(bottom = 4.dp),+ )++ RulerScale(+ pixelsPerMm = state.pixelsPerMm,+ unitSystem = state.unitSystem,+ markerY = markerY,+ onMarkerChange = { markerY = it },+ onHeightChange = { h -> if (markerY == 0f) markerY = h / 2f },+ modifier = Modifier.fillMaxWidth().weight(1f),+ )+ }+ }+}++/**+ * Vertical scale down both edges with a draggable measuring marker.+ *+ * Both scales run top-down and read identically, so an object can be laid against+ * whichever edge of the phone is convenient. They deliberately do *not* mirror: opposed+ * scales would be rotationally symmetric, so turning the phone around would give the+ * same reading back and the second scale would earn nothing.+ *+ * Tick spacing is driven by the physical pixel density rather than by dp: dp is a+ * rendering convenience, not a unit of length.+ */+@Composable+private fun RulerScale(+ pixelsPerMm: Float,+ unitSystem: UnitSystem,+ markerY: Float,+ onMarkerChange: (Float) -> Unit,+ onHeightChange: (Float) -> Unit,+ modifier: Modifier = Modifier,+) {+ val measurer = rememberTextMeasurer()+ val onSurface = MaterialTheme.colorScheme.onSurface+ val primary = MaterialTheme.colorScheme.primary+ val variant = MaterialTheme.colorScheme.onSurfaceVariant++ Canvas(+ modifier.pointerInput(Unit) {+ detectDragGestures { change, _ ->+ onMarkerChange(change.position.y.coerceIn(0f, size.height.toFloat()))+ }+ }+ ) {+ onHeightChange(size.height)++ val metric = unitSystem == UnitSystem.Metric+ // Metric: a tick every mm. Imperial: every 1/16 inch.+ val minorStepPx = if (metric) pixelsPerMm else pixelsPerMm * Units.MM_PER_INCH.toFloat() / 16f+ val majorEvery = if (metric) 10 else 16+ val midEvery = if (metric) 5 else 8+ if (minorStepPx <= 0.5f) return@Canvas++ val maxTickLen = size.width * 0.24f++ // `leftEdge` only changes which side the ticks grow from; both scales measure+ // the same distance from the top.+ fun drawEdge(leftEdge: Boolean) {+ var i = 0+ while (true) {+ val y = i * minorStepPx+ if (y > size.height) break+ val isMajor = i % majorEvery == 0+ val isMid = i % midEvery == 0+ val len = when {+ isMajor -> maxTickLen+ isMid -> maxTickLen * 0.62f+ else -> maxTickLen * 0.36f+ }+ val start = if (leftEdge) Offset(0f, y) else Offset(size.width - len, y)+ val end = if (leftEdge) Offset(len, y) else Offset(size.width, y)+ drawLine(+ color = if (isMajor) onSurface else variant,+ start = start,+ end = end,+ strokeWidth = if (isMajor) 3f else 1.5f,+ )+ if (isMajor && i > 0) {+ val label = if (metric) "${i / 10}" else "${i / 16}"+ val layout = measurer.measure(label, TextStyle(fontSize = 13.sp, color = onSurface))+ val lx = if (leftEdge) len + 8f else size.width - len - 8f - layout.size.width+ drawText(layout, topLeft = Offset(lx, y - layout.size.height / 2f))+ }+ i+++ }+ }++ drawEdge(leftEdge = true)+ drawEdge(leftEdge = false)++ drawLine(primary, Offset(0f, markerY), Offset(size.width, markerY), 3f)+ }+}
measure/src/main/java/com/vayunmathur/measure/ui/RulerPage.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/ui/RulerPage.kt b/measure/src/main/java/com/vayunmathur/measure/ui/RulerPage.ktindex 1bf321a766..6e0c7f3f6c 100644--- a/measure/src/main/java/com/vayunmathur/measure/ui/RulerPage.kt+++ b/measure/src/main/java/com/vayunmathur/measure/ui/RulerPage.kt@@ -1,39 +1,14 @@ package com.vayunmathur.measure.ui -import androidx.compose.foundation.Canvas-import androidx.compose.foundation.gestures.detectDragGestures-import androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.foundation.layout.fillMaxWidth-import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableFloatStateOf-import androidx.compose.runtime.remember-import androidx.compose.runtime.setValue-import androidx.compose.ui.Alignment-import androidx.compose.ui.Modifier-import androidx.compose.ui.geometry.Offset-import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.LocalResources-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.library.ui.AppScaffold-import com.vayunmathur.library.ui.IconButton-import com.vayunmathur.library.ui.IconSettings-import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.Text import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.measure.Route-import com.vayunmathur.measure.data.model.UnitSystem import com.vayunmathur.measure.domain.Units import com.vayunmathur.measure.platform.MeasureViewModel-import com.vayunmathur.measure.platform.RulerUiState import com.vayunmathur.measure.ui.components.MeasureBottomBar @Composable@@ -56,128 +31,3 @@ fun RulerPage(backStack: NavBackStack<Route>, viewModel: MeasureViewModel) { bottomBar = { MeasureBottomBar(backStack, Route.Ruler) }, ) }--@Composable-fun RulerContent(- state: RulerUiState,- onOpenSettings: () -> Unit = {},- bottomBar: @Composable () -> Unit = {},-) {- var markerY by remember { mutableFloatStateOf(0f) }-- AppScaffold(- title = "Ruler",- actions = { IconButton(onClick = onOpenSettings) { IconSettings() } },- bottomBar = bottomBar,- ) { padding ->- Column(- modifier = Modifier.fillMaxSize().padding(padding),- horizontalAlignment = Alignment.CenterHorizontally,- ) {- val fromTopMm = markerY / state.pixelsPerMm-- Text(- Units.formatLength(fromTopMm / 1000.0, state.unitSystem),- style = MaterialTheme.typography.headlineMedium,- modifier = Modifier.padding(top = 8.dp),- )- Text(- "Drag the line; read against either edge",- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.onSurfaceVariant,- modifier = Modifier.padding(bottom = 4.dp),- )-- RulerScale(- pixelsPerMm = state.pixelsPerMm,- unitSystem = state.unitSystem,- markerY = markerY,- onMarkerChange = { markerY = it },- onHeightChange = { h -> if (markerY == 0f) markerY = h / 2f },- modifier = Modifier.fillMaxWidth().weight(1f),- )- }- }-}--/**- * Vertical scale down both edges with a draggable measuring marker.- *- * Both scales run top-down and read identically, so an object can be laid against- * whichever edge of the phone is convenient. They deliberately do *not* mirror: opposed- * scales would be rotationally symmetric, so turning the phone around would give the- * same reading back and the second scale would earn nothing.- *- * Tick spacing is driven by the physical pixel density rather than by dp: dp is a- * rendering convenience, not a unit of length.- */-@Composable-private fun RulerScale(- pixelsPerMm: Float,- unitSystem: UnitSystem,- markerY: Float,- onMarkerChange: (Float) -> Unit,- onHeightChange: (Float) -> Unit,- modifier: Modifier = Modifier,-) {- val measurer = rememberTextMeasurer()- val onSurface = MaterialTheme.colorScheme.onSurface- val primary = MaterialTheme.colorScheme.primary- val variant = MaterialTheme.colorScheme.onSurfaceVariant-- Canvas(- modifier.pointerInput(Unit) {- detectDragGestures { change, _ ->- onMarkerChange(change.position.y.coerceIn(0f, size.height.toFloat()))- }- }- ) {- onHeightChange(size.height)-- val metric = unitSystem == UnitSystem.Metric- // Metric: a tick every mm. Imperial: every 1/16 inch.- val minorStepPx = if (metric) pixelsPerMm else pixelsPerMm * Units.MM_PER_INCH.toFloat() / 16f- val majorEvery = if (metric) 10 else 16- val midEvery = if (metric) 5 else 8- if (minorStepPx <= 0.5f) return@Canvas-- val maxTickLen = size.width * 0.24f-- // `leftEdge` only changes which side the ticks grow from; both scales measure- // the same distance from the top.- fun drawEdge(leftEdge: Boolean) {- var i = 0- while (true) {- val y = i * minorStepPx- if (y > size.height) break- val isMajor = i % majorEvery == 0- val isMid = i % midEvery == 0- val len = when {- isMajor -> maxTickLen- isMid -> maxTickLen * 0.62f- else -> maxTickLen * 0.36f- }- val start = if (leftEdge) Offset(0f, y) else Offset(size.width - len, y)- val end = if (leftEdge) Offset(len, y) else Offset(size.width, y)- drawLine(- color = if (isMajor) onSurface else variant,- start = start,- end = end,- strokeWidth = if (isMajor) 3f else 1.5f,- )- if (isMajor && i > 0) {- val label = if (metric) "${i / 10}" else "${i / 16}"- val layout = measurer.measure(label, TextStyle(fontSize = 13.sp, color = onSurface))- val lx = if (leftEdge) len + 8f else size.width - len - 8f - layout.size.width- drawText(layout, topLeft = Offset(lx, y - layout.size.height / 2f))- }- i++- }- }-- drawEdge(leftEdge = true)- drawEdge(leftEdge = false)-- drawLine(primary, Offset(0f, markerY), Offset(size.width, markerY), 3f)- }-}
measure/src/main/java/com/vayunmathur/measure/ui/SavedMeasurementsContent.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/ui/SavedMeasurementsContent.kt b/measure/src/main/java/com/vayunmathur/measure/ui/SavedMeasurementsContent.ktnew file mode 100644index 0000000000..26d31bfd8c--- /dev/null+++ b/measure/src/main/java/com/vayunmathur/measure/ui/SavedMeasurementsContent.kt@@ -0,0 +1,66 @@+package com.vayunmathur.measure.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconDelete+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.SettingsRow+import com.vayunmathur.library.ui.Text+import com.vayunmathur.measure.data.model.MeasurementKind+import com.vayunmathur.measure.data.model.SavedMeasurement+import com.vayunmathur.measure.data.model.UnitSystem+import com.vayunmathur.measure.domain.Units+import com.vayunmathur.measure.platform.SavedActions+import com.vayunmathur.measure.platform.SavedUiState++@Composable+fun SavedMeasurementsContent(+ state: SavedUiState,+ actions: SavedActions,+ onBack: () -> Unit = {},+) {+ AppScaffold(title = "Saved", onNavigateBack = onBack) { padding ->+ if (state.measurements.isEmpty()) {+ Column(+ modifier = Modifier.fillMaxSize().padding(padding).padding(32.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.Center,+ ) {+ Text("No saved measurements", style = MaterialTheme.typography.titleMedium)+ Text(+ "Measure something in AR and tap save",+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ } else {+ LazyColumn(modifier = Modifier.fillMaxSize().padding(padding)) {+ items(state.measurements, key = { it.id }) { m ->+ SettingsRow(+ title = m.label,+ supportingText = formatMeasurement(m, state.unitSystem),+ trailingContent = {+ IconButton(onClick = { actions.delete(m.id) }) { IconDelete() }+ },+ )+ }+ }+ }+ }+}++private fun formatMeasurement(m: SavedMeasurement, system: UnitSystem): String = when (m.kind) {+ MeasurementKind.Area -> Units.formatArea(m.value, system)+ MeasurementKind.Angle -> Units.formatAngle(m.value)+ else -> Units.formatLength(m.value, system)+}
measure/src/main/java/com/vayunmathur/measure/ui/SavedMeasurementsPage.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/ui/SavedMeasurementsPage.kt b/measure/src/main/java/com/vayunmathur/measure/ui/SavedMeasurementsPage.ktindex 3f03b65de0..54cadee229 100644--- a/measure/src/main/java/com/vayunmathur/measure/ui/SavedMeasurementsPage.kt+++ b/measure/src/main/java/com/vayunmathur/measure/ui/SavedMeasurementsPage.kt@@ -1,32 +1,11 @@ package com.vayunmathur.measure.ui -import androidx.compose.foundation.layout.Arrangement-import androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.foundation.layout.padding-import androidx.compose.foundation.lazy.LazyColumn-import androidx.compose.foundation.lazy.items import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue-import androidx.compose.ui.Alignment-import androidx.compose.ui.Modifier-import androidx.compose.ui.unit.dp-import com.vayunmathur.library.ui.AppScaffold-import com.vayunmathur.library.ui.IconButton-import com.vayunmathur.library.ui.IconDelete-import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.SettingsRow-import com.vayunmathur.library.ui.Text import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.measure.Route-import com.vayunmathur.measure.data.model.MeasurementKind-import com.vayunmathur.measure.data.model.SavedMeasurement-import com.vayunmathur.measure.data.model.UnitSystem-import com.vayunmathur.measure.domain.Units import com.vayunmathur.measure.platform.MeasureViewModel-import com.vayunmathur.measure.platform.SavedActions-import com.vayunmathur.measure.platform.SavedUiState @Composable fun SavedMeasurementsPage(backStack: NavBackStack<Route>, viewModel: MeasureViewModel) {@@ -37,45 +16,3 @@ fun SavedMeasurementsPage(backStack: NavBackStack<Route>, viewModel: MeasureView onBack = { backStack.pop() }, ) }--@Composable-fun SavedMeasurementsContent(- state: SavedUiState,- actions: SavedActions,- onBack: () -> Unit = {},-) {- AppScaffold(title = "Saved", onNavigateBack = onBack) { padding ->- if (state.measurements.isEmpty()) {- Column(- modifier = Modifier.fillMaxSize().padding(padding).padding(32.dp),- horizontalAlignment = Alignment.CenterHorizontally,- verticalArrangement = Arrangement.Center,- ) {- Text("No saved measurements", style = MaterialTheme.typography.titleMedium)- Text(- "Measure something in AR and tap save",- style = MaterialTheme.typography.bodyMedium,- color = MaterialTheme.colorScheme.onSurfaceVariant,- )- }- } else {- LazyColumn(modifier = Modifier.fillMaxSize().padding(padding)) {- items(state.measurements, key = { it.id }) { m ->- SettingsRow(- title = m.label,- supportingText = formatMeasurement(m, state.unitSystem),- trailingContent = {- IconButton(onClick = { actions.delete(m.id) }) { IconDelete() }- },- )- }- }- }- }-}--private fun formatMeasurement(m: SavedMeasurement, system: UnitSystem): String = when (m.kind) {- MeasurementKind.Area -> Units.formatArea(m.value, system)- MeasurementKind.Angle -> Units.formatAngle(m.value)- else -> Units.formatLength(m.value, system)-}
measure/src/main/java/com/vayunmathur/measure/ui/SettingsContent.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/ui/SettingsContent.kt b/measure/src/main/java/com/vayunmathur/measure/ui/SettingsContent.ktnew file mode 100644index 0000000000..d934ff9ef2--- /dev/null+++ b/measure/src/main/java/com/vayunmathur/measure/ui/SettingsContent.kt@@ -0,0 +1,103 @@+package com.vayunmathur.measure.ui++import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.SettingsDivider+import com.vayunmathur.library.ui.SettingsRow+import com.vayunmathur.library.ui.SettingsSection+import com.vayunmathur.library.ui.SettingsSwitchRow+import com.vayunmathur.library.ui.Text+import com.vayunmathur.measure.data.model.UnitSystem+import com.vayunmathur.measure.platform.SettingsActions+import com.vayunmathur.measure.platform.SettingsUiState++@Composable+fun SettingsContent(+ state: SettingsUiState,+ actions: SettingsActions,+ onBack: () -> Unit = {},+ onOpenDiagnostics: () -> Unit = {},+ onOpenSaved: () -> Unit = {},+) {+ AppScaffold(title = "Settings", onNavigateBack = onBack) { padding ->+ Column(+ // The list is taller than the dialog on most phones; without this the+ // advanced section at the bottom is simply unreachable.+ modifier = Modifier.fillMaxSize().padding(padding).verticalScroll(rememberScrollState()),+ ) {+ SettingsSection(title = "Units") {+ SettingsSwitchRow(+ title = "Imperial units",+ supportingText = "Feet and inches instead of metres",+ checked = state.unitSystem == UnitSystem.Imperial,+ onCheckedChange = {+ actions.setUnitSystem(if (it) UnitSystem.Imperial else UnitSystem.Metric)+ },+ )+ SettingsSwitchRow(+ title = "Fractional inches",+ supportingText = "Show 3/16\" rather than 0.19\"",+ checked = state.useFractionalInches,+ enabled = state.unitSystem == UnitSystem.Imperial,+ onCheckedChange = actions::setUseFractionalInches,+ )+ }+ SettingsDivider()+ SettingsSection(title = "Compass") {+ SettingsSwitchRow(+ title = "Use true north",+ supportingText = "Corrects for magnetic declination at your location",+ checked = state.useTrueNorth,+ onCheckedChange = actions::setUseTrueNorth,+ )+ }+ SettingsDivider()+ SettingsSection(title = "Calibration") {+ SettingsRow(+ title = "Level",+ supportingText = if (state.levelCalibrated) {+ "Zeroed against a reference surface"+ } else {+ "Using raw gravity reading"+ },+ enabled = state.levelCalibrated,+ onClick = actions::clearLevelCalibration,+ trailingContent = { if (state.levelCalibrated) Text("Clear") },+ )+ }+ SettingsDivider()+ SettingsSection(title = "General") {+ SettingsSwitchRow(+ title = "Haptic feedback",+ checked = state.hapticsEnabled,+ onCheckedChange = actions::setHapticsEnabled,+ )+ SettingsSwitchRow(+ title = "Keep screen on",+ supportingText = "While a measuring tool is open",+ checked = state.keepScreenOn,+ onCheckedChange = actions::setKeepScreenOn,+ )+ SettingsRow(title = "Saved measurements", onClick = onOpenSaved)+ }+ SettingsDivider()+ SettingsSection(title = "Advanced") {+ SettingsSwitchRow(+ title = "Tracking diagnostics",+ supportingText = "Feature counts, IMU rate and clock skew",+ checked = state.showDiagnostics,+ onCheckedChange = actions::setShowDiagnostics,+ )+ if (state.showDiagnostics) {+ SettingsRow(title = "Open diagnostics", onClick = onOpenDiagnostics)+ }+ }+ }+ }+}
measure/src/main/java/com/vayunmathur/measure/ui/SettingsPage.kt
diff --git a/measure/src/main/java/com/vayunmathur/measure/ui/SettingsPage.kt b/measure/src/main/java/com/vayunmathur/measure/ui/SettingsPage.ktindex 05deb83774..bf7883eee9 100644--- a/measure/src/main/java/com/vayunmathur/measure/ui/SettingsPage.kt+++ b/measure/src/main/java/com/vayunmathur/measure/ui/SettingsPage.kt@@ -1,26 +1,11 @@ package com.vayunmathur.measure.ui -import androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.foundation.layout.padding-import androidx.compose.foundation.rememberScrollState-import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue-import androidx.compose.ui.Modifier-import com.vayunmathur.library.ui.AppScaffold-import com.vayunmathur.library.ui.SettingsDivider-import com.vayunmathur.library.ui.SettingsRow-import com.vayunmathur.library.ui.SettingsSection-import com.vayunmathur.library.ui.SettingsSwitchRow-import com.vayunmathur.library.ui.Text import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.measure.Route-import com.vayunmathur.measure.data.model.UnitSystem import com.vayunmathur.measure.platform.MeasureViewModel-import com.vayunmathur.measure.platform.SettingsActions-import com.vayunmathur.measure.platform.SettingsUiState @Composable fun SettingsPage(backStack: NavBackStack<Route>, viewModel: MeasureViewModel) {@@ -33,89 +18,3 @@ fun SettingsPage(backStack: NavBackStack<Route>, viewModel: MeasureViewModel) { onOpenSaved = { backStack.add(Route.Saved) }, ) }--@Composable-fun SettingsContent(- state: SettingsUiState,- actions: SettingsActions,- onBack: () -> Unit = {},- onOpenDiagnostics: () -> Unit = {},- onOpenSaved: () -> Unit = {},-) {- AppScaffold(title = "Settings", onNavigateBack = onBack) { padding ->- Column(- // The list is taller than the dialog on most phones; without this the- // advanced section at the bottom is simply unreachable.- modifier = Modifier.fillMaxSize().padding(padding).verticalScroll(rememberScrollState()),- ) {- SettingsSection(title = "Units") {- SettingsSwitchRow(- title = "Imperial units",- supportingText = "Feet and inches instead of metres",- checked = state.unitSystem == UnitSystem.Imperial,- onCheckedChange = {- actions.setUnitSystem(if (it) UnitSystem.Imperial else UnitSystem.Metric)- },- )- SettingsSwitchRow(- title = "Fractional inches",- supportingText = "Show 3/16\" rather than 0.19\"",- checked = state.useFractionalInches,- enabled = state.unitSystem == UnitSystem.Imperial,- onCheckedChange = actions::setUseFractionalInches,- )- }- SettingsDivider()- SettingsSection(title = "Compass") {- SettingsSwitchRow(- title = "Use true north",- supportingText = "Corrects for magnetic declination at your location",- checked = state.useTrueNorth,- onCheckedChange = actions::setUseTrueNorth,- )- }- SettingsDivider()- SettingsSection(title = "Calibration") {- SettingsRow(- title = "Level",- supportingText = if (state.levelCalibrated) {- "Zeroed against a reference surface"- } else {- "Using raw gravity reading"- },- enabled = state.levelCalibrated,- onClick = actions::clearLevelCalibration,- trailingContent = { if (state.levelCalibrated) Text("Clear") },- )- }- SettingsDivider()- SettingsSection(title = "General") {- SettingsSwitchRow(- title = "Haptic feedback",- checked = state.hapticsEnabled,- onCheckedChange = actions::setHapticsEnabled,- )- SettingsSwitchRow(- title = "Keep screen on",- supportingText = "While a measuring tool is open",- checked = state.keepScreenOn,- onCheckedChange = actions::setKeepScreenOn,- )- SettingsRow(title = "Saved measurements", onClick = onOpenSaved)- }- SettingsDivider()- SettingsSection(title = "Advanced") {- SettingsSwitchRow(- title = "Tracking diagnostics",- supportingText = "Feature counts, IMU rate and clock skew",- checked = state.showDiagnostics,- onCheckedChange = actions::setShowDiagnostics,- )- if (state.showDiagnostics) {- SettingsRow(title = "Open diagnostics", onClick = onOpenDiagnostics)- }- }- }- }-}-