fix(tui): screen saver moves every element to prevent burn-in

The Bounce tiles panel, the clock/server/profile row and the lock line sat
still on an OLED/CRT. Now (burnin on, the default): the panel rides beside
the drifting logo on the side with room (alternating 20 s panel / 20 s
Query when both do not fit), the header and lock line change place every
30 s, the flip clock and its tiles drift, Big numbers changes corners, and
everything dims after 10 minutes (:saver burnin on|off, :saver dim
<minutes|off>, F9 Settings). The block-letter logo says the connected
profile's name (short name when 6 characters or fewer) with the server
host beneath, and the block font covers letters, digits - _ . with a
plain-text fallback.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
james.maesandClaude Fable 5.1 committed 2026-11-01 10:26:44 -06:00
1 parent bedbf69452
commit 899326a1c7
8 files changed
+640 -107

No files matched your search

+1
View File
@@ -287,6 +287,7 @@ in parentheses mark the changes made after the candidate.
### Fixed
- The screen saver moves every element so an OLED or CRT does not burn in: Bounce's tile panel rides beside the logo (the clock, server and lock lines used to sit still), the header and the lock line change place every 30 s, the flip clock drifts, Big numbers changes corners, and it dims after 10 minutes (`:saver burnin on|off`, `:saver dim <minutes|off>`); the block-letter logo now says the connected profile's name (short name up to 6 characters) with the server host beneath, instead of `qqq`.
- `qqq login --server URL` with `QQQ_PROFILE` (or `--profile`) naming an existing profile of another
server silently pointed that profile at the new server. It now warns and needs `--yes` (or a yes at the
question on a terminal); `--profile <new-name>` adds a profile instead. A token refresh under a one-off
+23 -8
View File
@@ -371,7 +371,7 @@ drives it in tmux at 80x24 and 120x36 against a server with the extension (defau
TUI commands: `home`, `back`, `quit`, `reset`, `refresh`, `help`, `helpkeys`, `menu`, `search <text>` (also `find`, `goto`, `palette`), `view`,
`views`, `share`, `actions`, `audits`, `dev`, `tags`, `report run <name>`, `theme <name>`, `ascii on|off`,
`linear on|off`, `shortcuts on|off`, `dates [order ymd|mdy|dmy] [clock 24h|12h] [week monday|sunday] [weeknumbers on|off] [enter picker|next]`, `lock`, `saver [style|style <s>|refresh <s>|tables <a,b>]`, `pin`, `pin remove`, `idle <minutes>`, `filter [clear|<grammar>]`,
`linear on|off`, `shortcuts on|off`, `dates [order ymd|mdy|dmy] [clock 24h|12h] [week monday|sunday] [weeknumbers on|off] [enter picker|next]`, `lock`, `saver [style|style <s>|refresh <s>|tables <a,b>|burnin on|off|dim <minutes|off>]`, `pin`, `pin remove`, `idle <minutes>`, `filter [clear|<grammar>]`,
`export <format>`, `jobs`, `profile [name]`, `servers`, `server <url>`, `signout`, `connection`, `doctor`, `open <table>`,
`app <name>`, `record <table> <key>`, `sql [statement | open <id>]`. Tab on an empty line lists every
command with a one-line description; after a command it lists its arguments (tables, processes, apps,
@@ -405,12 +405,27 @@ the plain sample server; one that fails shows `…`, then its last value dimmed
| *table* | — | record counts of up to three favourite tables: `:saver tables person,order` (per profile) |
Styles (F9 › Settings › Screen saver style, `:saver style <s>`; `auto` cycles every three minutes):
**Bounce** (Query, the qrun.io mascot, and the `qqq` logo drift DVD-style and change colour at every
wall, tiles in a corner), **Starfield** (stars fly out of the centre, Query drifts through, the tiles
float), **Flip clock** (big flip digits, the date and server, tiles beneath, Query peeking from a corner)
and **Big numbers** (the most interesting metric in block digits beside Query, rotating every 8 s). The
clock, server and profile stay on the top row. Query blinks, wags and hops every ten seconds and faces the
way he drifts; the art (braille, with a line-art version for `--ascii`) is in `src/saver/query-art.ts`.
**Bounce** (Query, the qrun.io mascot, and the name of the profile you are connected to in block letters
drift DVD-style and change colour at every wall, with the tiles in a panel riding beside them),
**Starfield** (stars fly out of the centre, Query drifts through, the tiles float), **Flip clock** (big
flip digits, the date and server, tiles beneath, Query peeking from a corner) and **Big numbers** (the most
interesting metric in block digits beside Query, rotating every 8 s). The block letters say the profile's
short name when it has 6 characters or fewer (else the profile name), with the server host in plain text
beneath; letters, digits, `-`, `_` and `.` are drawn in block letters, anything else falls back to plain
text. Query blinks, wags and hops every ten seconds and faces the way he drifts; the art (braille, with a
line-art version for `--ascii`) is in `src/saver/query-art.ts`.
Burn-in guard (F9 › Settings › Screen saver burn-in guard, `:saver burnin on|off`, default on): nothing
stays put, so an OLED or CRT does not keep a ghost of the saver. The clock · server · profile line and the
"locked · any key to unlock" line move to a new place every 30 s (a random column, the top and bottom rows
swapping); Bounce's tile panel follows the logo, on the side with room (if Query and the panel do not fit
together, the panel shows for 20 s and then Query for 20 s, both drifting); the flip clock's cards and tiles
drift a cell every few seconds inside a small box; Big numbers moves to another corner at each rotation;
Starfield's tiles keep floating. The clock stays visible throughout. `off` keeps the fixed layout (clock
and server on the top row, the hint on the last, tiles in the bottom-right corner).
Dimming (F9 › Settings › Screen saver dim, `:saver dim <minutes|off>`, default 10): once the saver has been
up that long, every colour fades toward the background. Both settings are saved in the `saver` section.
Animation runs at 4 frames a second at most and about one when nothing moves; only the saver repaints.
## Large instances
@@ -439,7 +454,7 @@ Everything below is local to the machine and shared with the CLI; nothing is sen
`app:<name>` widget order; `widget:<name>` dropdown choices of widgets that ask to keep them.
- `ui.files`: download and upload folders and whether a download asks or saves silently.
- `ui.lock`: the screen-lock PIN (a salted hash, never the PIN) and the idle minutes (0 = off).
- `saver`: the screen saver style and refresh seconds; `profiles.<name>.saver.tables`: favourite tables.
- `saver`: the screen saver style, refresh seconds, `burnin` (default on) and `dimMinutes` (default 10, 0 off); `profiles.<name>.saver.tables`: favourite tables.
- `ui.doctor`: the answers to the terminal check; `ui.recents`: recently viewed, per server.
- `~/.local/state/qqq/` (`QQQ_STATE_DIR`): the `:` and filter histories (`history-commands`,
`history-filters`); lines that look like secrets are not kept.
+51 -7
View File
@@ -14,15 +14,15 @@
*/
import { useEffect, useReducer } from 'react'
import { hasPin, readRecents } from '@qrun-io/qqq-core'
import { hasPin, readConfig, readRecents, shortNameOf } from '@qrun-io/qqq-core'
import type { Key } from '../keys'
import type { AppStore } from '../store'
import { glyphs, isAscii, theme } from '../theme'
import type { MenuEntry, Overlay } from '../types'
import { paintSaver, nextFrameDelay, styleAt, type SaverInput } from '../saver/layout'
import { paintSaver, nextFrameDelay, isDimmed, styleAt, type SaverInput } from '../saver/layout'
import { TileModel, realtimeEvents } from '../saver/model'
import { saverSources, type SaverContext } from '../saver/sources'
import { REFRESH_CHOICES, SAVER_STYLES, STYLE_LABELS, isStyle, readSaverSettings, writeSaverSettings, type SaverSettings, type SaverStyle, type SaverStyleSetting } from '../saver/settings'
import { DIM_CHOICES, REFRESH_CHOICES, SAVER_STYLES, STYLE_LABELS, isStyle, readSaverSettings, writeSaverSettings, type SaverSettings, type SaverStyle, type SaverStyleSetting } from '../saver/settings'
import { ChoiceOverlay, overlayId } from './basic'
import { LockOverlay } from './center'
@@ -34,11 +34,15 @@ export class SaverOverlay implements Overlay {
readonly settings: SaverSettings
readonly model: TileModel
private readonly lock: LockOverlay
/** When the saver came up (the dim counts from here). */
readonly startedAt = Date.now()
private readonly shortName: string | undefined
/** `preview`: shown by `:saver` (a style, or the setting): any key returns, no PIN. */
constructor(private store: AppStore, readonly preview?: SaverStyleSetting) {
this.settings = readSaverSettings(this.profile())
this.lock = new LockOverlay(store)
this.shortName = this.profileShortName()
this.model = new TileModel(store.client ? saverSources(this.context()) : [], { intervalMs: this.settings.refreshSeconds * 1000 })
}
@@ -46,6 +50,17 @@ export class SaverOverlay implements Overlay {
return this.store.status.profile || this.store.target?.name || undefined
}
/** The profile's short name (what the block-letter logo says), if there is a profile. */
private profileShortName(): string | undefined {
const name = this.profile()
if (!name) return undefined
try {
return shortNameOf(name, readConfig().profiles[name])
} catch {
return undefined
}
}
private context(): SaverContext {
const s = this.store
const client = s.client!
@@ -117,6 +132,7 @@ export class SaverOverlay implements Overlay {
profile: s.status.profile || s.target?.name || '',
brand: (s.meta?.branding as { appName?: string } | undefined)?.appName ?? 'QQQ',
ascii: isAscii(), theme: theme(), ramp: glyphs().spark,
shortName: this.shortName, burnin: this.settings.burnin, dim: isDimmed(now - this.startedAt, this.settings.dimMinutes),
locked: !this.preview && hasPin(), preview: Boolean(this.preview),
pin: !this.preview && this.lock.asking ? { length: this.lock.pin.value.length, message: this.lock.message } : undefined,
}
@@ -148,7 +164,7 @@ function SaverView({ saver, width, height }: { saver: SaverOverlay; width: numbe
)
}
/** `:saver` arguments: a style to preview, `style <s>`, `refresh <seconds>`, `tables <a,b>`. */
/** `:saver` arguments: a style to preview, `style <s>`, `refresh <seconds>`, `tables <a,b>`, `burnin on|off`, `dim <minutes|off>`. */
export function saverCommand(store: AppStore, args: string[], fail: (text: string) => void): void {
const [first, ...rest] = args
const profile = store.status.profile || store.target?.name
@@ -174,13 +190,25 @@ export function saverCommand(store: AppStore, args: string[], fail: (text: strin
writeSaverSettings({ tables }, profile)
return store.flash(tables.length ? `screen saver counts ${tables.slice(0, 3).join(', ')} for this profile` : 'screen saver table counts off')
}
fail('saver [auto|bounce|starfield|flip|big] previews · saver style <s> · saver refresh <seconds> · saver tables <a,b>')
if (first === 'burnin') {
if (rest[0] !== 'on' && rest[0] !== 'off') return fail('saver burnin on|off: on moves every element so nothing burns in')
writeSaverSettings({ burnin: rest[0] === 'on' })
return store.flash(`screen saver burn-in guard ${rest[0]} (saved)`)
}
if (first === 'dim') {
const n = rest[0] === 'off' ? 0 : Number(rest[0])
if (rest[0] !== 'off' && (!Number.isFinite(n) || n < 1)) return fail('saver dim <minutes|off>: dim the saver after this many minutes')
writeSaverSettings({ dimMinutes: n })
const minutes = readSaverSettings(profile).dimMinutes
return store.flash(minutes ? `screen saver dims after ${minutes} min (saved)` : 'screen saver dimming off (saved)')
}
fail('saver [auto|bounce|starfield|flip|big] previews · saver style <s> · saver refresh <seconds> · saver tables <a,b> · saver burnin on|off · saver dim <minutes|off>')
}
/** Completions for `:saver …`. */
export const SAVER_WORDS = ['auto', ...SAVER_STYLES, 'style', 'refresh', 'tables']
export const SAVER_WORDS = ['auto', ...SAVER_STYLES, 'style', 'refresh', 'tables', 'burnin', 'dim']
/** The Settings entries of the F9 menu: style, refresh interval, preview. */
/** The Settings entries of the F9 menu: style, refresh interval, burn-in guard, dim, preview. */
export function saverMenuEntries(store: AppStore): MenuEntry[] {
const profile = store.status.profile || store.target?.name
const current = readSaverSettings(profile)
@@ -200,6 +228,22 @@ export function saverMenuEntries(store: AppStore): MenuEntry[] {
store.flash(`screen saver tiles refresh every ${n} s (saved)`)
}, 'Enter chooses', Math.max(0, (REFRESH_CHOICES as readonly number[]).indexOf(current.refreshSeconds)))),
},
{
section: 'Settings', label: `Screen saver burn-in guard: ${current.burnin ? 'on' : 'off'}`, command: 'saver burnin on|off',
run: () => store.open(new ChoiceOverlay<boolean>(store, 'Move every element of the screen saver so nothing burns in', [
{ label: 'On: everything drifts', value: true }, { label: 'Off: fixed layout', value: false },
], (v) => {
writeSaverSettings({ burnin: v })
store.flash(`screen saver burn-in guard ${v ? 'on' : 'off'} (saved)`)
}, 'Enter chooses', current.burnin ? 0 : 1)),
},
{
section: 'Settings', label: `Screen saver dim: ${current.dimMinutes ? `after ${current.dimMinutes} min` : 'off'}`, command: 'saver dim <minutes|off>',
run: () => store.open(new ChoiceOverlay<number>(store, 'Dim the screen saver after', DIM_CHOICES.map((n) => ({ label: n ? `${n} minutes` : 'never', value: n })), (n) => {
writeSaverSettings({ dimMinutes: n })
store.flash(n ? `screen saver dims after ${n} min (saved)` : 'screen saver dimming off (saved)')
}, 'Enter chooses · :saver dim <minutes|off> for another time', Math.max(0, (DIM_CHOICES as readonly number[]).indexOf(current.dimMinutes)))),
},
{ section: 'Settings', label: 'Preview the screen saver', command: 'saver', run: () => saverCommand(store, [], (t) => store.flash(t, 'error')) },
]
}
+22
View File
@@ -71,6 +71,17 @@ export class Canvas {
return { x: x + 1, y: y + 1, w: Math.max(0, w - 2), h: Math.max(0, h - 2) }
}
/** Dims everything: each colour moves `amount` (0…1) of the way to the background (burn-in guard). */
dim(amount: number): void {
const bg = this.base.bg
for (const row of this.cells) {
for (const cell of row) {
cell.fg = mix(cell.fg ?? this.base.fg, cell.bg ?? bg, amount)
cell.bg = mix(cell.bg ?? bg, bg, amount)
}
}
}
/** The grid as text (tests, captures). */
text(): string {
return this.cells.map((r) => r.map((c) => c.ch).join('')).join('\n')
@@ -87,3 +98,14 @@ export class Canvas {
return out
}
}
/** `#rrggbb` colours blended; anything else (named colours, undefined) stays as it is. */
function mix(from: string | undefined, to: string | undefined, amount: number): string | undefined {
const a = /^#([0-9a-f]{6})$/i.exec(from ?? '')
const b = /^#([0-9a-f]{6})$/i.exec(to ?? '')
if (!a || !b) return from
const channel = (hex: string, i: number) => parseInt(hex.slice(i * 2, i * 2 + 2), 16)
let out = '#'
for (let i = 0; i < 3; i++) out += Math.round(channel(a[1]!, i) + (channel(b[1]!, i) - channel(a[1]!, i)) * amount).toString(16).padStart(2, '0')
return out
}
+39 -6
View File
@@ -3,7 +3,10 @@
* Licensed under the Apache License, Version 2.0 (see LICENSE).
*/
/** A 5-row block font for the screen saver: digits, the clock's colon, a few signs and `q`. */
/**
* A 5-row block font for the screen saver: letters (either case), digits, the clock's colon and
* `. , - _ / % …`. A name with any other character is drawn as plain text instead (`canDraw`).
*/
const GLYPHS: Record<string, string[]> = {
'0': ['####', '#..#', '#..#', '#..#', '####'],
@@ -27,6 +30,31 @@ const GLYPHS: Record<string, string[]> = {
'q': ['....', '####', '#..#', '####', '...#'],
'…': ['.....', '.....', '.....', '.....', '#.#.#'],
'?': ['###', '..#', '.##', '...', '.#.'],
'a': ['.##.', '#..#', '####', '#..#', '#..#'],
'b': ['###.', '#..#', '###.', '#..#', '###.'],
'c': ['.###', '#...', '#...', '#...', '.###'],
'd': ['###.', '#..#', '#..#', '#..#', '###.'],
'e': ['####', '#...', '###.', '#...', '####'],
'f': ['####', '#...', '###.', '#...', '#...'],
'g': ['.###', '#...', '#.##', '#..#', '.###'],
'h': ['#..#', '#..#', '####', '#..#', '#..#'],
'i': ['###', '.#.', '.#.', '.#.', '###'],
'j': ['..##', '...#', '...#', '#..#', '.##.'],
'l': ['#...', '#...', '#...', '#...', '####'],
'm': ['#...#', '##.##', '#.#.#', '#...#', '#...#'],
'n': ['#..#', '##.#', '#.##', '#..#', '#..#'],
'o': ['.##.', '#..#', '#..#', '#..#', '.##.'],
'p': ['###.', '#..#', '###.', '#...', '#...'],
'r': ['###.', '#..#', '###.', '#.#.', '#..#'],
's': ['.###', '#...', '.##.', '...#', '###.'],
't': ['####', '.#..', '.#..', '.#..', '.#..'],
'u': ['#..#', '#..#', '#..#', '#..#', '.##.'],
'v': ['#..#', '#..#', '#..#', '.##.', '..#.'],
'w': ['#...#', '#...#', '#.#.#', '##.##', '#...#'],
'x': ['#..#', '#..#', '.##.', '#..#', '#..#'],
'y': ['#..#', '#..#', '.##.', '..#.', '..#.'],
'z': ['####', '...#', '.##.', '#...', '####'],
'_': ['....', '....', '....', '....', '####'],
' ': ['..', '..', '..', '..', '..'],
}
@@ -34,22 +62,27 @@ export const FONT_HEIGHT = 5
/** Whether the block font can draw every character of the text. */
export function canDraw(text: string): boolean {
return [...text].every((c) => c in GLYPHS)
return [...text].every((c) => glyph(c))
}
/** A character's glyph; letters fall back to lower case (`M` has its own, for millions). */
function glyph(c: string): string[] | undefined {
return GLYPHS[c] ?? GLYPHS[c.toLowerCase()]
}
/** Cells wide the text takes in the block font (one blank column between glyphs). */
export function blockWidth(text: string): number {
const chars = [...text].filter((c) => c in GLYPHS)
return chars.reduce((w, c) => w + GLYPHS[c]![0]!.length, 0) + Math.max(0, chars.length - 1)
const chars = [...text].filter((c) => glyph(c))
return chars.reduce((w, c) => w + glyph(c)![0]!.length, 0) + Math.max(0, chars.length - 1)
}
/** The text in block letters: 5 rows, `█` (or `#` for the ASCII glyph set) on spaces. */
export function blockText(text: string, ascii = false): string[] {
const on = ascii ? '#' : '█'
const rows = ['', '', '', '', '']
const chars = [...text].filter((c) => c in GLYPHS)
const chars = [...text].filter((c) => glyph(c))
chars.forEach((c, i) => {
const g = GLYPHS[c]!
const g = glyph(c)!
for (let r = 0; r < FONT_HEIGHT; r++) rows[r] += g[r]!.replace(/#/g, on).replace(/\./g, ' ') + (i < chars.length - 1 ? ' ' : '')
})
return rows
+247 -76
View File
@@ -5,11 +5,16 @@
/**
* Paints one frame of the screen saver into a Canvas. Pure: the same input (time, size, tiles)
* gives the same frame, so every style is testable at 80×24 and 120×40. Every style keeps the
* clock, the server's short name and the profile on the top row and the wake hint on the last.
* gives the same frame, so every style is testable at 80×24 and 120×40. Every style shows the
* clock, the server's short name and the profile in one row and the wake hint in another.
*
* Styles: bounce (Query and the qqq logo drift DVD-style and change colour at each wall, tiles in
* a corner HUD), starfield (stars fly out of the centre, Query drifts through, the tiles float),
* Burn-in guard (on by default, `burnin off` restores the fixed layout): nothing stays put. The
* header and the lock line change place every 30 s (a new x, the top and bottom rows swapping),
* Bounce's tiles ride beside the logo, the flip clock drifts a cell every few seconds, Big numbers
* moves to another corner at each rotation, and after the configured minutes everything dims.
*
* Styles: bounce (Query and the profile's name in block letters drift DVD-style and change colour at each wall, tiles in
* a HUD beside them), starfield (stars fly out of the centre, Query drifts through, the tiles float),
* flip (big flip-clock digits with the date, tiles beneath, Query peeking from a corner), big (the
* most interesting metric in block digits beside Query, rotating every 8 s).
*/
@@ -46,6 +51,22 @@ export interface SaverInput {
pin?: { length: number; message: string }
/** The sparkline ramp of the glyph set. */
ramp: string
/** The profile's short name (the block-letter logo when it has 6 characters or fewer). */
shortName?: string
/** Burn-in guard: every element drifts. Off: the fixed layout. */
burnin: boolean
/** Draw everything dimmed (the saver has been up for the configured minutes). */
dim: boolean
}
/** How often the header and the lock line change place. */
export const SHIFT_MILLIS = 30_000
/** The dim: how far every colour moves toward the background. */
export const DIM_AMOUNT = 0.45
/** Whether the saver has been up long enough to dim (`dimMinutes` 0: never). */
export function isDimmed(shownMillis: number, dimMinutes: number): boolean {
return dimMinutes > 0 && shownMillis >= dimMinutes * 60_000
}
/** How long each style shows in auto mode. */
@@ -125,24 +146,60 @@ function drawHud(c: Canvas, x: number, y: number, w: number, h: number, input: S
input.tiles.slice(0, inner.h).forEach((tile, i) => tileLine(c, inner.x + 1, inner.y + i, inner.w - 2, tile, input, t.overlayBg))
}
function header(c: Canvas, input: SaverInput): void {
const t = input.theme
const d = new Date(input.now)
const clock = d.toLocaleTimeString('en-GB')
const left = ` ${clock} ${input.server} · ${input.profile}`
const right = `${input.brand} `
c.put(0, 0, pad(left, input.width), { fg: t.fg, bold: true })
if (left.length + right.length + 2 <= input.width) c.put(input.width - right.length, 0, right, { fg: t.acc })
c.put(1, 0, clock, { fg: t.acc2, bold: true })
/** Where the header and the lock line are drawn: fixed, or (burn-in guard) moved every 30 s. */
export interface ChromeLayout {
headerRow: number
headerX: number
headerText: string
footerRow: number
footerX: number
footerText: string
}
function footer(c: Canvas, input: SaverInput): void {
const t = input.theme
function footerText(input: SaverInput): string {
const hint = input.preview
? `preview: ${input.style} · any key returns · :saver bounce | starfield | flip | big`
: input.locked ? 'locked · any key to unlock' : 'any key returns'
const text = trunc(hint, input.width - 2)
c.put(Math.max(0, Math.floor((input.width - text.length) / 2)), input.height - 1, text, { fg: t.dim })
return trunc(hint, input.width - 2)
}
export function chromeLayout(input: SaverInput): ChromeLayout {
const clock = new Date(input.now).toLocaleTimeString('en-GB')
const last = input.height - 1
if (!input.burnin) {
return { headerRow: 0, headerX: 0, headerText: ` ${clock} ${input.server} · ${input.profile}`, footerRow: last, footerX: -1, footerText: footerText(input) }
}
const cycle = Math.floor(input.now / SHIFT_MILLIS)
const headerText = trunc(`${clock} ${input.server} · ${input.profile} · ${input.brand}`, input.width)
const text = footerText(input)
const even = cycle % 2 === 0
return {
headerRow: even ? 0 : last,
headerX: Math.floor(rand(cycle * 2.7 + 1) * (input.width - headerText.length + 1)),
headerText,
footerRow: even ? last : 0,
footerX: Math.floor(rand(cycle * 3.1 + 2) * (input.width - text.length + 1)),
footerText: text,
}
}
function header(c: Canvas, input: SaverInput, at: ChromeLayout): void {
const t = input.theme
if (input.burnin) {
c.put(at.headerX, at.headerRow, at.headerText, { fg: t.fg, bold: true })
c.put(at.headerX, at.headerRow, at.headerText.slice(0, 8), { fg: t.acc2, bold: true })
return
}
const clock = new Date(input.now).toLocaleTimeString('en-GB')
const right = `${input.brand} `
c.put(0, 0, pad(at.headerText, input.width), { fg: t.fg, bold: true })
if (at.headerText.length + right.length + 2 <= input.width) c.put(input.width - right.length, 0, right, { fg: t.acc })
c.put(1, 0, clock, { fg: t.acc2, bold: true })
}
function footer(c: Canvas, input: SaverInput, at: ChromeLayout): void {
const x = input.burnin ? at.footerX : Math.max(0, Math.floor((input.width - at.footerText.length) / 2))
c.put(x, at.footerRow, at.footerText, { fg: input.theme.dim })
}
function drawPin(c: Canvas, input: SaverInput): void {
@@ -162,15 +219,115 @@ function palette(t: ThemeTokens): string[] {
return [t.acc, t.acc2, t.ok, t.warn, t.markFg, t.err]
}
/** Query and, when there is room, the qqq logo: the sprite the Bounce style drifts. */
function bounceSprite(bodyH: number, width: number): { w: number; h: number; size: 'large' | 'small'; logo: 'block' | 'line' | 'none' } {
/** The block-letter logo under Query: the profile's name, with the server host beneath. */
interface NameLogo {
rows: string[]
/** Drawn in block letters (else plain text). */
block: boolean
host: string
w: number
}
/** The short name when it has 6 characters or fewer, else the profile name; block letters when the font covers it and it fits. */
export function logoName(input: SaverInput): string {
const short = input.shortName
return (short && short.length <= 6 ? short : input.profile) || short || 'qqq'
}
function nameLogo(input: SaverInput): NameLogo {
const name = logoName(input)
const block = canDraw(name) && blockWidth(name) <= input.width - 4
const rows = block ? blockText(name, input.ascii) : [trunc(name, input.width - 4)]
const host = trunc(input.server, input.width - 2)
return { rows, block, host, w: Math.max(host.length, ...rows.map((r) => [...r].length)) }
}
export interface Box {
x: number
y: number
w: number
h: number
}
interface BounceSprite {
w: number
h: number
size: 'large' | 'small'
logo: boolean
}
/** Query with the name logo under him when there is room (large Query only when it all fits). */
function bounceSprite(bodyH: number, width: number, logo: NameLogo): BounceSprite {
const large = querySize('large')
const small = querySize('small')
const logoW = blockWidth('qqq')
if (bodyH >= large.height + 1 + FONT_HEIGHT && width >= large.width + 4) return { w: large.width, h: large.height + 1 + FONT_HEIGHT, size: 'large', logo: 'block' }
if (bodyH >= large.height + 1 && width >= large.width + 4) return { w: large.width, h: large.height + 1, size: 'large', logo: 'line' }
if (bodyH >= FONT_HEIGHT + 1 + small.height) return { w: Math.max(small.width, logoW), h: small.height + 1 + FONT_HEIGHT, size: 'small', logo: 'block' }
return { w: small.width, h: small.height, size: 'small', logo: 'none' }
const extra = 2 + logo.rows.length
if (bodyH >= large.height + extra && width >= Math.max(large.width, logo.w) + 4) return { w: Math.max(large.width, logo.w), h: large.height + extra, size: 'large', logo: true }
if (bodyH >= small.height + extra) return { w: Math.min(width, Math.max(small.width, logo.w)), h: small.height + extra, size: 'small', logo: true }
return { w: small.width, h: small.height, size: 'small', logo: false }
}
/** The narrowest tile panel worth drawing beside the logo. */
const MIN_PANEL = 22
/** Too small for Query and the panel together: each shows for this long, alternating. */
export const ALTERNATE_MILLIS = 20_000
/**
* The tile panel beside the sprite: full width on the side with room (right first); where neither
* side has it, a compact one (a constant width, so its near edge always follows the logo). None when
* even that is too narrow.
*/
function panelBeside(sprite: Box, hudW: number, hudH: number, width: number, top: number, bodyH: number): Box | undefined {
const right = width - (sprite.x + sprite.w) - 1
const left = sprite.x - 1
const compact = Math.min(hudW, Math.floor((width - sprite.w - 2) / 2))
if (compact < Math.min(MIN_PANEL, hudW)) return undefined
const w = right >= hudW || left >= hudW ? hudW : compact
const useRight = right >= w
return { x: useRight ? sprite.x + sprite.w + 1 : sprite.x - 1 - w, y: Math.max(top, Math.min(sprite.y, top + bodyH - hudH)), w, h: hudH }
}
export interface BounceLayout {
sprite: Box
/** The sprite is drawn (false in the panel half of the alternation). */
showSprite: boolean
panel?: Box
size: 'large' | 'small'
showLogo: boolean
dx: 1 | -1
dy: 1 | -1
walls: number
}
/** Where Bounce puts everything this frame (exported for the tests). */
export function bounceLayout(input: SaverInput): BounceLayout {
const top = 1
const bodyH = input.height - 2
const sprite = bounceSprite(bodyH, input.width, nameLogo(input))
const hud = hudSize(input, input.width - 2, bodyH)
const step = Math.floor(input.now / FRAME_MILLIS)
const ystep = Math.floor(step / 2)
const maxX = Math.max(0, input.width - sprite.w)
const maxY = Math.max(0, bodyH - sprite.h)
const box: Box = { x: bounce(step, maxX), y: top + bounce(ystep, maxY), w: sprite.w, h: sprite.h }
const base = {
size: sprite.size, showLogo: sprite.logo, dx: direction(step, maxX), dy: direction(ystep, maxY),
// a new colour at each wall, as the DVD logo did
walls: (maxX ? Math.floor(step / maxX) : 0) + (maxY ? Math.floor(ystep / maxY) : 0),
}
const hasPanel = hud.h >= 3 && hud.w >= 12
if (!input.burnin || !hasPanel) {
return { ...base, sprite: box, showSprite: true, panel: hasPanel ? { x: input.width - hud.w - 1, y: top + bodyH - hud.h, w: hud.w, h: hud.h } : undefined }
}
if (Math.floor((input.width - sprite.w - 2) / 2) >= Math.min(MIN_PANEL, hud.w)) {
const panel = panelBeside(box, hud.w, hud.h, input.width, top, bodyH)
if (panel) return { ...base, sprite: box, showSprite: true, panel }
}
// too small for both: the panel for 20 s, then Query for 20 s, each drifting
if (Math.floor(input.now / ALTERNATE_MILLIS) % 2 === 0) {
const panel = { x: bounce(step, Math.max(0, input.width - hud.w)), y: top + bounce(ystep, Math.max(0, bodyH - hud.h)), w: hud.w, h: hud.h }
return { ...base, sprite: box, showSprite: false, panel }
}
return { ...base, sprite: box, showSprite: true }
}
function drawQuery(c: Canvas, x: number, y: number, size: 'large' | 'small', pose: QueryPose, input: SaverInput, color: string): void {
@@ -180,40 +337,30 @@ function drawQuery(c: Canvas, x: number, y: number, size: 'large' | 'small', pos
function paintBounce(c: Canvas, input: SaverInput): void {
const t = input.theme
const top = 1
const bodyH = input.height - 2
const sprite = bounceSprite(bodyH, input.width)
const maxX = Math.max(0, input.width - sprite.w)
const maxY = Math.max(0, bodyH - sprite.h)
const step = Math.floor(input.now / FRAME_MILLIS)
const ystep = Math.floor(step / 2)
const x = bounce(step, maxX)
const y = top + bounce(ystep, maxY)
const dx = direction(step, maxX)
const dy = direction(ystep, maxY)
// a new colour at each wall, as the DVD logo did
const walls = (maxX ? Math.floor(step / maxX) : 0) + (maxY ? Math.floor(ystep / maxY) : 0)
const colors = palette(t)
const color = colors[walls % colors.length]!
const pose = queryPoseAt(input.now, { dx, dy })
const q = querySize(sprite.size)
const qx = x + Math.floor((sprite.w - q.width) / 2)
const qy = y + (pose.dy < 0 && y > top ? -1 : 0)
drawQuery(c, qx, qy, sprite.size, pose, input, color)
if (pose.action) {
const bubble = 'woof!'
const bx = pose.facing === 'right' ? qx + q.width - 2 : qx - bubble.length + 2
c.put(Math.min(Math.max(0, bx), input.width - bubble.length), Math.max(top, qy - 1), bubble, { fg: t.acc2, bold: true })
const layout = bounceLayout(input)
const { sprite: box } = layout
if (layout.showSprite) {
const colors = palette(t)
const color = colors[layout.walls % colors.length]!
const pose = queryPoseAt(input.now, { dx: layout.dx, dy: layout.dy })
const q = querySize(layout.size)
const qx = box.x + Math.floor((box.w - q.width) / 2)
const qy = box.y + (pose.dy < 0 && box.y > top ? -1 : 0)
drawQuery(c, qx, qy, layout.size, pose, input, color)
if (pose.action) {
const bubble = 'woof!'
const bx = pose.facing === 'right' ? qx + q.width - 2 : qx - bubble.length + 2
c.put(Math.min(Math.max(0, bx), input.width - bubble.length), Math.max(top, qy - 1), bubble, { fg: t.acc2, bold: true })
}
if (layout.showLogo) {
const logo = nameLogo(input)
const ly = box.y + q.height + 1
const rowsW = Math.max(...logo.rows.map((r) => [...r].length))
c.block(box.x + Math.floor((box.w - rowsW) / 2), ly, logo.rows, { fg: color, bold: !logo.block })
c.put(box.x + Math.floor((box.w - logo.host.length) / 2), ly + logo.rows.length, logo.host, { fg: t.dim })
}
}
const logoY = y + q.height + 1
if (sprite.logo === 'block') {
const logo = blockText('qqq', input.ascii)
c.block(x + Math.floor((sprite.w - blockWidth('qqq')) / 2), logoY, logo, { fg: color })
} else if (sprite.logo === 'line') {
const name = 'q q q'
c.put(x + Math.floor((sprite.w - name.length) / 2), y + q.height, name, { fg: color, bold: true })
}
const hud = hudSize(input, input.width - 2, bodyH)
drawHud(c, input.width - hud.w - 1, top + bodyH - hud.h, hud.w, hud.h, input)
if (layout.panel) drawHud(c, layout.panel.x, layout.panel.y, layout.panel.w, layout.panel.h, input)
}
/** A deterministic 0…1 value for a seed (the star field). */
@@ -270,6 +417,11 @@ function hhmm(at: number): string {
return `${String(d.getHours()).padStart(2, '0')}${String(d.getMinutes()).padStart(2, '0')}`
}
/** A slow drift: one cell every `periodMs`, back and forth over −r…r (0 when the guard is off or there is no slack). */
function drift(input: SaverInput, periodMs: number, r: number): number {
return input.burnin && r > 0 ? bounce(Math.floor(input.now / periodMs), 2 * r) - r : 0
}
function paintFlip(c: Canvas, input: SaverInput): void {
const t = input.theme
const bodyH = input.height - 2
@@ -286,8 +438,12 @@ function paintFlip(c: Canvas, input: SaverInput): void {
const gap = 1
const colonW = 1 + 2 * scale
const total = cardW * 4 + gap * 2 + colonW
const x0 = Math.max(0, Math.floor((input.width - total) / 2))
const y0 = 1 + Math.max(0, Math.floor((bodyH - (cardH + 4 + tileRows)) / 2))
const slackY = bodyH - (cardH + 4 + tileRows)
const x0 = Math.max(0, Math.floor((input.width - total) / 2) + drift(input, 4000, Math.min(4, Math.floor((input.width - total) / 2))))
const y0 = 1 + Math.max(0, Math.floor(slackY / 2) + drift(input, 7000, slackY >= 2 ? 1 : 0))
// the tiles and Query shift too, inside the room each keeps clear of the other
const tileShift = input.burnin ? bounce(Math.floor(input.now / 5000), 3) : 0
const queryShift = input.burnin ? bounce(Math.floor(input.now / 6000), 3) : 0
const positions = [x0, x0 + cardW + gap, x0 + cardW * 2 + gap + colonW, x0 + cardW * 3 + gap * 2 + colonW]
const big = (ch: string) => blockText(ch, input.ascii).flatMap((r) => new Array<string>(scale).fill([...r].map((x) => x.repeat(scale)).join('')))
for (let i = 0; i < 4; i++) {
@@ -318,27 +474,30 @@ function paintFlip(c: Canvas, input: SaverInput): void {
let y = y0 + cardH + 1
for (const [text, style] of [[date, { fg: t.acc, bold: true }], [`${input.server} · ${input.profile}`, { fg: t.dim }]] as Array<[string, Style]>) {
const s = trunc(text, input.width - 2)
c.put(Math.floor((input.width - s.length) / 2), y++, s, style)
c.put(Math.floor((input.width - s.length) / 2) + (x0 - Math.max(0, Math.floor((input.width - total) / 2))), y++, s, style)
}
y++
// the tiles beneath (two columns when wide); the right edge stays clear for Query
const colW = Math.floor((input.width - 4 - querySize('small').width - 2 - (columns - 1) * 3) / columns)
const colW = Math.floor((input.width - 4 - querySize('small').width - 2 - (columns - 1) * 3 - (input.burnin ? 3 : 0)) / columns)
const rows = Math.max(0, input.height - 1 - y)
input.tiles.slice(0, rows * columns).forEach((tile, i) => {
const col = columns === 2 ? i % 2 : 0
const row = columns === 2 ? Math.floor(i / 2) : i
tileLine(c, 2 + col * (colW + 3), y + row, colW, tile, input)
tileLine(c, 2 + tileShift + col * (colW + 3), y + row, colW, tile, input)
})
// Query peeks up from the bottom-right corner: ears and eyes, all of him when he hops
const q = querySize('small')
const pose = queryPoseAt(input.now, { dx: -1 })
const shown = pose.action ? q.height : 3
const frame = queryFrame('small', pose, input.ascii).slice(0, shown)
const qx = input.width - q.width - 1
const qx = input.width - q.width - 1 - queryShift
c.fill(qx, input.height - 1 - shown, q.width, shown, {})
c.block(qx, input.height - 1 - shown, frame, { fg: t.acc2, bold: true })
}
/** Where Big numbers puts its group at each rotation (right?, bottom?): the four corners in a zig-zag. */
const BIG_CORNERS: ReadonlyArray<readonly [boolean, boolean]> = [[false, false], [true, true], [true, false], [false, true]]
function paintBig(c: Canvas, input: SaverInput): void {
const t = input.theme
const bodyH = input.height - 2
@@ -348,25 +507,36 @@ function paintBig(c: Canvas, input: SaverInput): void {
.sort((a, b) => (b.x.state.value!.interest ?? 0) - (a.x.state.value!.interest ?? 0) || a.i - b.i)
.map((e) => e.x)
const q = querySize('small')
const y0 = 1 + Math.max(1, Math.floor((bodyH - 14) / 2))
const rotation = Math.floor(input.now / 8000)
const [atRight, atBottom] = input.burnin ? BIG_CORNERS[rotation % BIG_CORNERS.length]! : [false, false]
const columns = input.width >= 100 ? 2 : 1
const colW = columns === 2 ? Math.floor((input.width - 7) / 2) : input.width - 4
const othersCount = Math.max(0, input.tiles.length - 1)
// the group (label, Query and number, detail, dots) and the tiles under it; guarded: in a corner
const contentH = 12 + Math.ceil(othersCount / columns)
const y0 = input.burnin ? 1 + (atBottom ? Math.max(0, bodyH - contentH) : 0) : 1 + Math.max(1, Math.floor((bodyH - 14) / 2))
const centred = (width: number, left: boolean, right: boolean) => (left ? 2 : right ? Math.max(0, input.width - width - 2) : Math.max(0, Math.floor((input.width - width) / 2)))
const place = (width: number) => (input.burnin ? centred(width, !atRight, atRight) : centred(width, false, false))
if (!candidates.length) {
const pose = queryPoseAt(input.now)
drawQuery(c, Math.floor((input.width - q.width) / 2), y0, 'small', pose, input, t.acc2)
const msg = input.tiles.length ? 'fetching the numbers…' : 'nothing to count on this server'
c.put(Math.floor((input.width - msg.length) / 2), y0 + q.height + 1, msg, { fg: t.dim })
const gx = place(Math.max(q.width, msg.length))
drawQuery(c, gx + Math.floor((Math.max(q.width, msg.length) - q.width) / 2), y0, 'small', pose, input, t.acc2)
c.put(gx, y0 + q.height + 1, msg, { fg: t.dim })
return
}
const index = Math.floor(input.now / 8000) % candidates.length
const index = rotation % candidates.length
const tile = candidates[index]!
const v = tile.state.value!
const big = v.big!
const color = levelColor(t, tile) === t.fg ? t.acc2 : levelColor(t, tile)
const label = trunc(tile.state.label.toUpperCase(), input.width - 4)
c.put(Math.floor((input.width - label.length) / 2), y0, label, { fg: t.acc, bold: true })
const drawBlock = canDraw(big) && blockWidth(big) + q.width + 3 <= input.width - 4
const numW = drawBlock ? blockWidth(big) : big.length
const groupW = q.width + 3 + numW
const gx = Math.max(0, Math.floor((input.width - groupW) / 2))
const gx = place(groupW)
const centreOver = (text: string) => Math.max(0, Math.min(input.width - text.length, gx + Math.floor((groupW - text.length) / 2)))
c.put(centreOver(label), y0, label, { fg: t.acc, bold: true })
const asleep = big === '0'
const pose: QueryPose = { ...queryPoseAt(input.now, { dx: 1 }), ...(asleep ? { blink: true, wag: false } : {}) }
drawQuery(c, gx, y0 + 2, 'small', pose, input, t.acc2)
@@ -374,16 +544,15 @@ function paintBig(c: Canvas, input: SaverInput): void {
if (drawBlock) c.block(gx + q.width + 3, y0 + 2, blockText(big, input.ascii), { fg: color, bold: true })
else c.put(gx + q.width + 3, y0 + 4, big, { fg: color, bold: true })
const detail = trunc(`${v.value}${v.detail ? ` · ${v.detail}` : ''}${tile.stale ? ' (stale)' : ''}`, input.width - 4)
c.put(Math.floor((input.width - detail.length) / 2), y0 + 2 + q.height + 1, detail, { fg: t.dim })
c.put(centreOver(detail), y0 + 2 + q.height + 1, detail, { fg: t.dim })
const dots = candidates.map((_, i) => (i === index ? (input.ascii ? '*' : '●') : (input.ascii ? '.' : '○'))).join(' ')
c.put(Math.floor((input.width - dots.length) / 2), y0 + 2 + q.height + 2, trunc(dots, input.width - 2), { fg: t.dim })
c.put(centreOver(dots), y0 + 2 + q.height + 2, trunc(dots, input.width - 2), { fg: t.dim })
// everything else on the lines beneath
const y = y0 + 2 + q.height + 4
const others = input.tiles.filter((x) => x !== tile)
const colW = input.width >= 100 ? Math.floor((input.width - 7) / 2) : input.width - 4
const columns = input.width >= 100 ? 2 : 1
const othersLeft = atRight ? Math.max(2, input.width - (columns * (colW + 3) - 3) - 2) : 2
others.slice(0, Math.max(0, (input.height - 1 - y) * columns)).forEach((o, i) => {
tileLine(c, 2 + (columns === 2 ? (i % 2) * (colW + 3) : 0), y + (columns === 2 ? Math.floor(i / 2) : i), colW, o, input)
tileLine(c, othersLeft + (columns === 2 ? (i % 2) * (colW + 3) : 0), y + (columns === 2 ? Math.floor(i / 2) : i), colW, o, input)
})
}
@@ -399,8 +568,10 @@ export function paintSaver(input: SaverInput): Canvas {
else if (input.style === 'starfield') paintStarfield(c, input)
else if (input.style === 'flip') paintFlip(c, input)
else paintBig(c, input)
header(c, input)
footer(c, input)
const chrome = chromeLayout(input)
header(c, input, chrome)
footer(c, input, chrome)
drawPin(c, input)
if (input.dim) c.dim(DIM_AMOUNT)
return c
}
+22 -2
View File
@@ -5,7 +5,8 @@
/**
* Screen saver settings in ~/.config/qqq/config.json (a `saver` section; the kernel keeps sections
* it does not know): the style, the refresh interval, and per profile the favourite tables whose
* it does not know): the style, the refresh interval, the burn-in guard (everything drifts) and the
* dim-after minutes, and per profile the favourite tables whose
* record counts get a tile (`profiles.<name>.saver.tables`).
*/
@@ -28,16 +29,31 @@ export const DEFAULT_REFRESH_SECONDS = 15
/** The favourite tables that get a count tile: "a couple". */
export const MAX_TABLES = 3
/** Minutes of saver before everything dims a little (0: never). */
export const DEFAULT_DIM_MINUTES = 10
export const DIM_CHOICES = [0, 5, 10, 20, 30] as const
export interface SaverSettings {
style: SaverStyleSetting
refreshSeconds: number
tables: string[]
/** Burn-in guard: every element drifts (default on); off keeps the fixed layout. */
burnin: boolean
/** Dim the saver after this many minutes (0: never). */
dimMinutes: number
}
interface SaverSection {
style?: string
refreshSeconds?: number
tables?: string[]
burnin?: boolean
dimMinutes?: number
}
/** Clamps the dim delay to whole minutes, 1 to 600; 0 (or anything not a number) is off. */
export function clampDim(minutes: number): number {
return Number.isFinite(minutes) && minutes >= 1 ? Math.min(600, Math.round(minutes)) : 0
}
export function isStyle(value: string | undefined): value is SaverStyleSetting {
@@ -54,7 +70,7 @@ export function readSaverSettings(profile?: string): SaverSettings {
try {
config = readConfig()
} catch {
return { style: 'auto', refreshSeconds: DEFAULT_REFRESH_SECONDS, tables: [] }
return { style: 'auto', refreshSeconds: DEFAULT_REFRESH_SECONDS, tables: [], burnin: true, dimMinutes: DEFAULT_DIM_MINUTES }
}
const global = (config.saver ?? {}) as SaverSection
const own = (profile ? (config.profiles[profile] as { saver?: SaverSection } | undefined)?.saver : undefined) ?? {}
@@ -63,6 +79,8 @@ export function readSaverSettings(profile?: string): SaverSettings {
style: isStyle(global.style) ? global.style : 'auto',
refreshSeconds: clampRefresh(Number(global.refreshSeconds ?? DEFAULT_REFRESH_SECONDS)),
tables,
burnin: global.burnin !== false,
dimMinutes: global.dimMinutes === undefined ? DEFAULT_DIM_MINUTES : clampDim(Number(global.dimMinutes)),
}
}
@@ -72,6 +90,8 @@ export function writeSaverSettings(change: Partial<SaverSettings>, profile?: str
const global = { ...((config.saver ?? {}) as SaverSection) }
if (change.style !== undefined) global.style = change.style
if (change.refreshSeconds !== undefined) global.refreshSeconds = clampRefresh(change.refreshSeconds)
if (change.burnin !== undefined) global.burnin = change.burnin
if (change.dimMinutes !== undefined) global.dimMinutes = clampDim(change.dimMinutes)
if (change.tables !== undefined) {
const tables = change.tables.slice(0, MAX_TABLES)
if (profile && config.profiles[profile]) {
+235 -8
View File
@@ -7,8 +7,8 @@ import { afterAll, beforeAll, describe, expect, test } from 'bun:test'
import { removePin, setPin } from '@qrun-io/qqq-core'
import { UiApiError } from '@qrun-io/qqq-ui-api-client'
import { SaverOverlay } from '../src/overlays/saver'
import { FONT_HEIGHT, blockText, blockWidth } from '../src/saver/font'
import { AUTO_STYLE_MILLIS, FRAME_MILLIS, bounce, nextFrameDelay, paintSaver, styleAt, type SaverInput, type SaverTile } from '../src/saver/layout'
import { FONT_HEIGHT, blockText, blockWidth, canDraw } from '../src/saver/font'
import { ALTERNATE_MILLIS, AUTO_STYLE_MILLIS, FRAME_MILLIS, SHIFT_MILLIS, bounce, bounceLayout, chromeLayout, isDimmed, logoName, nextFrameDelay, paintSaver, styleAt, type SaverInput, type SaverTile } from '../src/saver/layout'
import { EventRate, MAX_BACKOFF_MS, TileModel, isAbsent, sparkline, type TileSource, type TileValue } from '../src/saver/model'
import { decodeBraille, encodeBraille, mirrorAscii, queryFrame, queryPoseAt, querySize } from '../src/saver/query-art'
import { readSaverSettings, writeSaverSettings, SAVER_STYLES } from '../src/saver/settings'
@@ -212,7 +212,7 @@ const TILES: SaverTile[] = [
]
function input(over: Partial<SaverInput>): SaverInput {
return { style: 'bounce', now: 1_000_005_000, width: 80, height: 24, tiles: TILES, server: 'localhost:8078', profile: 'enterprise', brand: 'QQQ', ascii: false, theme: THEMES['high-contrast']!, locked: false, preview: false, ramp: '▁▂▃▄▅▆▇█', ...over }
return { style: 'bounce', now: 1_000_005_000, width: 80, height: 24, tiles: TILES, server: 'localhost:8078', profile: 'enterprise', brand: 'QQQ', ascii: false, theme: THEMES['high-contrast']!, locked: false, preview: false, ramp: '▁▂▃▄▅▆▇█', shortName: 'ent', burnin: false, dim: false, ...over }
}
describe('layout', () => {
@@ -240,13 +240,41 @@ describe('layout', () => {
})
}
test('Bounce draws large Query with the qqq logo at 120×40 and large Query at 80×24', () => {
test('Bounce draws large Query with the profile\'s short name in block letters and the host beneath at 120×40', () => {
const big = paintSaver(input({ style: 'bounce', width: 120, height: 40, tiles: [], now: 1_000_001_000 })).text()
const rows = [...queryFrame('large'), ...queryFrame('large', { facing: 'left' })].map((r) => r.trim().slice(0, 10))
expect(rows.some((r) => big.includes(r))).toBe(true)
expect(big).toContain(blockText('qqq')[1]!)
const small = paintSaver(input({ style: 'bounce', width: 80, height: 24, tiles: [], now: 1_000_001_000 })).text()
expect(small).toContain('q q q')
const lines = big.split('\n')
const ent = blockText('ent')
const top = lines.findIndex((l) => l.includes(ent[0]!))
expect(top).toBeGreaterThan(0)
ent.forEach((r, i) => expect(lines[top + i]).toContain(r))
// "localhost:8078" under the letters (the top row has it too, in normal text)
expect(lines[top + FONT_HEIGHT]).toContain('localhost:8078')
expect(big).not.toContain(blockText('qqq')[1]!)
})
test('the logo says the short name when it has 6 characters or fewer, else the profile; unknown characters fall back to plain text', () => {
expect(logoName(input({}))).toBe('ent')
expect(logoName(input({ shortName: 'enterp7', profile: 'enterprise' }))).toBe('enterprise')
expect(logoName(input({ shortName: undefined, profile: '' }))).toBe('qqq')
expect(canDraw('Prod-eu_1.a')).toBe(true)
expect(canDraw('abcdefghijklmnopqrstuvwxyz0123456789-_.')).toBe(true)
expect(canDraw('café')).toBe(false)
for (const text of ['ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz0123456789-_.']) {
const rows = blockText(text)
expect(rows.length).toBe(FONT_HEIGHT)
for (const r of rows) expect([...r].length).toBe(blockWidth(text))
}
// not drawable: plain text, and the host beneath
const plain = paintSaver(input({ style: 'bounce', width: 120, height: 40, tiles: [], shortName: undefined, profile: 'café prod', now: 1_000_001_000 })).text()
expect(plain).toContain('café prod')
expect(plain).not.toContain(blockText('prod')[0]!)
})
test('at 80×24 Query is small so the block-letter name fits', () => {
const text = paintSaver(input({ style: 'bounce', width: 80, height: 24, tiles: [], now: 1_000_001_000 })).text()
expect(text).toContain(blockText('ent')[2]!)
})
test('Big numbers shows the most interesting tile in block digits, then rotates', () => {
@@ -286,10 +314,191 @@ describe('settings', () => {
writeSaverSettings({ style: 'flip', refreshSeconds: 99 })
writeSaverSettings({ tables: ['person', 'order', 'shipment', 'extra'] }, 'fake')
const s = readSaverSettings('fake')
expect(s).toEqual({ style: 'flip', refreshSeconds: 30, tables: ['person', 'order', 'shipment'] })
expect(s).toEqual({ style: 'flip', refreshSeconds: 30, tables: ['person', 'order', 'shipment'], burnin: true, dimMinutes: 10 })
expect(readSaverSettings('other').tables).toEqual([])
writeSaverSettings({ style: 'auto', refreshSeconds: 15, tables: [] }, 'fake')
})
test('burn-in guard defaults on and dim to 10 minutes; both are saved, dim 0 is off', () => {
expect(readSaverSettings()).toMatchObject({ burnin: true, dimMinutes: 10 })
writeSaverSettings({ burnin: false, dimMinutes: 0 })
expect(readSaverSettings()).toMatchObject({ burnin: false, dimMinutes: 0 })
writeSaverSettings({ burnin: true, dimMinutes: 3.4 })
expect(readSaverSettings()).toMatchObject({ burnin: true, dimMinutes: 3 })
writeSaverSettings({ dimMinutes: 10 })
})
})
describe('burn-in guard', () => {
const SIZES = [[80, 24], [120, 40]] as const
const moments = (n: number, from = 1_000_000_000, every = 250) => Array.from({ length: n }, (_, i) => from + i * every)
for (const [width, height] of SIZES) {
test(`Bounce at ${width}×${height}: the tile panel rides beside the logo, swaps sides and never leaves the screen`, () => {
const panels = new Set<string>()
const sides = new Set<string>()
let moved = 0
let last = ''
for (const now of moments(400, 1_000_000_000, 700)) {
const i = input({ style: 'bounce', width, height, now, burnin: true })
const l = bounceLayout(i)
expect(l.showSprite).toBe(true)
const p = l.panel!
expect(p).toBeDefined()
expect(p.x).toBeGreaterThanOrEqual(0)
expect(p.x + p.w).toBeLessThanOrEqual(width)
expect(p.y).toBeGreaterThanOrEqual(1)
expect(p.y + p.h).toBeLessThanOrEqual(height - 1)
// beside the logo (a one-cell gap), on one side or the other, never on top of it
const right = p.x === l.sprite.x + l.sprite.w + 1
const left = p.x + p.w === l.sprite.x - 1
expect(right || left).toBe(true)
sides.add(right ? 'right' : 'left')
const key = `${p.x},${p.y}`
panels.add(key)
if (key !== last) moved++
last = key
// and it is on the canvas where it says
const lines = paintSaver(i).text().split('\n')
expect(lines[p.y]!.slice(p.x, p.x + p.w)).toContain(' live ')
}
expect(panels.size).toBeGreaterThan(20)
expect(moved).toBeGreaterThan(300)
expect(sides.size).toBe(2)
})
test(`Bounce at ${width}×${height}: the panel moves with the logo from one frame to the next`, () => {
for (const now of moments(60, 1_000_003_000)) {
const a = bounceLayout(input({ style: 'bounce', width, height, now, burnin: true }))
const b = bounceLayout(input({ style: 'bounce', width, height, now: now + FRAME_MILLIS, burnin: true }))
const spriteMoved = a.sprite.x !== b.sprite.x || a.sprite.y !== b.sprite.y
const panelMoved = a.panel!.x !== b.panel!.x || a.panel!.y !== b.panel!.y
if (spriteMoved) expect(panelMoved).toBe(true)
}
})
test(`Bounce at ${width}×${height} with the guard off keeps the panel in the bottom-right corner`, () => {
const seen = new Set<string>()
for (const now of moments(100, 1_000_000_000, 900)) {
const p = bounceLayout(input({ style: 'bounce', width, height, now, burnin: false })).panel!
seen.add(`${p.x},${p.y}`)
expect(p.x + p.w).toBe(width - 1)
expect(p.y + p.h).toBe(height - 1)
}
expect(seen.size).toBe(1)
})
test(`header and lock line at ${width}×${height} change place every cycle in every style; the clock stays visible`, () => {
for (const style of SAVER_STYLES) {
const header = new Set<string>()
const lock = new Set<string>()
const rows = new Set<number>()
for (let cycle = 0; cycle < 12; cycle++) {
const now = 1_000_000_000 + cycle * SHIFT_MILLIS + 5_000
const i = input({ style, width, height, now, burnin: true, locked: true })
const c = chromeLayout(i)
header.add(`${c.headerRow},${c.headerX}`)
lock.add(`${c.footerRow},${c.footerX}`)
rows.add(c.headerRow)
expect(c.headerRow).not.toBe(c.footerRow)
const lines = paintSaver(i).text().split('\n')
expect(lines[c.headerRow]!.slice(c.headerX, c.headerX + c.headerText.length)).toBe(c.headerText)
expect(lines[c.footerRow]!.slice(c.footerX, c.footerX + c.footerText.length)).toBe(c.footerText)
expect(c.footerText).toBe('locked · any key to unlock')
expect(lines.join('\n')).toMatch(/\d\d:\d\d:\d\d/)
expect(lines.length).toBe(height)
for (const l of lines) expect([...l].length).toBe(width)
}
expect(header.size).toBeGreaterThanOrEqual(8)
expect(lock.size).toBeGreaterThanOrEqual(8)
expect([...rows].sort()).toEqual([0, height - 1])
}
})
test(`with the guard off the header and lock line stay put at ${width}×${height}`, () => {
for (const style of SAVER_STYLES) {
const seen = new Set<string>()
for (let cycle = 0; cycle < 6; cycle++) {
const i = input({ style, width, height, now: 1_000_000_000 + cycle * SHIFT_MILLIS, burnin: false, locked: true })
const lines = paintSaver(i).text().split('\n')
expect(lines[0]).toContain('localhost:8078')
expect(lines[height - 1]).toContain('locked · any key to unlock')
seen.add(`${lines[0]!.indexOf('localhost')},${lines[height - 1]!.indexOf('locked')}`)
}
expect(seen.size).toBe(1)
}
})
test(`Flip clock at ${width}×${height} drifts a cell every few seconds inside a bounded box; guard off: fixed`, () => {
const cards = (now: number, burnin: boolean) => {
const lines = paintSaver(input({ style: 'flip', width, height, now, burnin, tiles: TILES.slice(0, 3) })).text().split('\n')
// the hinge of the first card
const row = lines.findIndex((l, y) => y > 0 && y < height - 1 && l.includes('▸'))
return { row, col: lines[row]!.indexOf('▸') }
}
const guarded = new Set<string>()
const fixed = new Set<string>()
for (let i = 0; i < 40; i++) {
const now = 1_000_000_000 + i * 4_100 + 1_000
const g = cards(now, true)
guarded.add(`${g.row},${g.col}`)
const f = cards(now, false)
fixed.add(`${f.row},${f.col}`)
}
expect(guarded.size).toBeGreaterThan(2)
const cols = [...guarded].map((k) => Number(k.split(',')[1]))
const rowsSeen = [...guarded].map((k) => Number(k.split(',')[0]))
expect(Math.max(...cols) - Math.min(...cols)).toBeLessThanOrEqual(8)
expect(Math.max(...rowsSeen) - Math.min(...rowsSeen)).toBeLessThanOrEqual(2)
expect(fixed.size).toBe(1)
})
test(`Big numbers at ${width}×${height} moves to another corner at each rotation; the number stays on screen`, () => {
const spots = new Set<string>()
for (let r = 0; r < 4; r++) {
const i = input({ style: 'big', width, height, now: r * 8000, burnin: true, tiles: TILES.slice(0, 3) })
const lines = paintSaver(i).text().split('\n')
const label = lines.findIndex((l, y) => y > 0 && y < height - 1 && /HEALTH|ONLINE|JOBS|EVENTS/.test(l))
expect(label).toBeGreaterThan(0)
spots.add(`${label},${lines[label]!.search(/HEALTH|ONLINE|JOBS|EVENTS/)}`)
expect(lines.join('\n')).toMatch(/\d\d:\d\d:\d\d/)
for (const l of lines) expect([...l].length).toBe(width)
}
expect(spots.size).toBe(4)
})
}
test('too small for Query and the panel together: the panel for 20 s, then Query for 20 s, both drifting', () => {
const w = 40
const h = 18
const live = (now: number) => paintSaver(input({ style: 'bounce', width: w, height: h, now, burnin: true })).text().includes(' live ')
const queryShown = (now: number) => bounceLayout(input({ style: 'bounce', width: w, height: h, now, burnin: true })).showSprite
const start = Math.floor(1_000_000_000 / (2 * ALTERNATE_MILLIS)) * 2 * ALTERNATE_MILLIS
expect(live(start + 3_000)).toBe(true)
expect(queryShown(start + 3_000)).toBe(false)
expect(live(start + ALTERNATE_MILLIS + 3_000)).toBe(false)
expect(queryShown(start + ALTERNATE_MILLIS + 3_000)).toBe(true)
const a = bounceLayout(input({ style: 'bounce', width: w, height: h, now: start + 3_000, burnin: true })).panel!
const b = bounceLayout(input({ style: 'bounce', width: w, height: h, now: start + 3_250, burnin: true })).panel!
expect(a.x !== b.x || a.y !== b.y).toBe(true)
expect(a.x + a.w).toBeLessThanOrEqual(w)
expect(b.y + b.h).toBeLessThanOrEqual(h - 1)
})
test('dimming starts at the configured time, 0 never; a dimmed frame has darker colours and the same text', () => {
expect(isDimmed(9 * 60_000 + 59_000, 10)).toBe(false)
expect(isDimmed(10 * 60_000, 10)).toBe(true)
expect(isDimmed(60_000, 1)).toBe(true)
expect(isDimmed(24 * 3_600_000, 0)).toBe(false)
const plain = paintSaver(input({ style: 'bounce', burnin: true, dim: false }))
const dimmed = paintSaver(input({ style: 'bounce', burnin: true, dim: true }))
expect(dimmed.text()).toBe(plain.text())
const first = (c: ReturnType<typeof paintSaver>) => c.runs(0).filter((r) => r.text.trim()).map((r) => r.fg)
expect(first(dimmed)).not.toEqual(first(plain))
const lum = (hex: string) => parseInt(hex.slice(1, 3), 16) + parseInt(hex.slice(3, 5), 16) + parseInt(hex.slice(5, 7), 16)
const bright = (c: ReturnType<typeof paintSaver>) => Math.max(...c.runs(0).filter((r) => r.text.trim() && r.fg?.startsWith('#')).map((r) => lum(r.fg!)))
expect(bright(dimmed)).toBeLessThan(bright(plain))
})
})
describe('in the TUI', () => {
@@ -329,10 +538,28 @@ describe('in the TUI', () => {
}
})
test('the overlay dims once the saver has been up for the configured minutes; burnin and dim are saved by :saver', async () => {
await command(h, 'saver dim 5')
await command(h, 'saver burnin off')
expect(readSaverSettings()).toMatchObject({ burnin: false, dimMinutes: 5 })
let s = new SaverOverlay(h.store, 'bounce')
expect(s.input(80, 24, s.startedAt + 4 * 60_000 + 59_000).dim).toBe(false)
expect(s.input(80, 24, s.startedAt + 5 * 60_000).dim).toBe(true)
expect(s.input(80, 24).burnin).toBe(false)
await command(h, 'saver dim off')
await command(h, 'saver burnin on')
s = new SaverOverlay(h.store, 'bounce')
expect(s.input(80, 24, s.startedAt + 3_600_000).dim).toBe(false)
expect(s.input(80, 24).burnin).toBe(true)
await command(h, 'saver dim 10')
})
test('F9 → Settings lists the saver style, refresh and preview', () => {
const labels = (h.store.commands() as unknown as { entries(f: string): Array<{ label: string }> }).entries('').map((e) => e.label)
expect(labels.some((l) => l.startsWith('Screen saver style:'))).toBe(true)
expect(labels.some((l) => l.startsWith('Screen saver refresh:'))).toBe(true)
expect(labels.some((l) => l.startsWith('Screen saver burn-in guard:'))).toBe(true)
expect(labels.some((l) => l.startsWith('Screen saver dim:'))).toBe(true)
expect(labels).toContain('Preview the screen saver')
})
})