Orbi-Fax Stage 1: Orbit's own teletext, offline (branch only, not installed)

Channel 000 and a Text entry in the TV guide open Orbi-Fax, a 40x25 teletext
page in the eight teletext colours with 2x3 mosaics and double height, drawn
from fixed buffers with no per-frame allocation.

- Pages: 100 index, 500 now and next, 501 listings, 510 highlights,
  520 Drive-In, 600 library arrivals, 700 Arcade records (today's single
  best per game), 999 the wizard. News, sport, weather and House and Rooms
  show as coming later.
- Navigation: number keys, a D-pad digit picker, Up/Down pages,
  Left/Right sub-pages, the Fastext row by OK or the colour keys. Back
  returns to the TV.
- Kids profiles see only their channels, never After Dark, the late show
  or the library page, and the Drive-In and Arcade only when allowed.
  Reduce motion stops the carousel and the typing warning. Orbi-Fax is
  silent.
- Concept previews, NOTES and the art exporter are in design/orbi-fax.
  The measurement plan for the Xiaomi TV is in docs/orbi-fax-stage1.md.
- 19 new unit tests. Release build, all 756 tests and lint pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-08 18:33:25 +00:00
co-authored by Claude Opus 5.5
parent 84b28b6f34
commit f1729e7bd6
44 changed files with 25247 additions and 2 deletions
@@ -91,6 +91,8 @@ private class ConnectionUi(savedTicket: Long) {
var programmeReminder by mutableStateOf<ProgrammeReminder?>(null)
var windingDown by mutableStateOf(false)
var catchUpOpen by mutableStateOf<CatchUpEntry?>(null)
/** Orbi-Fax open: true when it came from the TV (Back goes back to watching), false from the guide. */
var orbiFaxFromTv by mutableStateOf<Boolean?>(null)
var driveInVisits by mutableIntStateOf((System.currentTimeMillis() / 60_000 % DRIVE_IN_SCENES).toInt())
var guideCategory by mutableStateOf(ChannelCategory.All)
var scheduledChannels by mutableStateOf<Map<Int, ScheduledChannel>>(emptyMap())
@@ -155,6 +157,7 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea
var programmeReminder by ui::programmeReminder
var windingDown by ui::windingDown
var catchUpOpen by ui::catchUpOpen
var orbiFaxFromTv by ui::orbiFaxFromTv
// Each visit opens on the next of the three scenes.
var driveInVisits by ui::driveInVisits
var guideCategory by ui::guideCategory
@@ -776,6 +779,9 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea
return
}
if ((mainGuide || mainHome || mainWhatsOn || mainCatchUp) && liveSession != null && liveChannel != null) {
orbiFaxFromTv?.let { fromTv -> OrbiFaxScreen({ orbiFaxData(availableChannels, scheduledChannels.mapValues { it.value.plan }, driveInPlan,
{ session?.let { scheduleStore.loadArrivals(it.accountId).first }.orEmpty() }, orbiFaxRecords(OrbitSettings(appContext)), Profiles.current, System.currentTimeMillis()) },
onClose = { orbiFaxFromTv = null; watchingChannel = fromTv }); return }
if (watchingChannel) ScheduledChannelPlayer(liveSession, liveChannel, channelClockOffset,
intro = remember { CurtainIntro.takeIf { IntroTrial.take() } },
neighbours = availableChannels.map { it.number }.let { numbers -> listOf(1, -1).map { channelAfter(numbers, selectedNumber, it) } }
@@ -790,6 +796,7 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea
if (previous != null && availableChannels.any { it.number == previous }) { lastNumber = selectedNumber; selectedNumber = previous; channelClockOffset = 0 }
},
onNumber = { number ->
if (number == ORBI_FAX_CHANNEL) { orbiFaxFromTv = true; return@ScheduledChannelPlayer true }
val exists = availableChannels.any { it.number == number }
if (exists && number != selectedNumber) { lastNumber = selectedNumber; selectedNumber = number; channelClockOffset = 0 }
exists
@@ -819,7 +826,7 @@ internal fun EmbyConnectionScreen(modifier: Modifier = Modifier, visible: Boolea
onRemind = { item -> saveReminders(liveReminders(reminders, System.currentTimeMillis()) + ProgrammeReminder(item.channel, item.startMs, item.title))
if (item.driveIn == null) Taste.record(TasteKind.Saved, item.entry.media.item.id, item.entry.seriesId, item.entry.media.item.title, item.channel, "reminder") })
else -> GuideGrid(channelsIn(guideCategory, availableChannels).ifEmpty { availableChannels }, selectedNumber, modifier, guideCategory, homeCategories(availableChannels.map { it.number }), picture,
onCategory = { guideCategory = it }, onWatch = ::tune, onBack = { guideCategory = ChannelCategory.All; onHome() }, onCatchUp = { catchUpOpen = it },
onCategory = { guideCategory = it }, onWatch = ::tune, onText = { orbiFaxFromTv = false }, onBack = { guideCategory = ChannelCategory.All; onHome() }, onCatchUp = { catchUpOpen = it },
onPicture = { tune(selectedNumber, 0) }, onRest = { rested -> scope.launch { TuneAhead.warm(liveSession, rested) } },
reminders = reminders, onRemind = { number, startMs, title, on ->
val kept = liveReminders(reminders, System.currentTimeMillis()).filterNot { it.channel == number && it.startMs == startMs }
@@ -97,6 +97,18 @@ private fun CategoryChip(category: ChannelCategory, current: Boolean, grid: Focu
}
}
/** The guide's Text entry, styled as the categories are: Orbi-Fax opens on page 100. */
@Composable
private fun TextChip(grid: FocusRequester, onClick: () -> Unit) {
var focused by remember { mutableStateOf(false) }
val shape = androidx.compose.foundation.shape.RoundedCornerShape(12.dp)
Box(Modifier.focusProperties { down = grid }.onFocusChanged { focused = it.isFocused }
.background(if (focused) Yellow else Panel, shape).then(if (focused) Modifier.border(2.dp, Ink, shape) else Modifier)
.clickable(onClick = onClick).padding(horizontal = 12.dp, vertical = 4.dp)) {
Text("Text", color = if (focused) OnAccent else Ink, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, maxLines = 1)
}
}
/** The first row to draw. It moves a row before the edge, so there's always a sign of the next channel. */
internal fun guideFirstRow(row: Int, first: Int, visible: Int, count: Int): Int {
val last = (count - visible).coerceAtLeast(0)
@@ -129,7 +141,9 @@ internal fun GuideGrid(channels: List<SampleChannel>, selectedNumber: Int, modif
/** Reminders set, so a later programme shows it has one. */
reminders: List<ProgrammeReminder> = emptyList(),
/** OK on a later programme: set its reminder, or take it off again (Paul, 8 November 2026). */
onRemind: (channel: Int, startMs: Long, title: String, on: Boolean) -> Unit = { _, _, _, _ -> }) {
onRemind: (channel: Int, startMs: Long, title: String, on: Boolean) -> Unit = { _, _, _, _ -> },
/** The Text entry: opens Orbi-Fax, Orbit's teletext (Paul, 8 November 2026). None, no entry. */
onText: (() -> Unit)? = null) {
val title = category.label
// Moves on as the minute turns: nothing here shows seconds.
val now by rememberMinuteClock()
@@ -174,6 +188,7 @@ internal fun GuideGrid(channels: List<SampleChannel>, selectedNumber: Int, modif
// The categories along the top, as Home lists them: the current one gold, the focused one ringed.
Row(horizontalArrangement = Arrangement.spacedBy(5.dp)) {
categories.forEach { option -> CategoryChip(option, option == category, gridFocus) { onCategory(option) } }
if (onText != null) TextChip(gridFocus, onText)
}
Row(Modifier.fillMaxWidth().height(118.dp).background(Deep, androidx.compose.foundation.shape.RoundedCornerShape(6.dp)).padding(8.dp), horizontalArrangement = Arrangement.spacedBy(14.dp)) {
val branding = ChannelBrands.forNumber(channel.number)
@@ -0,0 +1,35 @@
package tv.orbit.classic
// Generated by design/orbi-fax/export-kotlin-art.py from the Orbi-Fax concept (8 November 2026). Don't edit by hand.
/** The dot-matrix glyphs for ASCII 32 to 126: nine rows of five dots each, one base-32 digit a row (bit 4 is the left dot). */
internal const val ORBI_FAX_GLYPHS =
"000000000444440400AA0000000AAVAVAA00000000000OP248J3008KK8LID0044800000024888420084222480004LEL4000044V44000000004480000E0000000000040001248G000EHJLPHE004C4444E00EH168GV00V1261HE0026AIV2200VGU11HE0068GUHHE00V12488800EHHEHHE00EHHF12C00040004000000000000248G8420000V0V0000842124800EH2440400000000000EHHVHHH00UHHUHHU00EHGGGHE00UHHHHHU00VGGUGGV00VGGUGGG00EHGNHHE00HHHVHHH00E44444E0072222IC00HIKOKIH00GGGGGGV00HRLLHHH00HHPLJHH00EHHHHHE00UHHUGGG00EHHHLID00UHHUKIH00EHGE1HE00V44444400HHHHHHE00HHHHHA400HHHLLLA00HHA4AHH00HHA444400V1248GV00000000000000000000000000000000000000000000V0000000000000E1FHF00GGUHHHU0000FGGGF0011FHHHF0000EHVGE00698S8880000FHHHF1EGGUHHHH0040C444E002062222IC889ACA900C44444E0000QLLLL0000UHHHH0000EHHHE0000UHHHUGG00FHHHF1100MPGGG0000FGE1U0088S88960000HHHHF0000HHAA40000HHLLA0000HA4AH0000HHHHF1E00V248V00000000000000000000000000000000000000"
/** Orbit's mark as 2x3 mosaics, 13 x 4 cells: per cell a colour digit (teletext order) then the six sixel bits in hex. */
internal val ORBI_FAX_MARK = arrayOf(
"00000000000033033c30c33c33000072073871c",
"00000000033a30700072073071c70e32c310000",
"00000072030b71c70f70300000033031e301000",
"73871e70770130230b30d30e307301000000000")
/** The P999 wizard, original to Orbit, 18 x 18 cells in the same form. */
internal val ORBI_FAX_WIZARD = arrayOf(
"00000000062063400000000000000000000042041e403000620000",
"00000000000060100000000000000042043c40700000000060b601",
"00033000000000000000000042043e33f43f43d410000000000000",
"32e33f31d00000000042043843f43f43f43f43f43d410000000000",
"00030300000000043843f33f43f43f43f43f43f43f43d410000000",
"00013f00033c33c33c33c33c33c33c33c33c33c33c33c33c314000",
"00013f00030330330330373873c73e73c73c730303303303301000",
"00013f00000000000073f73f73e73f73f73e73f715000000000000",
"00013f00000070a73f73f73770f70f70f72773f73f71f000000000",
"00013f00000000072b73f73f73f73f73f73f73f73f70162e604000",
"00013f73f43f43f43f43f73f73f73f73f73f73f43a410000000000",
"00013f73f43f43f43f43f73f73f73f73f73f71743f43d000000000",
"00013f00000043e43f43f43573f73f73f71f43f43f43f414000000",
"00013f00042843f43f43f43f72b73f73f43e43f43f43f43d60861d",
"00013f00043f43f43f43f43f43f73f71543f43f43f43f43f415000",
"00013f42a43f43f43f43f43f43f43f43f43f43f43f43f43f43f000",
"00013f43f43f43f41f40f40f43f43f43f41f40f40f43f43f43f435",
"00013f43f43f43f52a53f53f43f43f43f52a53f53f43f43f43f43f")
@@ -0,0 +1,89 @@
package tv.orbit.classic
/** Orbi-Fax opens from channel 000 (Paul, 8 November 2026). */
internal const val ORBI_FAX_CHANNEL = 0
internal const val ORBI_FAX_INDEX = 100
internal const val ORBI_FAX_WIZARD_PAGE = 999
/** The Fastext row's four links, then the "Page" box that opens the digit picker. */
internal const val ORBI_FAX_LINKS = 4
internal const val ORBI_FAX_PAGE_BOX = 4
private const val HISTORY_MAX = 16
internal enum class OrbiFaxKey { Up, Down, Left, Right, Ok, Back, Red, Green, Yellow, Cyan, PageUp, PageDown }
/** What navigation needs to know about the pages: which can be stepped through, their sub-pages and their links. */
internal interface OrbiFaxBook {
/** The pages Up and Down step through, in order. 999 is never among them: it has to be keyed. */
val pages: IntArray
fun subPages(page: Int): Int
/** Where Fastext link [index] (0 red, 1 green, 2 yellow, 3 cyan) goes from [page]. */
fun link(page: Int, index: Int): Int
}
/**
* Where the viewer is. [typed] holds digits keyed so far (up to two), [picker] the D-pad digit picker when it's open,
* and [bar] the focused link on the Fastext row (-1 when the row isn't focused).
*/
internal data class OrbiFaxNav(val page: Int = ORBI_FAX_INDEX, val sub: Int = 0, val typed: String = "", val picker: ChannelEntry? = null,
val bar: Int = -1, val history: List<Int> = emptyList()) {
fun go(number: Int): OrbiFaxNav {
val target = if (number in 100..999) number else ORBI_FAX_INDEX
return OrbiFaxNav(page = target, history = (history + page).takeLast(HISTORY_MAX))
}
/** One digit, from the number keys: the third one goes to the page. */
fun digit(d: Int): OrbiFaxNav {
picker?.let { p -> val next = p.type(d); return if (p.onLastSlot) go(next.number) else copy(picker = next) }
val now = typed + digitText(d)
return if (now.length == 3) go(now.toInt()) else copy(typed = now, bar = -1)
}
/** A key; null means Back with nothing left to close, so Orbi-Fax hands back to the TV. */
fun press(key: OrbiFaxKey, book: OrbiFaxBook): OrbiFaxNav? {
val count = book.subPages(page).coerceAtLeast(1)
picker?.let { p ->
return when (key) {
OrbiFaxKey.Up -> copy(picker = p.dial(1))
OrbiFaxKey.Down -> copy(picker = p.dial(-1))
OrbiFaxKey.Left -> copy(picker = p.previous())
OrbiFaxKey.Right -> copy(picker = p.next())
OrbiFaxKey.Ok -> go(p.number)
OrbiFaxKey.Back -> copy(picker = null)
else -> copy(picker = null).press(key, book)
}
}
if (bar >= 0) when (key) {
OrbiFaxKey.Left -> return copy(bar = (bar - 1).coerceAtLeast(0))
OrbiFaxKey.Right -> return copy(bar = (bar + 1).coerceAtMost(ORBI_FAX_PAGE_BOX))
OrbiFaxKey.Ok -> return if (bar == ORBI_FAX_PAGE_BOX) copy(bar = -1, picker = ChannelEntry.from(page)) else go(book.link(page, bar))
OrbiFaxKey.Back -> return copy(bar = -1)
else -> {}
}
return when (key) {
OrbiFaxKey.Back -> if (typed.isNotEmpty()) copy(typed = "") else null
OrbiFaxKey.Up, OrbiFaxKey.PageUp -> go(step(book.pages, 1))
OrbiFaxKey.Down, OrbiFaxKey.PageDown -> go(step(book.pages, -1))
OrbiFaxKey.Left -> copy(sub = Math.floorMod(sub - 1, count), typed = "")
OrbiFaxKey.Right -> copy(sub = Math.floorMod(sub + 1, count), typed = "")
OrbiFaxKey.Ok -> copy(bar = ORBI_FAX_PAGE_BOX, typed = "")
OrbiFaxKey.Red -> go(book.link(page, 0))
OrbiFaxKey.Green -> go(book.link(page, 1))
OrbiFaxKey.Yellow -> go(book.link(page, 2))
OrbiFaxKey.Cyan -> go(book.link(page, 3))
}
}
/** The carousel's turn to the next sub-page (never while the viewer is keying or choosing). */
fun turn(book: OrbiFaxBook): OrbiFaxNav {
val count = book.subPages(page)
return if (count <= 1 || typed.isNotEmpty() || picker != null || bar >= 0) this else copy(sub = (sub + 1) % count)
}
/** The next or previous page in [pages]; from a page that isn't among them, the nearest one in that direction. */
private fun step(pages: IntArray, direction: Int): Int {
if (pages.isEmpty()) return ORBI_FAX_INDEX
return if (direction > 0) pages.firstOrNull { it > page } ?: pages.first()
else pages.lastOrNull { it < page } ?: pages.last()
}
}
@@ -0,0 +1,188 @@
package tv.orbit.classic
import java.text.Normalizer
/**
* Orbi-Fax Stage 1 (approved by Paul on 8 November 2026): Orbit's own teletext, entirely offline.
* A page is the authentic 40 x 25 grid of character cells in the eight teletext colours, with 2x3 mosaics and double height.
* Every array is fixed in size and reused: building and drawing a page allocates nothing.
*/
internal object Teletext {
const val COLS = 40
const val ROWS = 25
const val CELLS = COLS * ROWS
/** Each cell is a 6 x 10 dot matrix, so the whole page is 240 x 250 dots, drawn scaled to a 4:3 area. */
const val CELL_W = 6
const val CELL_H = 10
const val WIDTH = COLS * CELL_W
const val HEIGHT = ROWS * CELL_H
const val BLACK = 0; const val RED = 1; const val GREEN = 2; const val YELLOW = 3
const val BLUE = 4; const val MAGENTA = 5; const val CYAN = 6; const val WHITE = 7
/** Teletext order, ARGB. Nothing else is ever drawn inside the page. */
val PALETTE = intArrayOf(0xFF000000.toInt(), 0xFFFF0000.toInt(), 0xFF00FF00.toInt(), 0xFFFFFF00.toInt(),
0xFF0000FF.toInt(), 0xFFFF00FF.toInt(), 0xFF00FFFF.toInt(), 0xFFFFFFFF.toInt())
}
/** Text as the glyph set can show it: accents dropped, curly quotes and dashes made plain, anything else a space. */
internal fun teletextText(text: String): String {
val plain = Normalizer.normalize(text, Normalizer.Form.NFD).replace(Regex("\\p{M}+"), "")
val out = StringBuilder(plain.length)
for (ch in plain) out.append(when (ch) {
'‘', '’', 'ʼ' -> '\''
'“', '”' -> '"'
'–', '—', '−' -> '-'
'…' -> '.'
' ', '\t', '\n' -> ' '
else -> if (ch.code in 32..126) ch else ' '
})
return out.toString()
}
internal class TeletextPage {
val chars = CharArray(Teletext.CELLS)
val fg = ByteArray(Teletext.CELLS)
val bg = ByteArray(Teletext.CELLS)
val mosaic = ByteArray(Teletext.CELLS)
val flags = ByteArray(Teletext.CELLS)
companion object {
const val MOSAIC = 1
const val DOUBLE = 2
/** The lower half of a double-height cell above: drawn by that cell, so this one shows only its background. */
const val LOWER = 4
}
init { clear() }
fun clear() {
chars.fill(' '); fg.fill(Teletext.WHITE.toByte()); bg.fill(Teletext.BLACK.toByte()); mosaic.fill(0); flags.fill(0)
}
/** Clears one row only, as the header does each second. */
fun clearRow(row: Int) {
val from = row * Teletext.COLS; val to = from + Teletext.COLS
chars.fill(' ', from, to); fg.fill(Teletext.WHITE.toByte(), from, to); bg.fill(Teletext.BLACK.toByte(), from, to)
mosaic.fill(0, from, to); flags.fill(0, from, to)
}
/**
* Writes [text] from [col], clipped at the row's end. [background] of -1 keeps what's there. Double height covers the
* row below too. Returns the column after the text.
*/
fun put(row: Int, col: Int, text: CharSequence, colour: Int = Teletext.WHITE, background: Int = -1, double: Boolean = false): Int {
if (row !in 0 until Teletext.ROWS) return col
for (i in text.indices) {
val c = col + i
if (c !in 0 until Teletext.COLS) continue
val at = row * Teletext.COLS + c
val ch = text[i]
chars[at] = if (ch.code in 32..126) ch else ' '
fg[at] = colour.toByte()
if (background >= 0) bg[at] = background.toByte()
flags[at] = if (double) DOUBLE.toByte() else 0
if (double && row + 1 < Teletext.ROWS) {
val below = at + Teletext.COLS
chars[below] = ' '; flags[below] = LOWER.toByte()
if (background >= 0) bg[below] = background.toByte()
}
}
return col + text.length
}
/** Writes a number right-aligned so its last digit sits in [lastCol], with no string made. */
fun putNumber(row: Int, lastCol: Int, value: Int, colour: Int = Teletext.WHITE) {
var v = if (value < 0) 0 else value; var c = lastCol
do { if (c >= 0) put(row, c, digitText(v % 10), colour); v /= 10; c-- } while (v > 0)
}
fun fill(row: Int, fromCol: Int, toCol: Int, background: Int) {
if (row !in 0 until Teletext.ROWS) return
for (c in fromCol.coerceAtLeast(0) until toCol.coerceAtMost(Teletext.COLS)) bg[row * Teletext.COLS + c] = background.toByte()
}
/** A 2x3 mosaic cell: bit 0 top left, 1 top right, 2 middle left, 3 middle right, 4 bottom left, 5 bottom right. */
fun mosaic(row: Int, col: Int, bits: Int, colour: Int) {
if (row !in 0 until Teletext.ROWS || col !in 0 until Teletext.COLS) return
val at = row * Teletext.COLS + col
chars[at] = ' '; fg[at] = colour.toByte(); mosaic[at] = (bits and 63).toByte(); flags[at] = MOSAIC.toByte()
}
/** A line of mosaics, by default the bottom third of each cell. */
fun rule(row: Int, colour: Int, fromCol: Int = 0, toCol: Int = Teletext.COLS, bits: Int = 0b110000) {
for (c in fromCol until toCol) mosaic(row, c, bits, colour)
}
/** Mosaic artwork in [ORBI_FAX_MARK]'s form: three characters a cell (colour digit, then the bits in hex). */
fun art(row: Int, col: Int, rows: Array<String>) {
for (r in rows.indices) {
val line = rows[r]
var c = 0
while (c * 3 + 2 < line.length) {
val bits = Character.digit(line[c * 3 + 1], 16) * 16 + Character.digit(line[c * 3 + 2], 16)
if (bits != 0) mosaic(row + r, col + c, bits, line[c * 3] - '0')
c++
}
}
}
/** One row as plain text, mosaics shown as '#'. For tests and logs. */
fun rowText(row: Int): String = buildString {
for (c in 0 until Teletext.COLS) {
val at = row * Teletext.COLS + c
append(if (flags[at].toInt() and MOSAIC != 0) '#' else chars[at])
}
}
}
private val Digits = Array(10) { it.toString() }
internal fun digitText(d: Int) = Digits[d]
/** Draws a page into a 240 x 250 ARGB buffer: backgrounds first, then every glyph and mosaic. Allocates nothing. */
internal object TeletextRenderer {
private val glyphs: ByteArray = ByteArray(95 * 9).also { out ->
for (i in out.indices) out[i] = Character.digit(ORBI_FAX_GLYPHS[i], 32).toByte()
}
private val bandTop = intArrayOf(0, 3, 7)
private val bandHeight = intArrayOf(3, 4, 3)
fun glyphRow(ch: Char, row: Int): Int {
val code = ch.code - 32
return if (code in 0 until 95 && row in 0 until 9) glyphs[code * 9 + row].toInt() else 0
}
fun render(page: TeletextPage, out: IntArray) {
require(out.size == Teletext.WIDTH * Teletext.HEIGHT)
val w = Teletext.WIDTH
for (cell in 0 until Teletext.CELLS) {
val x0 = (cell % Teletext.COLS) * Teletext.CELL_W; val y0 = (cell / Teletext.COLS) * Teletext.CELL_H
val colour = Teletext.PALETTE[page.bg[cell].toInt()]
for (y in y0 until y0 + Teletext.CELL_H) out.fill(colour, y * w + x0, y * w + x0 + Teletext.CELL_W)
}
for (cell in 0 until Teletext.CELLS) {
val flag = page.flags[cell].toInt()
if (flag and TeletextPage.LOWER != 0) continue
val x0 = (cell % Teletext.COLS) * Teletext.CELL_W; val y0 = (cell / Teletext.COLS) * Teletext.CELL_H
val colour = Teletext.PALETTE[page.fg[cell].toInt()]
if (flag and TeletextPage.MOSAIC != 0) {
val bits = page.mosaic[cell].toInt()
for (band in 0 until 3) for (half in 0 until 2) if (bits shr (band * 2 + half) and 1 != 0) {
val left = x0 + half * 3
for (y in y0 + bandTop[band] until y0 + bandTop[band] + bandHeight[band]) out.fill(colour, y * w + left, y * w + left + 3)
}
continue
}
val ch = page.chars[cell]
if (ch == ' ') continue
val scale = if (flag and TeletextPage.DOUBLE != 0) 2 else 1
for (gy in 0 until 9) {
val bits = glyphRow(ch, gy)
if (bits == 0) continue
for (s in 0 until scale) {
val y = y0 + (gy + 1) * scale + s
if (y >= Teletext.HEIGHT) continue
for (gx in 0 until 5) if (bits shr (4 - gx) and 1 != 0) out[y * w + x0 + gx] = colour
}
}
}
}
}
@@ -0,0 +1,299 @@
package tv.orbit.classic
import java.time.Instant
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.Locale
import tv.orbit.classic.Teletext.BLACK
import tv.orbit.classic.Teletext.BLUE
import tv.orbit.classic.Teletext.CYAN
import tv.orbit.classic.Teletext.GREEN
import tv.orbit.classic.Teletext.MAGENTA
import tv.orbit.classic.Teletext.RED
import tv.orbit.classic.Teletext.WHITE
import tv.orbit.classic.Teletext.YELLOW
internal data class OrbiFaxShow(val startMs: Long, val title: String)
internal data class OrbiFaxChannel(val number: Int, val name: String, val shows: List<OrbiFaxShow>)
internal data class OrbiFaxHighlight(val channelName: String, val startMs: Long, val title: String, val tag: String)
internal data class OrbiFaxBill(val label: String, val whenText: String, val titles: List<String>)
internal data class OrbiFaxArrival(val title: String, val type: String)
internal data class OrbiFaxRecord(val game: String, val colour: Int, val best: String?)
/**
* Everything the pages show, read once from Orbit's own records (nothing from the network). A null list is a page the
* profile isn't allowed; an empty one is a page with nothing on it yet. Text is already in the glyph set.
*/
internal data class OrbiFaxData(val channels: List<OrbiFaxChannel>, val highlights: List<OrbiFaxHighlight>, val driveIn: List<OrbiFaxBill>?,
val arrivals: List<OrbiFaxArrival>?, val records: List<OrbiFaxRecord>?, val kids: Boolean)
internal const val ORBI_FAX_NOW_NEXT = 500
internal const val ORBI_FAX_LISTINGS = 501
internal const val ORBI_FAX_HIGHLIGHTS = 510
internal const val ORBI_FAX_DRIVE_IN = 520
internal const val ORBI_FAX_ARRIVALS = 600
internal const val ORBI_FAX_ARCADE = 700
private const val CHANNELS_PER_SUB = 6
private const val HIGHLIGHTS_PER_SUB = 5
private const val ARRIVALS_PER_SUB = 16
private const val LISTING_ROWS = 17
/** The warning on 999, exactly as established. */
internal const val ORBI_FAX_WARNING = "You have gone too far, young traveller. Return at once!"
private val WarningLines = arrayOf("You have gone", "too far, young", "traveller.", "Return at once!")
/** The pages that will come later: shown greyed on the index and as their own "coming later" page. */
internal val OrbiFaxLater = linkedMapOf(101 to "News", 300 to "Sport", 400 to "Weather", 800 to "House and Rooms")
private val LinkLabels = mapOf(100 to "Index", 500 to "On Now", 501 to "Listing", 510 to "Tonight", 520 to "DriveIn", 600 to "Library", 700 to "Arcade")
internal class OrbiFaxPages(val data: OrbiFaxData) : OrbiFaxBook {
/** Whether this profile may see [page]. Kids never sees the library page, and the Drive-In and Arcade only when allowed. */
fun allowed(page: Int) = when (page) {
ORBI_FAX_DRIVE_IN -> data.driveIn != null
ORBI_FAX_ARRIVALS -> data.arrivals != null
ORBI_FAX_ARCADE -> data.records != null
else -> true
}
override val pages: IntArray = intArrayOf(ORBI_FAX_INDEX, ORBI_FAX_NOW_NEXT, ORBI_FAX_LISTINGS, ORBI_FAX_HIGHLIGHTS, ORBI_FAX_DRIVE_IN, ORBI_FAX_ARRIVALS, ORBI_FAX_ARCADE)
.filter(::allowed).toIntArray()
override fun subPages(page: Int) = when (page) {
ORBI_FAX_NOW_NEXT -> chunks(data.channels.size, CHANNELS_PER_SUB)
ORBI_FAX_LISTINGS -> data.channels.size.coerceAtLeast(1)
ORBI_FAX_HIGHLIGHTS -> chunks(data.highlights.size, HIGHLIGHTS_PER_SUB)
ORBI_FAX_ARRIVALS -> chunks(data.arrivals?.size ?: 0, ARRIVALS_PER_SUB)
else -> 1
}
private val linkCache = HashMap<Int, IntArray>()
private fun links(page: Int) = linkCache.getOrPut(page) {
val wanted = if (page == ORBI_FAX_INDEX) listOf(500, 510, 520, 700, 600, 501) else listOf(100, 500, 510, 700, 520, 600, 501)
wanted.filter { it != page && allowed(it) }.take(ORBI_FAX_LINKS).toIntArray()
}
override fun link(page: Int, index: Int) = links(page).getOrElse(index) { ORBI_FAX_INDEX }
/** Builds [page] into [out], all but the header row, which [header] writes each second. */
fun build(out: TeletextPage, page: Int, sub: Int, nowMs: Long, zone: ZoneId, reveal: Int = Int.MAX_VALUE) {
out.clear()
val s = sub.coerceIn(0, subPages(page) - 1)
when {
!allowed(page) -> notAllowed(out, page)
page == ORBI_FAX_INDEX -> index(out)
page == ORBI_FAX_NOW_NEXT -> nowNext(out, s, nowMs, zone)
page == ORBI_FAX_LISTINGS -> listings(out, s, nowMs, zone)
page == ORBI_FAX_HIGHLIGHTS -> highlights(out, s, zone)
page == ORBI_FAX_DRIVE_IN -> driveIn(out)
page == ORBI_FAX_ARRIVALS -> arrivals(out, s)
page == ORBI_FAX_ARCADE -> arcade(out)
page == ORBI_FAX_WIZARD_PAGE -> wizard(out, reveal)
else -> missing(out, page)
}
if (subPages(page) > 1) subIndicator(out, s + 1, subPages(page))
}
/** Row 0: page number, ORBI-FAX, what's being keyed (or the page), date and clock. */
fun header(out: TeletextPage, nav: OrbiFaxNav, nowMs: Long, zone: ZoneId) {
out.clearRow(0)
out.put(0, 0, "P"); out.putNumber(0, 3, nav.page)
out.put(0, 5, " ORBI-FAX ", YELLOW, BLUE)
val picker = nav.picker
when {
picker != null -> for (i in 0 until 3) {
val focused = i == picker.slot
out.put(0, 16 + i, digitText(picker.digits[i]), if (focused) BLACK else YELLOW, if (focused) YELLOW else BLACK)
}
nav.typed.isNotEmpty() -> { out.put(0, 16, nav.typed, YELLOW); for (i in nav.typed.length until 3) out.put(0, 16 + i, "-", YELLOW) }
else -> out.putNumber(0, 18, nav.page)
}
val at = Instant.ofEpochMilli(nowMs).atZone(zone)
out.put(0, 21, DateFormat.format(at))
out.put(0, 32, ClockFormat.format(at), YELLOW)
}
/** Row 24: the four Fastext links (red, green, yellow, cyan) and "Page", the focused one shown in reverse. */
fun fastext(out: TeletextPage, nav: OrbiFaxNav) {
out.clearRow(24)
val colours = intArrayOf(RED, GREEN, YELLOW, CYAN)
for (i in 0 until ORBI_FAX_LINKS) {
val label = LinkLabels[link(nav.page, i)] ?: "Index"
val focused = nav.bar == i
out.put(24, i * 9 + 1, label, if (focused) BLACK else colours[i], if (focused) colours[i] else BLACK)
}
val focused = nav.bar == ORBI_FAX_PAGE_BOX
out.put(24, 36, "Page", if (focused) BLACK else WHITE, if (focused) WHITE else BLACK)
}
private fun title(out: TeletextPage, text: String, colour: Int = YELLOW) = out.put(1, 1, text, colour, double = true)
private fun subIndicator(out: TeletextPage, at: Int, of: Int) {
val text = "$at/$of"
out.put(1, Teletext.COLS - text.length, text, WHITE)
}
private fun index(out: TeletextPage) {
for (r in 1..4) out.fill(r, 0, Teletext.COLS, BLUE)
out.art(1, 0, ORBI_FAX_MARK)
out.put(1, 14, "ORBI-FAX", YELLOW, BLUE, double = true)
out.put(3, 14, "Orbit's own pages", WHITE, BLUE)
out.put(4, 14, "Channel 000 opens Orbi-Fax", CYAN, BLUE)
out.rule(5, YELLOW)
val sections = listOf("On Orbit Now" to 500, "Tonight's Highlights" to 510, "The Drive-In" to 520,
"New In Your Library" to 600, "Arcade Records" to 700).filter { allowed(it.second) }
sections.forEachIndexed { i, (name, number) ->
val row = 7 + i * 2
out.put(row, 2, name, YELLOW)
out.put(row, 4 + name.length, ".".repeat((32 - name.length).coerceAtLeast(0)), BLUE)
out.putNumber(row, 38, number)
}
out.rule(19, BLUE)
out.put(20, 2, "Coming later", WHITE)
var col = 2
OrbiFaxLater.entries.take(3).forEach { (number, name) -> col = out.put(21, col, "$name $number", BLUE) + 3 }
OrbiFaxLater[800]?.let { out.put(22, 2, "$it 800", BLUE) }
out.put(23, 2, "OK for links, or key a page number", CYAN)
}
private fun nowNext(out: TeletextPage, sub: Int, nowMs: Long, zone: ZoneId) {
title(out, "ON ORBIT NOW")
out.put(3, 1, DateFormat.format(Instant.ofEpochMilli(nowMs).atZone(zone)))
out.put(3, 24, "NOW"); out.put(3, 28, "then"); out.put(3, 33, "NEXT", CYAN)
out.rule(4, YELLOW)
if (data.channels.isEmpty()) { out.put(6, 1, "No channels are on yet.", WHITE); return }
data.channels.drop(sub * CHANNELS_PER_SUB).take(CHANNELS_PER_SUB).forEachIndexed { i, ch ->
val row = 5 + i * 3
out.fill(row, 0, Teletext.COLS, BLUE)
out.putNumber(row, 3, ch.number); out.put(row, 5, ch.name.take(34), YELLOW, BLUE)
val now = ch.shows.lastOrNull { it.startMs <= nowMs } ?: ch.shows.firstOrNull()
val next = now?.let { n -> ch.shows.firstOrNull { it.startMs > n.startMs } }
now?.let { show(out, row + 1, it, WHITE, zone) }
next?.let { show(out, row + 2, it, CYAN, zone) }
}
out.put(23, 1, "Full listings 501, channel by channel", WHITE)
}
private fun listings(out: TeletextPage, sub: Int, nowMs: Long, zone: ZoneId) {
title(out, "LISTINGS")
val ch = data.channels.getOrNull(sub)
if (ch == null) { out.rule(4, YELLOW); out.put(6, 1, "No channels are on yet.", WHITE); return }
out.fill(3, 0, Teletext.COLS, BLUE); out.putNumber(3, 3, ch.number); out.put(3, 5, ch.name.take(34), YELLOW, BLUE)
out.rule(4, YELLOW)
val current = ch.shows.lastOrNull { it.startMs <= nowMs }
ch.shows.filter { it.startMs >= (current?.startMs ?: Long.MIN_VALUE) }.take(LISTING_ROWS).forEachIndexed { i, s ->
show(out, 5 + i, s, if (s === current) WHITE else CYAN, zone, timeColour = if (s === current) YELLOW else WHITE)
}
out.put(23, 1, "< > for the next channel", WHITE)
}
private fun show(out: TeletextPage, row: Int, s: OrbiFaxShow, colour: Int, zone: ZoneId, timeColour: Int = colour) {
out.put(row, 2, TimeFormat.format(Instant.ofEpochMilli(s.startMs).atZone(zone)), timeColour)
out.put(row, 8, s.title.take(31), colour)
}
private fun highlights(out: TeletextPage, sub: Int, zone: ZoneId) {
title(out, "TONIGHT'S HIGHLIGHTS")
out.put(3, 1, "Picked from Orbit's own schedules", CYAN)
out.rule(4, YELLOW)
if (data.highlights.isEmpty()) { out.put(6, 1, "Nothing picked out yet. Look again", WHITE); out.put(7, 1, "after the noon edition.", WHITE); return }
data.highlights.drop(sub * HIGHLIGHTS_PER_SUB).take(HIGHLIGHTS_PER_SUB).forEachIndexed { i, h ->
val row = 5 + i * 3
out.put(row, 1, TimeFormat.format(Instant.ofEpochMilli(h.startMs).atZone(zone)), WHITE)
out.put(row, 7, h.channelName.take(32), YELLOW)
out.put(row + 1, 3, h.title.take(36), WHITE)
if (h.tag.isNotEmpty()) out.put(row + 2, 3, h.tag.take(36), CYAN)
}
}
private fun driveIn(out: TeletextPage) {
title(out, "THE DRIVE-IN")
out.put(3, 1, "Films under the stars", CYAN)
out.rule(4, YELLOW)
val bills = data.driveIn.orEmpty()
if (bills.isEmpty()) { out.put(6, 1, "No shows are booked yet.", WHITE); return }
var row = 5
for (bill in bills) {
if (row > 21) break
out.put(row, 1, bill.label.take(20), YELLOW)
out.put(row, (Teletext.COLS - bill.whenText.length).coerceAtLeast(22), bill.whenText.take(18), WHITE)
row++
for (t in bill.titles) { if (row > 22) break; out.put(row, 3, t.take(36), WHITE); row++ }
row++
}
}
private fun arrivals(out: TeletextPage, sub: Int) {
title(out, "NEW IN YOUR LIBRARY")
out.put(3, 1, "First seen in the last 14 days", CYAN)
out.rule(4, YELLOW)
val list = data.arrivals.orEmpty()
if (list.isEmpty()) { out.put(6, 1, "Nothing new yet.", WHITE); return }
list.drop(sub * ARRIVALS_PER_SUB).take(ARRIVALS_PER_SUB).forEachIndexed { i, a ->
out.put(5 + i, 1, a.title.take(30), WHITE)
out.put(5 + i, 33, a.type.take(7), CYAN)
}
}
private fun arcade(out: TeletextPage) {
title(out, "ARCADE RECORDS")
out.put(3, 1, "The best on this TV", CYAN)
out.rule(4, YELLOW)
data.records.orEmpty().forEachIndexed { i, r ->
val row = 5 + i * 2
out.put(row, 1, r.game.uppercase(Locale.ROOT), r.colour)
val best = r.best ?: "no record yet"
out.put(row, Teletext.COLS - 1 - best.length, best, if (r.best == null) BLUE else WHITE)
}
out.put(23, 1, "Beat a record in the Orbit Arcade", CYAN)
}
private fun wizard(out: TeletextPage, reveal: Int) {
out.art(2, 1, ORBI_FAX_WIZARD)
out.rule(1, CYAN, 19, Teletext.COLS)
out.rule(12, CYAN, 19, Teletext.COLS, bits = 0b000011)
var left = reveal
WarningLines.forEachIndexed { i, line ->
if (left <= 0) return@forEachIndexed
val shown = if (left >= line.length) line else line.substring(0, left)
out.put(3 + i * 2, 21, shown, if (i == WarningLines.lastIndex) YELLOW else WHITE, double = true)
left -= line.length
}
out.put(14, 21, "This page is past", CYAN); out.put(15, 21, "the edge of", CYAN); out.put(16, 21, "Orbi-Fax.", CYAN)
out.put(18, 21, "Key 100 to fly"); out.put(19, 21, "home to the index.")
out.put(22, 1, "P999 The wizard's corner", MAGENTA)
}
private fun missing(out: TeletextPage, page: Int) {
title(out, "PAGE $page")
out.rule(4, YELLOW)
val later = OrbiFaxLater[page]
if (later != null) { out.put(6, 1, "$later is coming later to Orbi-Fax.", WHITE) }
else { out.put(6, 1, "There's no page $page in Orbi-Fax.", WHITE) }
out.put(8, 1, "Key 100 for the index.", CYAN)
}
private fun notAllowed(out: TeletextPage, page: Int) {
title(out, "PAGE $page")
out.rule(4, YELLOW)
out.put(6, 1, "This page isn't on this profile.", WHITE)
out.put(8, 1, "Key 100 for the index.", CYAN)
}
companion object {
val DateFormat: DateTimeFormatter = DateTimeFormatter.ofPattern("EEE dd MMM", Locale.UK)
val ClockFormat: DateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss", Locale.UK)
val TimeFormat: DateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm", Locale.UK)
private fun chunks(size: Int, per: Int) = ((size + per - 1) / per).coerceAtLeast(1)
/** The Arcade's games, as the Arcade names and colours them, with today's single best per game. */
fun records(orbMan: Int, snake: Int, blocks: Int, bricks: Int, blast: Int, skySolved: Int, pairs: Int, patienceWins: Int) = listOf(
OrbiFaxRecord("Star Chase", YELLOW, orbMan.takeIf { it > 0 }?.let { "%,d".format(Locale.UK, it) }),
OrbiFaxRecord("Comet Trail", GREEN, snake.takeIf { it > 0 }?.let { "%,d".format(Locale.UK, it) }),
OrbiFaxRecord("Block Drop", CYAN, blocks.takeIf { it > 0 }?.let { "%,d".format(Locale.UK, it) }),
OrbiFaxRecord("Brick Break", RED, bricks.takeIf { it > 0 }?.let { "%,d".format(Locale.UK, it) }),
OrbiFaxRecord("Blast Off", MAGENTA, blast.takeIf { it > 0 }?.let { "%,d".format(Locale.UK, it) }),
OrbiFaxRecord("Skydoku", WHITE, skySolved.takeIf { it > 0 }?.let { "$it solved" }),
OrbiFaxRecord("BumbleHive", YELLOW, null),
OrbiFaxRecord("Pairs", GREEN, pairs.takeIf { it > 0 }?.let { "$it moves" }),
OrbiFaxRecord("Patience", CYAN, patienceWins.takeIf { it > 0 }?.let { "$it won" }))
}
}
@@ -0,0 +1,245 @@
package tv.orbit.classic
import android.graphics.Bitmap
import android.os.SystemClock
import android.view.KeyEvent
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.focusable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
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.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
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.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.FilterQuality
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.drawscope.rotate
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.tv.material3.Text
import java.time.ZoneId
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
/** Sub-pages turn on their own every this often, unless Reduce motion is on (then only < and > turn them). */
internal const val ORBI_FAX_CAROUSEL_MS = 12_000L
/** The pages' records are read again this often while Orbi-Fax is open. */
private const val ORBI_FAX_REFRESH_MS = 60_000L
private const val ARRIVALS_SHOWN = 64
private const val LISTED_SHOWS = 18
/** Orbit Classic's own colours, for the 16:9 margins only (design/orbi-fax/NOTES.md). Inside the page it's teletext's eight. */
private val MarginTop = Color(0xFF030915)
private val MarginBottom = Color(0xFF12356B)
private val MarginFrame = Color(0xFF194C91)
private val MarginFocus = Color(0xFFFFDE59)
private val MarginMuted = Color(0xFFB7CBE8)
private val MarginOrange = Color(0xFFF7A928)
/**
* Reads what Orbi-Fax shows from Orbit's own records, for the profile watching. [channels] and [plans] come already
* filtered by the After Dark lock and the profile; Kids also never sees After Dark or the late show here, whatever is ticked.
*/
internal fun orbiFaxData(channels: List<SampleChannel>, plans: Map<Int, ChannelPlan>, driveIn: ChannelPlan?, arrivals: () -> List<Arrival>,
records: List<OrbiFaxRecord>, profile: Profile?, nowMs: Long, zone: ZoneId = ZoneId.systemDefault()): OrbiFaxData {
val kids = profile?.kind == ProfileKind.Kids
fun kidsMayNotSee(number: Int) = kids && (number == AFTER_DARK_NUMBER || number in LockedChannels)
val shown = channels.filterNot { lockedOut(it.number) || profileHides(it.number, profile) || kidsMayNotSee(it.number) }.sortedBy { it.number }
val listed = shown.map { ch ->
val shows = runCatching { ch.guide(nowMs, LISTED_SHOWS) }.getOrDefault(emptyList()).map { show ->
val title = if (kids && takeoverOf(ch.number, show, zone)?.kidsSafe == false) "Asleep till 6am" else guideTitle(ch.number, show).first
OrbiFaxShow(show.startMs, teletextText(title))
}
OrbiFaxChannel(ch.number, teletextText(ChannelBrands.displayName(ch)), shows)
}
val driveInAllowed = profile == null || profile.kind != ProfileKind.Kids || profile.driveIn
val okPlans = plans.filterKeys { !lockedOut(it) && !profileHides(it, profile) && !kidsMayNotSee(it) }
val page = runCatching { whatsOnPage(okPlans, driveIn.takeIf { driveInAllowed }, nowMs, zone) }.getOrNull()
val highlights = page?.let { listOfNotNull(it.pick) + it.tonight + it.comingUp }.orEmpty()
.filterNot { it.driveIn != null && (lockedOut(it.driveIn) || (kids && it.driveIn.kind == DriveInKind.LateShow)) }
.distinctBy { it.channel to it.startMs }.sortedBy { it.startMs }
.map { item ->
val name = if (item.driveIn != null) "The Drive-In" else ChannelBrands.forNumber(item.channel)?.displayName ?: "Channel ${item.channel}"
OrbiFaxHighlight(teletextText(name), item.startMs, teletextText(item.title), teletextText(item.tag))
}
val bills = if (!driveInAllowed) null else driveIn?.let { plan ->
runCatching { driveInLineup(driveInBills(plan, zone), nowMs) }.getOrDefault(emptyList())
.filterNot { lockedOut(it) || (kids && it.kind == DriveInKind.LateShow) }.take(4)
.map { bill -> OrbiFaxBill(teletextText(bill.kind.label), teletextText(driveInWhen(bill, nowMs)), bill.entries.map { teletextText(guideTitleParts(it.media.item.title).first) }) }
}.orEmpty().takeIf { driveInAllowed }
// The library page lists whatever arrived, with no rating to go by, so it's for grown-up profiles only.
val newArrivals = if (kids) null else runCatching(arrivals).getOrDefault(emptyList())
.filter { it.firstSeenMs >= nowMs - NEW_TO_LIBRARY_DAYS * 24 * 60 * 60_000L }.sortedByDescending { it.firstSeenMs }.take(ARRIVALS_SHOWN)
.map { OrbiFaxArrival(teletextText(it.title + (it.year?.let { y -> " ($y)" } ?: "")), teletextText(it.type)) }
return OrbiFaxData(listed, highlights, bills, newArrivals, records.takeUnless { kids && profile?.arcade == false }, kids)
}
/** The Arcade's records as kept today: one best per game on this TV, read from its settings. */
internal fun orbiFaxRecords(settings: OrbitSettings) = OrbiFaxPages.records(settings.orbManBest, settings.snakeBest, settings.blockDropBest,
settings.brickBreakBest, settings.blastBest, settings.skydokuSolved, settings.pairsBest, settings.patienceWins)
/** How long drawing takes, logged every so often for the measurement on the Xiaomi TV (tag OrbiFax). */
private class RenderTimer {
var count = 0; var totalNs = 0L; var maxNs = 0L
fun record(ns: Long) {
count++; totalNs += ns; if (ns > maxNs) maxNs = ns
if (count == 30) {
android.util.Log.i("OrbiFax", "render avgUs=${totalNs / count / 1000} maxUs=${maxNs / 1000} renders=$count")
count = 0; totalNs = 0; maxNs = 0
}
}
}
/**
* Orbi-Fax full screen: the 4:3 page centred, Orbit's margins either side. Silent throughout, so the quiet settings have
* nothing to quieten. Back closes whatever's open, then hands back to the TV.
*/
@Composable
internal fun OrbiFaxScreen(load: () -> OrbiFaxData, onClose: () -> Unit) {
val zone = remember { ZoneId.systemDefault() }
val reduce = Motion.reduce
var data by remember { mutableStateOf<OrbiFaxData?>(null) }
LaunchedEffect(Unit) {
while (true) {
data = withContext(Dispatchers.Default) { runCatching(load).onFailure { android.util.Log.w("OrbiFax", "load failed=${it.javaClass.simpleName}") }.getOrNull() }
?: data ?: OrbiFaxData(emptyList(), emptyList(), emptyList(), emptyList(), emptyList(), kids = false)
delay(ORBI_FAX_REFRESH_MS)
}
}
val book = remember(data) { data?.let(::OrbiFaxPages) }
var nav by remember { mutableStateOf(OrbiFaxNav()) }
var nowMs by remember { mutableLongStateOf(System.currentTimeMillis()) }
LaunchedEffect(Unit) { while (true) { delay(1_000 - System.currentTimeMillis() % 1_000); nowMs = System.currentTimeMillis() } }
// The wizard's warning types itself out, unless Reduce motion is on.
var reveal by remember(nav.page) { mutableIntStateOf(if (reduce) Int.MAX_VALUE else 0) }
LaunchedEffect(nav.page, reduce) {
if (nav.page == ORBI_FAX_WIZARD_PAGE && !reduce) while (reveal < ORBI_FAX_WARNING.length) { delay(70); reveal++ }
}
LaunchedEffect(nav, book, reduce) {
val b = book ?: return@LaunchedEffect
if (!reduce && b.subPages(nav.page) > 1) { delay(ORBI_FAX_CAROUSEL_MS); nav = nav.turn(b) }
}
// Fixed buffers, made once: the page, its 240 x 250 dots and the bitmap they're copied into.
val page = remember { TeletextPage() }
val pixels = remember { IntArray(Teletext.WIDTH * Teletext.HEIGHT) }
val bitmap = remember { Bitmap.createBitmap(Teletext.WIDTH, Teletext.HEIGHT, Bitmap.Config.ARGB_8888) }
val image = remember(bitmap) { bitmap.asImageBitmap() }
val timer = remember { RenderTimer() }
val minute = nowMs / 60_000
remember(book, nav.page, nav.sub, reveal, minute) { book?.build(page, nav.page, nav.sub, nowMs, zone, reveal); 0 }
val stamp = remember(book, nav, reveal, nowMs) {
val b = book
if (b != null) {
val started = SystemClock.elapsedRealtimeNanos()
b.header(page, nav, nowMs, zone); b.fastext(page, nav)
TeletextRenderer.render(page, pixels)
bitmap.setPixels(pixels, 0, Teletext.WIDTH, 0, 0, Teletext.WIDTH, Teletext.HEIGHT)
timer.record(SystemClock.elapsedRealtimeNanos() - started)
}
nowMs + nav.hashCode() + reveal
}
val focus = remember { FocusRequester() }
LaunchedEffect(Unit) { focus.requestFocus() }
BackHandler { val b = book; val next = if (b == null) null else nav.press(OrbiFaxKey.Back, b); if (next == null) onClose() else nav = next }
var okDown by remember { mutableStateOf(false) }
BoxWithConstraints(Modifier.fillMaxSize().background(Brush.verticalGradient(listOf(MarginTop, MarginBottom)))
.focusRequester(focus).focusable().onPreviewKeyEvent { event ->
val native = event.nativeKeyEvent
val b = book ?: return@onPreviewKeyEvent native.keyCode != KeyEvent.KEYCODE_BACK
val ok = native.keyCode == KeyEvent.KEYCODE_DPAD_CENTER || native.keyCode == KeyEvent.KEYCODE_ENTER || native.keyCode == KeyEvent.KEYCODE_NUMPAD_ENTER
// OK acts on release, and only after its own press here, so the OK that opened Orbi-Fax doesn't also act on it.
if (ok) {
if (native.action == KeyEvent.ACTION_DOWN) okDown = true
else if (native.action == KeyEvent.ACTION_UP && okDown) { okDown = false; nav.press(OrbiFaxKey.Ok, b)?.let { nav = it } }
return@onPreviewKeyEvent true
}
if (native.action != KeyEvent.ACTION_DOWN) return@onPreviewKeyEvent native.keyCode != KeyEvent.KEYCODE_BACK
val key = when (native.keyCode) {
KeyEvent.KEYCODE_DPAD_UP -> OrbiFaxKey.Up
KeyEvent.KEYCODE_DPAD_DOWN -> OrbiFaxKey.Down
KeyEvent.KEYCODE_DPAD_LEFT -> OrbiFaxKey.Left
KeyEvent.KEYCODE_DPAD_RIGHT -> OrbiFaxKey.Right
KeyEvent.KEYCODE_CHANNEL_UP, KeyEvent.KEYCODE_PAGE_UP -> OrbiFaxKey.PageUp
KeyEvent.KEYCODE_CHANNEL_DOWN, KeyEvent.KEYCODE_PAGE_DOWN -> OrbiFaxKey.PageDown
KeyEvent.KEYCODE_PROG_RED -> OrbiFaxKey.Red
KeyEvent.KEYCODE_PROG_GREEN -> OrbiFaxKey.Green
KeyEvent.KEYCODE_PROG_YELLOW -> OrbiFaxKey.Yellow
KeyEvent.KEYCODE_PROG_BLUE -> OrbiFaxKey.Cyan
else -> null
}
when {
native.keyCode in KeyEvent.KEYCODE_0..KeyEvent.KEYCODE_9 -> nav = nav.digit(native.keyCode - KeyEvent.KEYCODE_0)
key != null -> nav.press(key, b)?.let { nav = it }
else -> return@onPreviewKeyEvent false
}
true
}) {
val pageHeight = maxHeight * (1000f / 1080f)
val pageWidth = pageHeight * 1.44f
val margin = (maxWidth - pageWidth) / 2
Row(Modifier.fillMaxSize(), verticalAlignment = Alignment.CenterVertically) {
Column(Modifier.width(margin).fillMaxHeight().padding(vertical = 40.dp), horizontalAlignment = Alignment.CenterHorizontally) {
Canvas(Modifier.size(72.dp)) {
drawCircle(MarginFocus, size.minDimension * .28f, style = Stroke(size.minDimension * .055f))
rotate(-25f) {
drawOval(Color.White, Offset(size.width * .04f, size.height * .39f), Size(size.width * .92f, size.height * .22f), style = Stroke(size.minDimension * .035f))
}
}
Text("Orbi-Fax", color = Color.White, fontSize = 20.sp, fontWeight = FontWeight.SemiBold)
Box(Modifier.padding(vertical = 6.dp).width(40.dp).height(2.dp).background(MarginOrange))
Text("channel 000", color = MarginMuted, fontSize = 12.sp)
}
Box(Modifier.width(pageWidth).height(pageHeight).background(MarginFrame).padding(2.dp)) {
Canvas(Modifier.fillMaxSize()) {
stamp // read, so a new page or second redraws
drawImage(image, IntOffset.Zero, IntSize(Teletext.WIDTH, Teletext.HEIGHT), IntOffset.Zero,
IntSize(size.width.toInt(), size.height.toInt()), filterQuality = FilterQuality.None)
}
}
Column(Modifier.weight(1f).fillMaxHeight().padding(vertical = 40.dp), horizontalAlignment = Alignment.CenterHorizontally) {
Text("P${nav.page}", color = MarginFocus, fontSize = 28.sp, fontWeight = FontWeight.SemiBold)
val count = book?.subPages(nav.page) ?: 1
if (count > 1) Text("${nav.sub.coerceIn(0, count - 1) + 1}/$count", color = MarginMuted, fontSize = 13.sp)
Spacer(Modifier.weight(1f))
listOf(Color(0xFFFF0000), Color(0xFF00FF00), Color(0xFFFFFF00), Color(0xFF00FFFF)).forEach { dot ->
Box(Modifier.padding(4.dp).size(12.dp).background(dot, CircleShape))
}
Text("OK links and pages", color = MarginMuted, fontSize = 11.sp, modifier = Modifier.padding(top = 8.dp))
Text("Back to the TV", color = MarginMuted, fontSize = 11.sp)
}
}
}
}