summaryrefslogtreecommitdiff
path: root/ui/src/commonMain/kotlin/coffee/liz/rookery/ui/TimerScreen.kt
blob: 926fe106f7a9c459fce1f6d7fa25c641f109fa2b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
package coffee.liz.rookery.ui

import androidx.compose.foundation.Canvas
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.gestures.waitForUpOrCancellation
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicText
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.withFrameMillis
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.semantics.LiveRegionMode
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.liveRegion
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coffee.liz.rookery.model.DNF
import coffee.liz.rookery.model.Event
import coffee.liz.rookery.model.Penalty
import coffee.liz.rookery.model.Puzzle
import coffee.liz.rookery.model.formatSolve
import coffee.liz.rookery.model.formatTime
import coffee.liz.rookery.puzzle.Puzzles
import coffee.liz.rookery.stats.Averages
import coffee.liz.rookery.stats.StatKind
import coffee.liz.rookery.timer.TimerMachine.State
import org.jetbrains.compose.resources.ExperimentalResourceApi
import org.jetbrains.compose.resources.decodeToSvgPainter

@Composable
fun TimerScreen(m: AppModel) {
    val ticking = m.timer !is State.Idle && m.timer !is State.Stopped
    LaunchedEffect(ticking) { while (ticking) withFrameMillis { m.frame() } }

    if (m.displayMode) { DisplayMode(m); return }
    Row(Modifier.fillMaxSize(), horizontalArrangement = Arrangement.spacedBy(10.dp)) {
        Column(Modifier.width(280.dp).fillMaxHeight(), verticalArrangement = Arrangement.spacedBy(10.dp)) {
            SessionBox(m)
            SolveTable(m, Modifier.weight(1f))
        }
        Column(Modifier.weight(1f).fillMaxHeight(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
            ScrambleBox(m)
            TimerDevice(m, Modifier.weight(1f).fillMaxWidth())
            Label(hint(m.timer, m.inspection, m.host.touchInput), Modifier.fillMaxWidth(), color = Rk.c.inkDim, style = Rk.t.label.copy(textAlign = TextAlign.Center))
            LastSolveLine(m)
        }
        Column(Modifier.width(280.dp).fillMaxHeight().verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(10.dp)) {
            StatsBox(m)
            PreviewBox(m)
            SelectedSolveBox(m)
        }
    }
}

@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun SessionBox(m: AppModel) {
    var choosing by remember { mutableStateOf(false) }
    GroupBox("sessions") {
        Column(Modifier.heightIn(max = 150.dp)) {
            LazyColumn {
                itemsIndexed(m.derived.sessions) { _, s ->
                    val sel = s.id == m.derived.session?.id
                    Row(
                        Modifier.fillMaxWidth().then(if (sel) Modifier.background(Rk.c.select) else Modifier)
                            .clickable { m.selectSession(s.id) }.padding(horizontal = 4.dp, vertical = 2.dp),
                    ) {
                        Label(s.name, Modifier.weight(1f), color = if (sel) Rk.c.selectInk else Rk.c.link, maxLines = 1)
                        Label(s.event.short, color = if (sel) Rk.c.selectInk else Rk.c.inkDim, style = Rk.t.label)
                    }
                }
            }
        }
        RetroButton(if (choosing) "never mind" else "new session", { choosing = !choosing })
        if (choosing) FlowRow {
            for (e in Event.entries) RetroButton(e.short, { m.createSession(e); choosing = false }, description = "new ${e.title} session", style = Rk.t.label)
        }
    }
}

@Composable
private fun SolveTable(m: AppModel, modifier: Modifier) {
    val solves = m.derived.sessionSolves
    val results = remember(solves) { solves.map { it.result } }
    val list = rememberLazyListState()
    LaunchedEffect(solves.size) { if (solves.isNotEmpty()) list.scrollToItem(0) }
    Table(modifier.fillMaxWidth()) {
        Row(Modifier.fillMaxWidth()) { HeaderCell("#", 0.7f); HeaderCell("time", 1.4f); HeaderCell("ao5", 1.3f); HeaderCell("ao12", 1.3f) }
        if (solves.isEmpty()) Label("no solves yet.", Modifier.padding(6.dp), color = Rk.c.inkDim)
        LazyColumn(state = list) {
            val n = solves.size
            itemsIndexed(solves.asReversed(), key = { _, s -> s.id }) { ri, s ->
                val i = n - 1 - ri
                val sel = s.id == m.selectedSolveId
                val ao5 = if (i >= 4) formatTime(Averages.average(results.subList(i - 4, i + 1)), true) else ""
                val ao12 = if (i >= 11) formatTime(Averages.average(results.subList(i - 11, i + 1)), true) else ""
                val ink = if (sel) Rk.c.selectInk else null
                Row(
                    Modifier.fillMaxWidth().then(if (sel) Modifier.background(Rk.c.select) else Modifier)
                        .clickable { m.selectedSolveId = if (sel) null else s.id }
                        .semantics(mergeDescendants = true) { contentDescription = "solve ${i + 1}, ${formatSolve(s)}" },
                ) {
                    Cell("${i + 1}", 0.7f, color = ink ?: Rk.c.inkDim)
                    Cell(if (s.penalty == Penalty.DNF) "DNF" else formatSolve(s), 1.4f, color = ink ?: if (s.penalty == Penalty.DNF) Rk.c.bad else null)
                    Cell(ao5, 1.3f, color = ink)
                    Cell(ao12, 1.3f, color = ink)
                }
            }
        }
    }
}

@Composable
private fun ScrambleBox(m: AppModel) {
    Table(Modifier.fillMaxWidth()) {
        Row(Modifier.fillMaxWidth().edge(Rk.c, sunk = true).padding(horizontal = 6.dp), verticalAlignment = Alignment.CenterVertically) {
            BasicText(m.event.title.lowercase(), Modifier.weight(1f), style = Rk.t.heading.copy(color = Rk.c.heading))
            RetroButton("next scramble", { m.newScramble() })
        }
        val size = when { m.scramble.length > 300 -> 13.sp; m.scramble.length > 120 -> 16.sp; else -> 22.sp }
        BasicText(
            m.scramble, Modifier.fillMaxWidth().edge(Rk.c, sunk = true).padding(10.dp).semantics { contentDescription = "scramble: ${m.scramble}" },
            style = Rk.t.mono.copy(fontSize = size, color = Rk.c.ink, textAlign = TextAlign.Center, lineHeight = size * 1.35f),
        )
    }
}

/** What the readout shows, in characters the seven-segment display knows. */
private fun readout(s: State, now: Long, last: String): String = when (s) {
    State.Idle -> last
    is State.Inspecting -> inspectionText(now - s.since)
    is State.Holding -> s.inspectingSince?.let { inspectionText(now - it) } ?: "0.00"
    is State.Ready -> "0.00"
    is State.Running -> formatTime(now - s.since)
    is State.Stopped -> when (s.penalty) {
        Penalty.DNF -> "dnF"
        Penalty.PLUS2 -> formatTime(s.ms + 2000) + "+"
        Penalty.NONE -> formatTime(s.ms)
    }
}

private fun inspectionText(elapsed: Long): String {
    val left = 15 - elapsed / 1000
    return if (left > 0) "$left" else if (elapsed <= 17_000) "+2" else "dnF"
}

private fun hint(s: State, inspection: Boolean, touch: Boolean): String {
    val key = if (touch) "the screen" else "space"
    return when (s) {
        State.Idle, is State.Stopped -> if (inspection) (if (touch) "tap to start inspection." else "space starts inspection.  f: big display.") else "hold $key until the green light, then let go."
        is State.Inspecting -> "hold $key until the green light."
        is State.Holding -> "keep holding."
        is State.Ready -> "let go."
        is State.Running -> if (touch) "tap anywhere to stop." else "any key stops.  esc throws it away."
    }
}

/**
 * The timer as an object on the desk: a dark plastic body, a grey-green liquid-crystal window that
 * fills whatever room it has, and the two lamps a mat has. Red is "hands down", green is "go".
 */
@Composable
fun TimerDevice(m: AppModel, modifier: Modifier = Modifier) {
    val s = m.timer
    val last = m.lastSolve()?.let { if (it.penalty == Penalty.DNF) "dnF" else formatTime(it.result) + if (it.penalty == Penalty.PLUS2) "+" else "" } ?: "0.00"
    val text = readout(s, m.now, last)
    val glass = Color(0xFFA9B7A1)
    val ink = Color(0xFF1A2316)
    Column(
        modifier.clip(RoundedCornerShape(18.dp)).background(Color(0xFF1B1D1C)).outline(Color(0xFF3A3D3B)).padding(14.dp)
            .then(if (!m.host.touchInput) Modifier else Modifier.pointerInput(Unit) {
                awaitEachGesture { awaitFirstDown(); m.press(); waitForUpOrCancellation(); m.release() }
            }),
    ) {
        Box(
            Modifier.weight(1f).fillMaxWidth().clip(RoundedCornerShape(6.dp)).background(glass).outline(Color(0xFF0C0D0C), 2.dp).padding(horizontal = 22.dp, vertical = 14.dp)
                .semantics { liveRegion = LiveRegionMode.Polite; contentDescription = "timer ${text.replace("dnF", "DNF")}" },
        ) {
            SevenSegment(text, ink, ink.copy(alpha = 0.06f), Modifier.fillMaxSize())
        }
        Row(Modifier.fillMaxWidth().padding(top = 10.dp), verticalAlignment = Alignment.CenterVertically) {
            Lamp(Color(0xFFFF4D4D), lit = s is State.Holding)
            Spacer(Modifier.width(8.dp))
            Lamp(Color(0xFF58E06F), lit = s is State.Ready || s is State.Running)
            Spacer(Modifier.weight(1f))
            BasicText("rookery", style = Rk.t.label.copy(color = Color(0xFF6A6F6C), letterSpacing = 3.sp))
        }
    }
}

@Composable
private fun Lamp(color: Color, lit: Boolean) {
    Canvas(Modifier.size(12.dp)) {
        if (lit) drawCircle(color.copy(alpha = 0.35f), radius = size.minDimension * 0.75f)
        drawCircle(if (lit) color else Color(color.red * 0.25f, color.green * 0.25f, color.blue * 0.25f), radius = size.minDimension / 2)
        drawCircle(Color.White.copy(alpha = if (lit) 0.6f else 0.12f), radius = size.minDimension * 0.14f, center = center.copy(x = center.x - size.width * 0.14f, y = center.y - size.height * 0.14f))
    }
}

@Composable
private fun LastSolveLine(m: AppModel) {
    val last = m.lastSolve() ?: return
    Row(verticalAlignment = Alignment.CenterVertically) {
        Label("that one was: ", color = Rk.c.inkDim)
        Tabs(listOf(Penalty.NONE, Penalty.PLUS2, Penalty.DNF), last.penalty, { when (it) { Penalty.NONE -> "fine"; Penalty.PLUS2 -> "+2"; Penalty.DNF -> "dnf" } }, { m.setPenalty(last.id, it) })
        Label("  ·  ", color = Rk.c.inkDim)
        RetroButton("delete it", { m.deleteSolve(last.id) }, description = "delete last solve")
        Spacer(Modifier.weight(1f))
        if (m.lastPbs.isNotEmpty()) Label("pb " + m.lastPbs.joinToString(" & ") { it.kind.label } + "!", color = Rk.c.accent, style = Rk.t.heading)
    }
}

@Composable
private fun StatsBox(m: AppModel) {
    val ss = m.derived.sessionStats
    val es = m.derived.eventStats
    Table(Modifier.fillMaxWidth()) {
        Row { HeaderCell("", 1f); HeaderCell("now", 1.2f); HeaderCell("best", 1.2f); HeaderCell("ever", 1.2f) }
        for (k in StatKind.entries) {
            val line = ss.line(k)
            val life = es.line(k)
            if (line == null && life == null) continue
            val round = k != StatKind.SINGLE
            Row {
                Cell(k.label, 1f, style = Rk.t.label, color = Rk.c.heading)
                Cell(formatTime(line?.current, round), 1.2f)
                Cell(formatTime(line?.best, round), 1.2f)
                Cell(formatTime(life?.best, round), 1.2f, color = Rk.c.gold.takeIf { life?.best != null && life.best == line?.best && life.best != DNF })
            }
        }
        Label("${ss.solved} of ${ss.count} solved, mean ${formatTime(ss.mean, true)}", Modifier.padding(horizontal = 4.dp), color = Rk.c.inkDim, style = Rk.t.label)
    }
}

@OptIn(ExperimentalResourceApi::class)
@Composable
private fun PreviewBox(m: AppModel) {
    m.replay?.let { ReplayBox(m, it); return }
    val state = m.previewState
    val svg = m.previewSvg
    val density = LocalDensity.current
    val painter = remember(svg, density) { svg?.let { runCatching { it.encodeToByteArray().decodeToSvgPainter(density) }.getOrNull() } }
    if (state == null && painter == null) return
    GroupBox("what it should look like") {
        val colors = remember(m.event) { Puzzles.colors(m.event.puzzle).map(::rgb) }
        if (state != null) PuzzleView(state, colors, Modifier.fillMaxWidth().height(190.dp), description = "3D scramble preview, drag to spin", draggable = true)
        // tnoodle's official drawing: the reference for every event
        if (painter != null) Image(painter, "scramble drawing for ${m.event.title}", Modifier.fillMaxWidth().height(if (state != null) 120.dp else 170.dp))
    }
}

@Composable
private fun ReplayBox(m: AppModel, r: Replay) {
    val camera = remember(r.solveId) { Camera() }
    GroupBox("replay") {
        PuzzleView(r.state, remember { Puzzles.colors(Puzzle.CUBE3).map(::rgb) }, Modifier.fillMaxWidth().height(230.dp), camera, r.anim, "solve replay, drag to spin", draggable = true)
        Label("move ${r.index} of ${r.total}, ${formatTime(r.elapsedMs)}", style = Rk.t.mono)
        when (r.endedSolved) {
            true -> Label("and it ends solved.", color = Rk.c.good)
            false -> Label("it does not end solved.", color = Rk.c.bad)
            null -> {}
        }
        Row {
            m.derived.sessionSolves.firstOrNull { it.id == r.solveId }?.let { s -> RetroButton("again", { m.startReplay(s) }); Label(" · ", color = Rk.c.inkDim, modifier = Modifier.padding(vertical = 4.dp)) }
            RetroButton("close", { m.stopReplay() })
        }
    }
}

@Composable
private fun SelectedSolveBox(m: AppModel) {
    val s = m.derived.sessionSolves.firstOrNull { it.id == m.selectedSolveId } ?: return
    GroupBox("solve") {
        Label(formatSolve(s), style = Rk.t.mono.copy(fontSize = 28.sp))
        Label(s.scramble, style = Rk.t.mono.copy(fontSize = 12.sp), color = Rk.c.inkDim)
        if (s.comment.isNotEmpty()) Label("“${s.comment}”")
        Tabs(listOf(Penalty.NONE, Penalty.PLUS2, Penalty.DNF), s.penalty, { when (it) { Penalty.NONE -> "fine"; Penalty.PLUS2 -> "+2"; Penalty.DNF -> "dnf" } }, { m.setPenalty(s.id, it) })
        Row {
            s.moves?.let { mv ->
                if (s.event.puzzle == Puzzle.CUBE3) { RetroButton("replay the ${mv.split(' ').size} moves", { m.startReplay(s) }); Label(" · ", color = Rk.c.inkDim, modifier = Modifier.padding(vertical = 4.dp)) }
            }
            RetroButton("delete", { m.deleteSolve(s.id) })
        }
    }
}

/** The whole window as one timer: for a second monitor, or a phone leaning on the mat. */
@Composable
private fun DisplayMode(m: AppModel) {
    val ss = m.derived.sessionStats
    Column(Modifier.fillMaxSize().padding(8.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
        val size = if (m.scramble.length > 120) 18.sp else 28.sp
        BasicText(m.scramble, Modifier.fillMaxWidth(), style = Rk.t.mono.copy(fontSize = size, color = Rk.c.ink, textAlign = TextAlign.Center, lineHeight = size * 1.3f))
        TimerDevice(m, Modifier.weight(1f).fillMaxWidth())
        Row(verticalAlignment = Alignment.CenterVertically) {
            Spacer(Modifier.width(84.dp)) // the penguin's spot
            val parts = listOf(StatKind.AO5, StatKind.AO12, StatKind.AO100).mapNotNull { k -> ss.line(k)?.let { "${k.label} ${formatTime(it.current, true)}" } }
            Label((listOf(m.event.short.lowercase(), "${ss.count} solves") + parts).joinToString("  ·  "), Modifier.weight(1f), style = Rk.t.mono.copy(fontSize = 18.sp), color = Rk.c.inkDim)
            Label(hint(m.timer, m.inspection, m.host.touchInput) + "  ", color = Rk.c.inkDim, style = Rk.t.label)
            RetroButton("leave display", { m.changeDisplayMode(false) })
        }
    }
}