Cotton code
428 lines · 27.7 KB · KotlinRaw
@file:OptIn(    androidx.compose.foundation.ExperimentalFoundationApi::class,    androidx.compose.material3.ExperimentalMaterial3Api::class,)package com.cottondb.android.ui.homeimport androidx.compose.foundation.Canvasimport androidx.compose.foundation.Imageimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.combinedClickableimport androidx.compose.foundation.layout.*import androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.foundation.lazy.LazyColumnimport androidx.compose.material3.HorizontalDividerimport androidx.compose.material3.Textimport androidx.compose.material3.pulltorefresh.PullToRefreshBoximport androidx.compose.runtime.*import androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.alphaimport androidx.compose.ui.graphics.graphicsLayerimport androidx.compose.ui.draw.shadowimport androidx.compose.ui.geometry.Offsetimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.graphics.Pathimport androidx.compose.ui.graphics.StrokeCapimport androidx.compose.ui.graphics.drawscope.Strokeimport androidx.compose.ui.layout.ContentScaleimport androidx.compose.ui.res.painterResourceimport androidx.compose.ui.semantics.Roleimport androidx.compose.ui.semantics.contentDescriptionimport androidx.compose.ui.semantics.semanticsimport androidx.compose.ui.text.font.FontWeightimport androidx.compose.ui.text.style.TextAlignimport androidx.compose.ui.text.style.TextOverflowimport androidx.compose.ui.unit.dpimport androidx.compose.ui.unit.spimport com.cottondb.android.Rimport com.cottondb.android.design.CottonFontsimport com.cottondb.android.design.CottonMetricsimport com.cottondb.android.design.CottonTextStylesimport com.cottondb.android.generated.CottonPaletteimport com.cottondb.android.home.*import java.time.Clockimport java.time.Durationimport java.time.Instantimport java.time.LocalDateimport java.time.format.DateTimeFormatterimport java.util.Locale/** * Cotton's launcher: Asked of you as slips, Done for you as receipts with an Undo, a board of * project caps and real tool objects. */@Composablefun HomeScreen(    state: HomeState,    onRefresh: () -> Unit,    onNavigate: (String) -> Unit,    onSaveArrangement: (HomeArrangement) -> Unit,    clock: Clock,    onUndo: (HomeDone) -> Unit = {},) {    val home = when (state) {        HomeState.Loading -> null        is HomeState.Data -> state.home        is HomeState.Error -> state.last    }    var arranging by remember { mutableStateOf(false) }    var draft by remember(home?.arrangement, home?.projects, home?.tools) {        mutableStateOf(home?.let(::ArrangementDraft))    }    var fanOpen by remember { mutableStateOf(false) }    var fanDestination by remember { mutableStateOf<String?>(null) }    LaunchedEffect(fanOpen, fanDestination) {        if (!fanOpen) fanDestination?.let { destination ->            fanDestination = null            onNavigate(destination)        }    }    val today = LocalDate.now(clock)    Box(Modifier.fillMaxSize().background(CottonPalette.groundMuted)) {        Image(painterResource(R.drawable.home_plaster), null, Modifier.fillMaxSize().alpha(.18f), contentScale = ContentScale.Crop)        Column(Modifier.fillMaxSize().safeContentPadding()) {            PullToRefreshBox(                isRefreshing = (state as? HomeState.Data)?.refreshing == true,                onRefresh = onRefresh,                modifier = Modifier.weight(1f),            ) {            LazyColumn(                Modifier.fillMaxSize(),                contentPadding = PaddingValues(CottonMetrics.settingsMargin, 8.dp, CottonMetrics.settingsMargin, CottonMetrics.footerGap),            ) {                item { HomeTitle(arranging) { fanOpen = true } }                when {                    home != null -> {                        if (state is HomeState.Error) item { HomeError(state.message, onRefresh) }                        item {                            HomeBody(home, draft ?: ArrangementDraft(home), arranging,                                onBeginArrange = { draft = ArrangementDraft(home); arranging = true },                                onChangeDraft = { draft = it }, onNavigate = onNavigate, clock = clock, today = today,                                receipt = (state as? HomeState.Data)?.receipt, onUndo = onUndo)                        }                    }                    state is HomeState.Error -> item { HomeError(state.message, onRefresh) }                    else -> item { Text("Loading your database…", Modifier.padding(top = 24.dp), style = CottonTextStyles.body, color = CottonPalette.inkSecondary) }                }            }            }            HomeFooter(arranging, { onNavigate("/search") }, onNavigate) {                draft?.takeIf { it.changed }?.let { onSaveArrangement(it.record) }                arranging = false            }        }        if (fanOpen) HomeAddFan(            today = today.toString(),            onDismiss = { fanOpen = false },            onChoose = { destination -> fanDestination = destination; fanOpen = false },        )    }}@Composable private fun HomeTitle(arranging: Boolean, onNew: () -> Unit) = Row(    Modifier.fillMaxWidth().padding(top = 8.dp, bottom = 12.dp), verticalAlignment = Alignment.CenterVertically,) {    Text("Cotton", Modifier.weight(1f), style = CottonTextStyles.pageTitle.copy(fontFamily = CottonFonts.display), color = CottonPalette.ink)    if (!arranging) RoundControl("New", onNew) { PlusMark(CottonPalette.ink) }}@Composable private fun HomeBody(    home: HomeRead, draft: ArrangementDraft, arranging: Boolean, onBeginArrange: () -> Unit,    onChangeDraft: (ArrangementDraft) -> Unit, onNavigate: (String) -> Unit, clock: Clock, today: LocalDate,    receipt: HomeReceipt?, onUndo: (HomeDone) -> Unit,) = Column(verticalArrangement = Arrangement.spacedBy(30.dp)) {    if (home.workingOn.count > 0) WorkingOnLine(home.workingOn, onNavigate, clock)    if (home.asked.isNotEmpty()) AskedBand(home.asked, onNavigate)    if (home.done.isNotEmpty() || receipt != null) DoneBand(home.done, receipt, onNavigate, onUndo, clock)    ProjectsBoard(draft.projects(home.projects), arranging, onBeginArrange,        { slug, delta -> onChangeDraft(draft.moveProject(slug, delta)) }, { onNavigate("/projects/$it") }, { onNavigate("/projects") })    ToolDirectory(draft.tools(home.tools), draft.hidden, arranging, onBeginArrange,        { key, delta -> onChangeDraft(draft.moveTool(key, delta)) },        { key -> onChangeDraft(draft.putAway(key)) }, { key -> onChangeDraft(draft.bringBack(key)) }, onNavigate, today)    SettingsRow { onNavigate("/device") }    home.syncLine?.let { Text(it, Modifier.padding(bottom = 12.dp), style = CottonTextStyles.caption, color = CottonPalette.statusWarning) }}/** Asked of you: one slip per question only the owner can answer, normally under five. */@Composable private fun AskedBand(asked: List<HomeAsked>, onNavigate: (String) -> Unit) = Column(verticalArrangement = Arrangement.spacedBy(14.dp)) {    SectionTitle("Asked of you")    asked.chunked(3).forEach { row ->        Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(10.dp)) {            row.forEach { item -> AskedSlip(item, Modifier.weight(1f)) { onNavigate(item.path) } }            repeat(3 - row.size) { Spacer(Modifier.weight(1f)) }        }    }}/** * Done for you: what Cotton filed, remembered and could not read, newest first. Receipts, never a * count. Each row opens its record; an undo row also carries an Undo. */@Composable private fun DoneBand(    done: List<HomeDone>, receipt: HomeReceipt?, onNavigate: (String) -> Unit, onUndo: (HomeDone) -> Unit, clock: Clock,) = Column {    if (done.isNotEmpty()) SectionTitle("Done for you")    receipt?.let {        Text(it.message, Modifier.padding(top = 6.dp),            style = CottonTextStyles.preview.copy(fontFamily = CottonFonts.hand),            color = if (it.failed) CottonPalette.statusError else CottonPalette.statusSuccess)    }    Spacer(Modifier.height(8.dp))    done.forEach { item -> DoneRow(item, clock, { onNavigate(item.path) }, { onUndo(item) }) }}@Composable private fun DoneRow(item: HomeDone, clock: Clock, onOpen: () -> Unit, onUndo: () -> Unit) = Column(Modifier.fillMaxWidth()) {    HorizontalDivider(color = CottonPalette.hairline, thickness = CottonMetrics.hairline)    Row(Modifier.fillMaxWidth().padding(vertical = 10.dp, horizontal = 2.dp), verticalAlignment = Alignment.CenterVertically) {        Column(Modifier.weight(1f).combinedClickable(role = Role.Button, onClick = onOpen)) {            val meta = listOfNotNull(item.label, relativeAge(item.at, clock)).joinToString(" · ")            Text(meta, style = CottonTextStyles.caption, color = CottonPalette.inkSecondary, maxLines = 1, overflow = TextOverflow.Ellipsis)            if (item.text.isNotBlank()) {                Text(item.text, Modifier.padding(top = 2.dp), style = CottonTextStyles.body.copy(fontFamily = CottonFonts.type),                    color = CottonPalette.ink, maxLines = 2, overflow = TextOverflow.Ellipsis)            }        }        if (item.canUndo) {            Text("Undo", Modifier.padding(start = 12.dp).combinedClickable(role = Role.Button, onClick = onUndo).padding(8.dp),                style = CottonTextStyles.body.copy(fontFamily = CottonFonts.type), color = CottonPalette.ink)        }    }}@Composable private fun WorkingOnLine(workingOn: HomeWorkingOn, onNavigate: (String) -> Unit, clock: Clock) {    val count = if (workingOn.count == 1) "Working on 1" else "Working on ${workingOn.count}"    val line = listOfNotNull(count, workingOn.oldestTask, relativeAge(workingOn.oldestQueuedAt, clock)).joinToString(" · ")    Row(        Modifier.fillMaxWidth().combinedClickable(role = Role.Button, onClick = { onNavigate("/activity") }),        verticalAlignment = Alignment.CenterVertically,    ) {        Text(line, Modifier.weight(1f), style = CottonTextStyles.preview.copy(fontFamily = CottonFonts.hand), color = CottonPalette.inkBody, maxLines = 1, overflow = TextOverflow.Ellipsis)        ChevronMark(CottonPalette.inkSecondary, false)    }}@Composable private fun AskedSlip(item: HomeAsked, modifier: Modifier, onClick: () -> Unit) = Box(    modifier.height(94.dp).shadow(3.dp, RoundedCornerShape(CottonMetrics.cardRadius)).background(CottonPalette.groundElevated, RoundedCornerShape(CottonMetrics.cardRadius))        .combinedClickable(role = Role.Button, onClick = onClick), contentAlignment = Alignment.CenterStart,) {    Text(item.label, Modifier.padding(12.dp), style = CottonTextStyles.preview.copy(fontFamily = CottonFonts.type), color = CottonPalette.inkBody, maxLines = 4, overflow = TextOverflow.Ellipsis)}@Composable private fun ProjectsBoard(    projects: List<HomeProject>, arranging: Boolean, onBeginArrange: () -> Unit, onMove: (String, Int) -> Unit,    onOpen: (String) -> Unit, onNewProject: () -> Unit,) = Column(verticalArrangement = Arrangement.spacedBy(14.dp)) {    SectionTitle("Projects")    val cells = projects.map { ProjectCell.Project(it) } + List(emptyCapCount(projects.size)) { ProjectCell.New }    cells.chunked(4).forEach { row ->        Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {            row.forEach { cell -> when (cell) {                is ProjectCell.Project -> ProjectCap(cell.value, arranging, Modifier.weight(1f), onBeginArrange, onMove, onOpen)                ProjectCell.New -> EmptyCap(Modifier.weight(1f), onNewProject)            } }            repeat(4 - row.size) { Spacer(Modifier.weight(1f)) }        }    }}private sealed interface ProjectCell { data class Project(val value: HomeProject) : ProjectCell; data object New : ProjectCell }@Composable private fun ProjectCap(    project: HomeProject, arranging: Boolean, modifier: Modifier, onLongPress: () -> Unit,    onMove: (String, Int) -> Unit, onOpen: (String) -> Unit,) = Box(    modifier.aspectRatio(1f).combinedClickable(role = Role.Button, onClick = { if (!arranging) onOpen(project.slug) }, onLongClick = onLongPress)        .semantics { contentDescription = if (arranging) "Arrange ${project.name}" else "Open ${project.name}" }, contentAlignment = Alignment.Center,) {    Image(painterResource(capResource(project.colour.wireName)), null, Modifier.fillMaxSize(), contentScale = ContentScale.Fit)    Text(project.name, Modifier.width(58.dp), style = CottonTextStyles.preview.copy(fontFamily = CottonFonts.cap, fontWeight = FontWeight.Normal),        color = if (isLightCap(project.colour.wireName)) CottonPalette.ink else CottonPalette.ground, textAlign = TextAlign.Center, maxLines = 3, overflow = TextOverflow.Ellipsis)    if (arranging) ArrangeControls(project.slug, onMove, null)}@Composable private fun EmptyCap(modifier: Modifier, onClick: () -> Unit) = Box(    modifier.aspectRatio(1f).combinedClickable(role = Role.Button, onClick = onClick), contentAlignment = Alignment.Center,) { Image(painterResource(R.drawable.cap_empty), null, Modifier.fillMaxSize(), contentScale = ContentScale.Fit); PlusMark(CottonPalette.inkTertiary) }@Composable private fun ToolDirectory(    tools: List<HomeTool>, hidden: Set<String>, arranging: Boolean, onBeginArrange: () -> Unit,    onMove: (String, Int) -> Unit, onPutAway: (String) -> Unit, onBringBack: (String) -> Unit, onNavigate: (String) -> Unit,    today: LocalDate,) = Column(verticalArrangement = Arrangement.spacedBy(14.dp)) {    SectionTitle("Your data")    tools.filterNot { it.key in hidden }.chunked(4).forEach { row ->        Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {            row.forEach { tool -> ToolObject(tool, arranging, Modifier.weight(1f), onBeginArrange, onMove, onPutAway, onNavigate, today) }            repeat(4 - row.size) { Spacer(Modifier.weight(1f)) }        }    }    if (arranging && hidden.isNotEmpty()) {        Text("Put away", style = CottonTextStyles.caption, color = CottonPalette.inkSecondary)        tools.filter { it.key in hidden }.forEach { tool ->            Row(Modifier.fillMaxWidth().background(CottonPalette.chipGround, RoundedCornerShape(CottonMetrics.cardRadius)).padding(8.dp), verticalAlignment = Alignment.CenterVertically) {                Text(tool.name, Modifier.weight(1f), style = CottonTextStyles.preview.copy(fontFamily = CottonFonts.type), color = CottonPalette.inkSecondary)                Text("Bring back", Modifier.combinedClickable(role = Role.Button, onClick = { onBringBack(tool.key) }).padding(8.dp), style = CottonTextStyles.caption, color = CottonPalette.accent)            }        }    }}@Composable private fun ToolObject(    tool: HomeTool, arranging: Boolean, modifier: Modifier, onLongPress: () -> Unit,    onMove: (String, Int) -> Unit, onPutAway: (String) -> Unit, onNavigate: (String) -> Unit, today: LocalDate,) = BoxWithConstraints(    modifier.aspectRatio(1f).combinedClickable(role = Role.Button, onClick = { if (!arranging) onNavigate(tool.path) }, onLongClick = onLongPress)        .semantics { contentDescription = if (arranging) "Arrange ${tool.name}" else "Open ${tool.name}" }, contentAlignment = Alignment.Center,) {    Image(painterResource(toolResource(tool.key)), null, Modifier.fillMaxSize(), contentScale = ContentScale.Fit)    if (tool.key == "calendar") CalendarPrint(today, maxWidth)    toolPrint(tool.key)?.let { print ->        val side = maxWidth        Text(            text = if (print.uppercase) tool.name.uppercase() else tool.name,            modifier = Modifier                .width(side * print.width)                .offset(x = side * (print.centerX - .5f), y = side * (print.centerY - .5f))                .graphicsLayer(rotationZ = print.rotation),            style = CottonTextStyles.caption.copy(fontFamily = print.face, fontSize = (side.value * print.height * .8f).sp),            color = if (print.creamInk) CottonPalette.ground else CottonPalette.ink,            textAlign = TextAlign.Center,            maxLines = print.lines,            overflow = TextOverflow.Ellipsis,        )    }    if (arranging) ArrangeControls(tool.key, onMove, onPutAway)}/** Matches the month and day printed on CottonUI's calendar object. */@Composable private fun CalendarPrint(today: LocalDate, side: androidx.compose.ui.unit.Dp) = Box(    Modifier.fillMaxSize(), contentAlignment = Alignment.Center,) {    Text(        today.format(DateTimeFormatter.ofPattern("MMM", Locale.US)).uppercase(Locale.US),        Modifier.width(side * .40f).offset(x = side * 0f, y = side * -.14f),        style = CottonTextStyles.caption.copy(fontFamily = CottonFonts.type, fontSize = (side.value * .068f).sp),        color = CottonPalette.ink,        textAlign = TextAlign.Center,    )    Text(        today.dayOfMonth.toString(),        Modifier.width(side * .50f).offset(x = side * 0f, y = side * .10f),        style = CottonTextStyles.screenTitle.copy(fontFamily = CottonFonts.display, fontSize = (side.value * .224f).sp),        color = CottonPalette.ink,        textAlign = TextAlign.Center,    )}private fun relativeAge(queuedAt: String?, clock: Clock): String? {    val instant = queuedAt?.let { runCatching { Instant.parse(it) }.getOrNull() } ?: return null    val elapsed = Duration.between(instant, clock.instant()).coerceAtLeast(Duration.ZERO)    val minutes = elapsed.toMinutes()    return when {        minutes < 1 -> "just now"        minutes < 60 -> "${minutes}m ago"        minutes < 24 * 60 -> "${minutes / 60}h ago"        minutes < 7 * 24 * 60 -> "${minutes / (24 * 60)}d ago"        else -> instant.atZone(clock.zone).format(DateTimeFormatter.ofPattern("d MMM", Locale.US))    }}@Composable private fun ArrangeControls(key: String, onMove: (String, Int) -> Unit, onPutAway: ((String) -> Unit)?) = Row(    Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween,) {    RoundControl("Move earlier", { onMove(key, -1) }) { ChevronMark(CottonPalette.ink, true) }    if (onPutAway != null) RoundControl("Put away", { onPutAway(key) }) { CloseMark(CottonPalette.statusError) }    RoundControl("Move later", { onMove(key, 1) }) { ChevronMark(CottonPalette.ink, false) }}@Composable private fun SettingsRow(onClick: () -> Unit) = Column(Modifier.fillMaxWidth().combinedClickable(role = Role.Button, onClick = onClick)) {    HorizontalDivider(color = CottonPalette.hairline, thickness = CottonMetrics.hairline)    Row(Modifier.fillMaxWidth().padding(vertical = 16.dp, horizontal = 2.dp), verticalAlignment = Alignment.CenterVertically) {        Text("Settings", Modifier.weight(1f), style = CottonTextStyles.body.copy(fontFamily = CottonFonts.type), color = CottonPalette.ink); ChevronMark(CottonPalette.inkSecondary, false)    }}@Composable private fun HomeFooter(arranging: Boolean, onSearch: () -> Unit, onNewThought: (String) -> Unit, onDone: () -> Unit) = Row(    Modifier.fillMaxWidth().background(CottonPalette.groundMuted).padding(horizontal = CottonMetrics.settingsMargin, vertical = 8.dp),    horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.CenterVertically,) {    Text("Search", Modifier.weight(1f).height(CottonMetrics.footerSearchHeight).background(CottonPalette.groundElevated, RoundedCornerShape(CottonMetrics.footerSearchHeight / 2))        .combinedClickable(role = Role.Button, onClick = onSearch).padding(horizontal = 20.dp, vertical = 17.dp), style = CottonTextStyles.preview, color = CottonPalette.inkSecondary)    Row(        Modifier.height(CottonMetrics.footerSearchHeight).background(CottonPalette.ink, RoundedCornerShape(CottonMetrics.footerSearchHeight / 2))            .combinedClickable(                role = Role.Button,                onClick = { if (arranging) onDone() else onNewThought("/capture?start=listening") },                onLongClick = if (arranging) null else { { onNewThought("/capture?start=typing") } },            ).semantics { contentDescription = if (arranging) "Done arranging" else "New thought. Long press to type instead." }                .padding(horizontal = 20.dp, vertical = 17.dp),        verticalAlignment = Alignment.CenterVertically,        horizontalArrangement = Arrangement.spacedBy(10.dp),    ) {        if (!arranging) MicrophoneMark(CottonPalette.ground)        Text(if (arranging) "Done" else "New thought", style = CottonTextStyles.preview.copy(fontFamily = CottonFonts.type), color = CottonPalette.ground)    }}@Composable private fun HomeError(message: String, onRefresh: () -> Unit) = Column(Modifier.padding(top = 16.dp, bottom = 8.dp)) {    Text("Home could not be read", style = CottonTextStyles.screenTitle, color = CottonPalette.ink)    Text(message, Modifier.padding(top = 6.dp), style = CottonTextStyles.body, color = CottonPalette.inkBody)    Text("Try again", Modifier.combinedClickable(role = Role.Button, onClick = onRefresh).padding(top = 12.dp), style = CottonTextStyles.preview, color = CottonPalette.accent)}@Composable private fun SectionTitle(text: String) = Text(text, style = CottonTextStyles.sectionLabel, color = CottonPalette.inkSecondary)@Composable private fun RoundControl(label: String, onClick: () -> Unit, mark: @Composable () -> Unit) = Box(    Modifier.size(CottonMetrics.navCircleTarget).combinedClickable(role = Role.Button, onClick = onClick).semantics { contentDescription = label }, contentAlignment = Alignment.Center,) { Box(Modifier.size(CottonMetrics.navCircleDiameter).background(CottonPalette.groundElevated, RoundedCornerShape(CottonMetrics.navCircleDiameter / 2)), contentAlignment = Alignment.Center) { mark() } }@Composable private fun PlusMark(color: Color) = Canvas(Modifier.size(18.dp)) { drawLine(color, Offset(size.width / 2, 2.dp.toPx()), Offset(size.width / 2, size.height - 2.dp.toPx()), 1.7.dp.toPx(), StrokeCap.Round); drawLine(color, Offset(2.dp.toPx(), size.height / 2), Offset(size.width - 2.dp.toPx(), size.height / 2), 1.7.dp.toPx(), StrokeCap.Round) }@Composable private fun MicrophoneMark(color: Color) = Canvas(Modifier.size(16.dp)) { val stroke = 1.5.dp.toPx(); drawRoundRect(color, Offset(size.width * .34f, size.height * .08f), androidx.compose.ui.geometry.Size(size.width * .32f, size.height * .48f), androidx.compose.ui.geometry.CornerRadius(size.width * .16f), style = Stroke(stroke)); drawArc(color, 0f, 180f, false, Offset(size.width * .20f, size.height * .30f), androidx.compose.ui.geometry.Size(size.width * .60f, size.height * .50f), style = Stroke(stroke)); drawLine(color, Offset(size.width * .50f, size.height * .80f), Offset(size.width * .50f, size.height), stroke, StrokeCap.Round) }@Composable private fun ChevronMark(color: Color, left: Boolean) = Canvas(Modifier.size(16.dp)) { val x = if (left) .65f else .35f; val other = if (left) .35f else .65f; val p = Path().apply { moveTo(size.width * x, size.height * .2f); lineTo(size.width * other, size.height * .5f); lineTo(size.width * x, size.height * .8f) }; drawPath(p, color, style = Stroke(1.6.dp.toPx(), cap = StrokeCap.Round)) }@Composable private fun CloseMark(color: Color) = Canvas(Modifier.size(15.dp)) { drawLine(color, Offset(3.dp.toPx(), 3.dp.toPx()), Offset(size.width - 3.dp.toPx(), size.height - 3.dp.toPx()), 1.5.dp.toPx(), StrokeCap.Round); drawLine(color, Offset(size.width - 3.dp.toPx(), 3.dp.toPx()), Offset(3.dp.toPx(), size.height - 3.dp.toPx()), 1.5.dp.toPx(), StrokeCap.Round) }private data class ArrangementDraft(val projectSlugs: List<String>, val toolKeys: List<String>, val hidden: Set<String>, val initial: HomeArrangement) {    constructor(home: HomeRead) : this(home.arrangement.projectSlugs, home.arrangement.toolKeys, home.arrangement.hiddenToolKeys.toSet(), home.arrangement)    val changed get() = record != initial    val record get() = HomeArrangement(projectSlugs, toolKeys, toolKeys.filter(hidden::contains))    fun projects(all: List<HomeProject>) = projectSlugs.mapNotNull { slug -> all.firstOrNull { it.slug == slug } } + all.filterNot { it.slug in projectSlugs }    fun tools(all: List<HomeTool>) = toolKeys.mapNotNull { key -> all.firstOrNull { it.key == key } } + all.filterNot { it.key in toolKeys }    fun moveProject(slug: String, delta: Int) = copy(projectSlugs = projectSlugs.move(slug, delta))    fun moveTool(key: String, delta: Int) = copy(toolKeys = toolKeys.move(key, delta))    fun putAway(key: String) = copy(hidden = hidden + key)    fun bringBack(key: String) = copy(hidden = hidden - key)}private fun List<String>.move(value: String, delta: Int): List<String> { val at = indexOf(value); val to = at + delta; if (at < 0 || to !in indices) return this; return toMutableList().apply { removeAt(at); add(to, value) } }private fun emptyCapCount(count: Int) = if (count == 0) 1 else (4 - count % 4) % 4private fun isLightCap(colour: String) = colour in setOf("cream", "yellow", "silver", "sky", "pink")private fun capResource(colour: String): Int = when (colour) { "cream" -> R.drawable.cap_cream; "red" -> R.drawable.cap_red; "navy" -> R.drawable.cap_navy; "yellow" -> R.drawable.cap_yellow; "green" -> R.drawable.cap_green; "silver" -> R.drawable.cap_silver; "orange" -> R.drawable.cap_orange; "burgundy" -> R.drawable.cap_burgundy; "sky" -> R.drawable.cap_sky; "pink" -> R.drawable.cap_pink; "black" -> R.drawable.cap_black; "teal" -> R.drawable.cap_teal; else -> error("Unknown canonical cap colour: $colour") }private fun toolResource(key: String): Int = when (key) { "todos" -> R.drawable.tool_todos; "calendar" -> R.drawable.tool_calendar; "notes" -> R.drawable.tool_notes; "journal" -> R.drawable.tool_journal; "goals" -> R.drawable.tool_goals; "mood" -> R.drawable.tool_mood; "messages" -> R.drawable.tool_messages; "email" -> R.drawable.tool_email; "calls" -> R.drawable.tool_calls; "people" -> R.drawable.tool_people; "locations" -> R.drawable.tool_locations; "news" -> R.drawable.tool_news; "reader" -> R.drawable.tool_reader; "alarms" -> R.drawable.tool_alarms; "accounts" -> R.drawable.tool_money; "meetings" -> R.drawable.tool_meetings; "documents" -> R.drawable.tool_documents; "photos" -> R.drawable.tool_photos; "videos" -> R.drawable.tool_videos; "passwords" -> R.drawable.tool_passwords; "code" -> R.drawable.tool_code; else -> error("Home has no canonical object for $key") }/** Exact normalized print placements from CottonUI's `ToolPrint.table`. */private data class ToolPrintSpec(    val centerX: Float, val centerY: Float, val width: Float, val height: Float,    val rotation: Float = 0f, val face: androidx.compose.ui.text.font.FontFamily = CottonFonts.type,    val creamInk: Boolean = false, val uppercase: Boolean = false, val lines: Int = 1,)private fun toolPrint(key: String): ToolPrintSpec? = when (key) {    "todos" -> ToolPrintSpec(.50f, .380f, .54f, .120f)    // The date is printed by CalendarPrint from HomeScreen's injected clock.    "calendar" -> null    "notes" -> ToolPrintSpec(.50f, .480f, .62f, .160f, -3f, CottonFonts.hand)    "journal" -> ToolPrintSpec(.50f, .500f, .50f, .110f, face = CottonFonts.cap, creamInk = true, uppercase = true)    "mood" -> ToolPrintSpec(.50f, .770f, .44f, .100f)    "messages" -> ToolPrintSpec(.50f, .700f, .58f, .120f, -3f, CottonFonts.hand)    "email" -> ToolPrintSpec(.50f, .560f, .52f, .110f)    "people" -> ToolPrintSpec(.50f, .575f, .34f, .090f)    "news" -> ToolPrintSpec(.50f, .290f, .70f, .140f, face = CottonFonts.display)    "reader" -> ToolPrintSpec(.50f, .600f, .52f, .120f, face = CottonFonts.display)    "alarms" -> ToolPrintSpec(.50f, .700f, .36f, .085f)    "accounts" -> ToolPrintSpec(.50f, .550f, .52f, .130f, face = CottonFonts.cap, creamInk = true)    "meetings" -> ToolPrintSpec(.50f, .335f, .48f, .080f)    "documents" -> ToolPrintSpec(.50f, .550f, .58f, .120f)    "photos" -> ToolPrintSpec(.50f, .840f, .44f, .090f, face = CottonFonts.hand)    "passwords" -> ToolPrintSpec(.645f, .565f, .25f, .085f, -28f)    "code" -> ToolPrintSpec(.50f, .600f, .46f, .110f)    // The remaining source objects are intentionally wordless.    "calls", "goals", "locations", "videos" -> null    else -> error("Home has no canonical print rule for $key")}