diff --git a/meshterm/platforms.py b/meshterm/platforms.py index 94588d9..f442e31 100644 --- a/meshterm/platforms.py +++ b/meshterm/platforms.py @@ -85,10 +85,11 @@ class Platform: and quantizes the two scales that would otherwise spend a gradient — the per-node key hue (:func:`~meshterm.ui.theme.node_style`) and the heard-age heat (:func:`~meshterm.ui.widgets._recency_style`). Wired in P3. - effects: Whether animated/decorative rendering runs at all: the header battery - blink, the braille spinner. ``False`` drops to static chrome and a ``LINE`` - spinner fallback, which is cheaper on a console where a repaint is dear. - Wired in P2/P3. + effects: Whether animated/decorative rendering runs at all — the braille spinner, + which drops to a ``LINE`` fallback. Cheaper on a console where a repaint is + dear. The header battery gauge is deliberately *not* behind it: its sweep is + the charging state itself and its blink is the last warning before the pack + dies, and both ride the idle repaint that happens anyway. Wired in P2/P3. tick_s: The :class:`~prompt_toolkit.application.Application` refresh interval — the *idle* repaint cadence only, since every screen pushes its own repaint through ``TuiSession.invalidate`` when its data actually moves. Composing one frame was diff --git a/meshterm/ui/menu.py b/meshterm/ui/menu.py index 4d7d80b..f73eb2a 100644 --- a/meshterm/ui/menu.py +++ b/meshterm/ui/menu.py @@ -241,18 +241,13 @@ def _battery_segment(ctx: AppContext) -> Text: reading = ctx.battery.reading() if reading is None: return Text() - platform = get_platform() - # The sweep is how the gauge says "charging" at all, so its clock runs on every platform; - # only the step widens to whatever that platform actually repaints at. The low-battery - # blink is decoration over a charge the cell already shows, so it stays behind `effects` - # — not worth a forced repaint, nor a colour swap on a 16-slot console. - frame = int(time.monotonic() / max(_BATTERY_ANIM_MIN_S, platform.tick_s)) - return battery_cell( - reading.percent, - charging=reading.charging, - frame=frame, - animate=platform.effects, - ) + # Both of the gauge's animations run on every platform; only the step widens to whatever + # that platform actually repaints at. Neither is behind `Platform.effects`: the header is + # rebuilt on the idle tick regardless, so an animation costs a colour swap in a frame + # already being painted — and the two things it animates are "power is coming in" and + # "this handheld is about to die", neither of which is decoration. + frame = int(time.monotonic() / max(_BATTERY_ANIM_MIN_S, get_platform().tick_s)) + return battery_cell(reading.percent, charging=reading.charging, frame=frame) def _header_segments(ctx: AppContext, cache: dict) -> list[Text]: diff --git a/meshterm/ui/theme.py b/meshterm/ui/theme.py index 8d91024..07814a9 100644 --- a/meshterm/ui/theme.py +++ b/meshterm/ui/theme.py @@ -121,13 +121,19 @@ MESH_THEME = Theme( "snr.good": "bold #4ade80", "snr.ok": "bold #fbbf24", "snr.bad": "bold #f87171", - # The status-bar battery gauge, as a fuel-gauge palette: green healthy, orange at - # a quarter, red near empty. ``batt.dim`` is the off-beat of the critically-low - # blink — a dark slate the red glyph flickers to, so it pulses without vanishing. - "batt.high": "bold #4ade80", - "batt.mid": "bold #fb923c", - "batt.low": "bold #f87171", - "batt.dim": "#475569", + # The status-bar battery gauge: a filled block, not four thin dots. Every cell is a + # lit foreground over its own darker ground of the same hue — light green on green + # over half, yellow on brown over a quarter, light red on red below — so the gauge + # reads as a *block* at a glance and the braille fill inside it says how much of the + # pack is left. ``batt.flash`` and ``batt.flash.off`` are the two beats of the + # last-percent alarm: black dots on red, alternating with the light red on the bare + # page. Losing the ground for a beat is a bigger change than any hue swap could be, + # which is what makes it read across a room. + "batt.full": "bold #4ade80 on #15803d", + "batt.mid": "bold #fbbf24 on #a16207", + "batt.low": "bold #f87171 on #991b1b", + "batt.flash": "not bold #000000 on #dc2626", + "batt.flash.off": "bold #f87171", # The node-type *marks* — THE colours behind ● ▲ ■ ◉ wherever a typed node is # drawn (see ui.widgets._NODE_GLYPHS), and the map's own marker language: clients # the loud pink, repeaters the calmer violet, rooms a white square, sensors an @@ -323,10 +329,14 @@ MESH_THEME_16 = Theme( "snr.good": "bold color(10)", "snr.ok": "bold color(11)", "snr.bad": "bold color(9)", - "batt.high": "bold color(10)", - "batt.mid": "not bold color(3)", - "batt.low": "bold color(9)", - "batt.dim": "color(8)", + # Each band is its bright slot over its own dim one — the console has exactly one + # pair per hue, and backgrounds stop at the dim bank, so the block look is the + # palette's natural shape rather than a compromise with it. + "batt.full": "bold color(10) on color(2)", + "batt.mid": "bold color(11) on color(3)", + "batt.low": "bold color(9) on color(1)", + "batt.flash": "not bold color(0) on color(1)", + "batt.flash.off": "bold color(9)", "type.node": "color(13)", "type.repeater": "not bold color(5)", "type.room": "color(15)", diff --git a/meshterm/ui/widgets.py b/meshterm/ui/widgets.py index cbf3ae2..c3d5fa6 100644 --- a/meshterm/ui/widgets.py +++ b/meshterm/ui/widgets.py @@ -1345,63 +1345,107 @@ _BRAILLE_BASE = 0x2800 #: into the canvas module for two constants. _BRAILLE_DOTS = ((0x01, 0x02, 0x04, 0x40), (0x08, 0x10, 0x20, 0x80)) -#: Battery charge tiers: ``(percent floor, braille rows lit from the bottom, colour)``, -#: highest first. The glyph is one braille cell (2×4 dots) filled from its bottom row up, so -#: four coarse levels read as a shrinking fuel gauge: the whole cell above three-quarters, -#: six dots above half, four above a quarter, two below it — green while healthy, orange at a -#: quarter, red near empty (the app's ok/warn/err semantics as a gauge). -_BATTERY_TIERS: tuple[tuple[int, int, str], ...] = ( - (75, 4, "batt.high"), - (50, 3, "batt.high"), - (25, 2, "batt.mid"), - (0, 1, "batt.low"), +#: The fuel-gauge bands: ``(percent floor, style)``, highest first. Colour answers *how much +#: pack is left* in three broad steps — light green on green over half, yellow on brown over a +#: quarter, light red on red below — while the eight-rung braille fill inside the block +#: answers *how much more precisely*. Two questions, two channels: a band that stayed put +#: while the dots climbed is what makes the cell readable at a glance and still exact on a +#: second look. +_BATTERY_BANDS: tuple[tuple[int, str], ...] = ( + (50, "batt.full"), + (25, "batt.mid"), + (0, "batt.low"), ) -#: At or below this charge the red glyph blinks with a dim frame — a can't-miss low warning. -_BATTERY_CRITICAL = 10 +#: Steps in the fill: one braille cell is 2×4 dots, and each dot row lights left-then-right, +#: so the cell reads as an eight-rung ladder — one rung per 12.5% of charge. +_BATTERY_STEPS = 8 + +#: Halfway down the last rung the cell starts alarming, and it does it by dropping the ground +#: rather than by changing hue: black dots on red one frame (``batt.flash``), the light red on +#: the bare page the next (``batt.flash.off``). Every other cell in the app's gauge is a +#: filled block, so a beat with no fill at all is the loudest thing the palette can say. +#: A percentage rather than a rung because half a rung is not a rung: a rung is ``100 / 8`` = +#: 12.5% of the pack, so its midpoint is 6.25% — the last dot half spent. +#: +#: The alternation is ours, drawn a frame at a time. The console's own blink attribute is no +#: use even where a terminal honours it: SGR 5 toggles the *foreground* and leaves the ground +#: alone, which is the half of this that matters (and the PicoCalc's framebuffer console +#: ignores it outright — device-checked, along with its want of bright backgrounds). +_BATTERY_FLASH_PCT = 100 / _BATTERY_STEPS / 2 #: Frames in the charging sweep: empty → four fills → round again (bottom-to-full loop). _CHARGE_FRAMES = 5 -def _braille_fill(rows: int) -> str: - """A single braille cell with its bottom ``rows`` (0–4) dot rows lit.""" - rows = max(0, min(4, rows)) +def _braille_fill(steps: int) -> str: + """A single braille cell filled from the bottom by ``steps`` (0–8) half-rows. + + Each dot row is two steps: the left dot lights first, then the right one completes the + row, so the fill climbs in half-rows rather than whole ones and one cell carries eight + distinguishable levels. + """ + steps = max(0, min(_BATTERY_STEPS, steps)) bits = 0 - for row in range(4 - rows, 4): - bits |= _BRAILLE_DOTS[0][row] | _BRAILLE_DOTS[1][row] + for step in range(steps): + row, col = 3 - step // 2, step % 2 + bits |= _BRAILLE_DOTS[col][row] return chr(_BRAILLE_BASE + bits) -def _battery_tier(percent: int) -> tuple[int, str]: - """The ``(rows lit, colour)`` a charge level draws at (see :data:`_BATTERY_TIERS`).""" - for floor, rows, color in _BATTERY_TIERS: +def _battery_steps(percent: int) -> int: + """How many half-rows a charge lights: one rung per 12.5%, never fewer than one. + + The bands are ``0–12.5`` → one rung … ``87.5–100`` → the full cell, each one taking its + lower bound. A pack on its last percent still lights a single dot, so the gauge is never + an empty cell while the pack is still running. + """ + pct = max(0, min(100, int(percent))) + return max(1, min(_BATTERY_STEPS, int(pct * _BATTERY_STEPS / 100) + 1)) + + +def _battery_band(percent: int) -> str: + """The band a charge draws in (see :data:`_BATTERY_BANDS`) — always the *true* charge. + + Read off the pack rather than off the cell, so the charging sweep keeps saying what the + pack holds while its fill climbs through frames that mean nothing on their own. + """ + for floor, style in _BATTERY_BANDS: if percent >= floor: - return rows, color - return 1, "batt.low" + return style + return "batt.low" -def battery_cell( - percent: int, *, charging: bool = False, frame: int = 0, animate: bool = True -) -> Text: - """The status-bar battery gauge: one braille cell coloured by charge, then its ``%``. +def battery_cell(percent: int, *, charging: bool = False, frame: int = 0) -> Text: + """The status-bar battery gauge: one filled braille block, then its ``%``. - The braille cell fills from the bottom up in four coarse steps (see - :data:`_BATTERY_TIERS`), coloured green while healthy, orange at a quarter, red near - empty. Two live states animate off the caller's ``frame`` counter (advanced one step per - repaint tick), so the gauge moves without any per-frame plumbing: + The cell is a lit foreground over its own darker ground — a *block*, coloured by band + (:data:`_BATTERY_BANDS`): light green on green over half, yellow on brown over a quarter, + light red on red below. Inside that block the braille fills from the bottom up in eight + half-row steps (see :func:`_braille_fill`), one rung per 12.5% of charge, the left dot of + a row lighting before the right. So the block answers *roughly how much* from across the + room and the dots answer *exactly how much* on a second look. Two live states animate off + the caller's ``frame`` counter (advanced one step per repaint tick), so the gauge moves + without any per-frame plumbing: - * **Charging** overrides the fill: the cell sweeps empty-to-full on a loop, the charge - colour held, so a plugged-in pack visibly climbs — while the number beside it stays the - *true* charge, never the animation's. - * **Critically low** (≤ :data:`_BATTERY_CRITICAL`%, not charging) blinks the red cell to a - dim slate on alternate frames — an unmissable pulse in the corner. + * **Charging** overrides the fill: the cell sweeps empty-to-full on a loop, so a + plugged-in pack visibly climbs. The band does *not* sweep with it — colour keeps + answering for the real charge, since a frame of the animation means nothing on its own + — and neither does the number beside it, which stays the true percent throughout. The + sweep climbs by whole dot rows, not by the fill's half-rows: it is a "power is coming + in" animation rather than a reading, and its tick is slow enough (a step per repaint) + that five frames say that better than nine. + * **Below :data:`_BATTERY_FLASH_PCT`** — half the last dot's worth of charge, and only + when nothing is charging it — the cell alternates between black dots on red and the + light red on the bare page. Dropping the ground for a beat is a bigger change than any + hue swap in a palette where every other cell is filled, which is the point: it is the + last warning a handheld gives before it dies. - The two differ in what they're *for*, which is what ``animate`` sorts out. The sweep is - the only thing that says charging at all, so it runs everywhere — a platform whose frames - are dear (the PicoCalc: see ``Platform.effects``) just steps it on that platform's own - slower repaint cadence. The blink is an alarm laid over a charge the gauge already shows, - so it is genuinely decorative and ``animate=False`` drops it, leaving the red cell steady. + Both run on every platform, stepping at whatever that platform repaints at — 2 s on the + PicoCalc, where the header is rebuilt on the idle tick anyway, so an animation costs a + colour swap in a frame already being painted and nothing else. Neither is behind + ``Platform.effects``: one *is* the charging state, and the other is the last warning a + handheld gives before it dies. A pack at 100% is drawn as **not charging** whichever way the flag reads: a full cell resting full is the honest picture, and a topped-off charger left plugged in shouldn't @@ -1412,20 +1456,24 @@ def battery_cell( charging: Whether the pack is taking charge (drives the fill sweep). Ignored at 100%. frame: A monotonically advancing tick; only its phase is read, so any steadily-incrementing integer animates the two live states. - animate: Whether decorative animation runs. ``False`` holds the low-battery blink at - its resting frame; the charging sweep runs regardless, being the state itself. Returns: - A Rich :class:`Text`: the coloured glyph, a space, and ``NN%`` in muted text. + A Rich :class:`Text`: the coloured block, a space, and ``NN%`` in muted text — the + block's colours on the glyph's span alone, so the ground stops at the cell. """ pct = max(0, min(100, int(percent))) - rows, color = _battery_tier(pct) - if charging and pct < 100: - # The charge colour is held; only the fill sweeps, so it reads as "filling", not - # as the charge itself jumping around. - rows = frame % _CHARGE_FRAMES - elif animate and pct <= _BATTERY_CRITICAL and frame % 2: - color = "batt.dim" - out = Text(_braille_fill(rows), style=color) + # The sweep climbs by whole rows, so the loop stays legible. Colour comes off the pack + # either way: a sweep frame is an animation, not a reading, and must not be coloured + # as though it were one. + sweeping = charging and pct < 100 + steps = (frame % _CHARGE_FRAMES) * 2 if sweeping else _battery_steps(pct) + color = _battery_band(pct) + if not sweeping and pct < _BATTERY_FLASH_PCT: + color = "batt.flash.off" if frame % 2 else "batt.flash" + # The colours ride the *glyph's own span*, never the Text's base style: the block paints + # a background, and a base style merges into every span, so a base block would drag the + # muted percent onto the coloured ground alongside the cell. + out = Text() + out.append(_braille_fill(steps), style=color) out.append(f" {pct}%", style="muted") return out diff --git a/tests/test_battery.py b/tests/test_battery.py index 3f70470..d00c2de 100644 --- a/tests/test_battery.py +++ b/tests/test_battery.py @@ -19,7 +19,7 @@ from meshterm.services.battery_service import ( BatteryService, battery_percent, ) -from meshterm.ui.widgets import _BATTERY_CRITICAL, battery_cell +from meshterm.ui.widgets import _BATTERY_FLASH_PCT, battery_cell # --- the LiPo state-of-charge curve ------------------------------------------------------- @@ -43,13 +43,33 @@ def test_battery_percent_interpolates_and_stays_monotonic() -> None: # --- the one-cell braille glyph ----------------------------------------------------------- -def test_battery_cell_fills_from_the_bottom_by_tier() -> None: - """Each tier drops dot rows off the top: full, six, four, two dots lit.""" +def _glyph_style(cell) -> str: + """The style on the gauge's glyph span — the cell's colour, not the percent's.""" + return str(cell.spans[0].style) + + +def test_battery_cell_fills_in_eight_half_row_steps() -> None: + """One rung per 12.5%: each dot row lights left first, then right, bottom to top.""" assert battery_cell(100).plain[0] == "⣿" # all 8 dots assert battery_cell(90).plain[0] == "⣿" - assert battery_cell(60).plain[0] == chr(0x2800 | 0xF6) # bottom 6 dots - assert battery_cell(30).plain[0] == chr(0x2800 | 0xE4) # bottom 4 dots - assert battery_cell(10).plain[0] == chr(0x2800 | 0xC0) # bottom 2 dots + assert battery_cell(80).plain[0] == chr(0x2800 | 0xF7) # 7 rungs: + the top row's left + assert battery_cell(70).plain[0] == chr(0x2800 | 0xF6) # 6 rungs: the bottom three rows + assert battery_cell(60).plain[0] == chr(0x2800 | 0xE6) # 5 rungs: + a left dot + assert battery_cell(45).plain[0] == chr(0x2800 | 0xE4) # 4 rungs: the bottom two rows + assert battery_cell(30).plain[0] == chr(0x2800 | 0xC4) # 3 rungs: + a left dot + assert battery_cell(20).plain[0] == chr(0x2800 | 0xC0) # 2 rungs: the bottom row + assert battery_cell(5).plain[0] == chr(0x2800 | 0x40) # 1 rung: the bottom-left dot + # A dead-flat pack still lights that one dot rather than drawing an empty cell. + assert battery_cell(0).plain[0] == chr(0x2800 | 0x40) + + +def test_battery_cell_steps_on_every_eighth_of_the_pack() -> None: + """The fill is monotonic and really does carry eight distinct levels, 12.5% apart.""" + fills = [battery_cell(pct).plain[0] for pct in range(101)] + assert len(set(fills)) == 8 + # Each band takes its lower bound: 12.5% is the second rung, 87.5% the eighth. + assert fills[12] != fills[13] and fills[13] == fills[24] != fills[25] + assert fills[87] != fills[88] and fills[88] == fills[100] def test_battery_cell_shows_the_true_percent() -> None: @@ -57,21 +77,31 @@ def test_battery_cell_shows_the_true_percent() -> None: assert battery_cell(42).plain == chr(0x2800 | 0xE4) + " 42%" -def test_battery_cell_colours_by_tier() -> None: - """Green healthy, orange at a quarter, red near empty — the fuel-gauge palette.""" - assert str(battery_cell(90).style) == "batt.high" # green - assert str(battery_cell(60).style) == "batt.high" # green - assert str(battery_cell(30).style) == "batt.mid" # orange - assert str(battery_cell(5).style) == "batt.low" # red +def test_battery_cell_colours_by_band_while_the_dots_carry_the_detail() -> None: + """Three broad bands over half / over a quarter / below, each a block of its own hue.""" + assert _glyph_style(battery_cell(100)) == "batt.full" # light green on green + assert _glyph_style(battery_cell(50)) == "batt.full" + assert _glyph_style(battery_cell(49)) == "batt.mid" # yellow on brown + assert _glyph_style(battery_cell(25)) == "batt.mid" + assert _glyph_style(battery_cell(24)) == "batt.low" # light red on red + assert _glyph_style(battery_cell(7)) == "batt.low" + # The band holds across a band's worth of rungs, so only the fill moves inside it. + # (Below 6.25% the alarm takes the cell over, which the next test covers.) + turns = [p for p in range(8, 101) if _glyph_style(battery_cell(p)) != _glyph_style(battery_cell(p - 1))] + assert turns == [25, 50] + assert len({battery_cell(p).plain[0] for p in range(25, 50)}) == 2 # two rungs per band -def test_battery_cell_blinks_when_critically_low() -> None: - """Below the critical line the red glyph flickers to a dim slate on alternate frames.""" - assert 5 <= _BATTERY_CRITICAL - assert str(battery_cell(5, frame=0).style) == "batt.low" # the on-beat, red - assert str(battery_cell(5, frame=1).style) == "batt.dim" # the off-beat, dim - # Above the critical line the glyph never blinks. - assert {str(battery_cell(40, frame=f).style) for f in range(4)} == {"batt.mid"} +def test_battery_cell_alarm_drops_the_block_on_alternate_frames() -> None: + """Under 6.25% the cell alternates black-on-red with the light red on the bare page.""" + # Half a rung: a rung is an eighth of the pack, so the alarm line is 6.25%. + assert _BATTERY_FLASH_PCT == 6.25 + assert _glyph_style(battery_cell(6, frame=0)) == "batt.flash" # black dots on red + assert _glyph_style(battery_cell(6, frame=1)) == "batt.flash.off" # light red, no ground + assert _glyph_style(battery_cell(0, frame=1)) == "batt.flash.off" + # Everything above the line holds its band, however low it is. + assert {_glyph_style(battery_cell(7, frame=f)) for f in range(4)} == {"batt.low"} + assert {_glyph_style(battery_cell(40, frame=f)) for f in range(4)} == {"batt.mid"} def test_battery_cell_charging_sweeps_bottom_to_full_holding_the_percent() -> None: @@ -81,17 +111,27 @@ def test_battery_cell_charging_sweeps_bottom_to_full_holding_the_percent() -> No assert fills[4] == "⣿" # full assert fills[5] == fills[0] # loops back assert battery_cell(20, charging=True, frame=4).plain.endswith(" 20%") - # The charge colour tracks the real state of charge (20% → red), held across the sweep. - assert {str(battery_cell(20, charging=True, frame=f).style) for f in range(6)} == {"batt.low"} -def test_battery_cell_sweeps_even_where_decoration_is_switched_off() -> None: - """``animate=False`` silences the blink, never the sweep — the sweep *is* the state.""" - fills = [battery_cell(20, charging=True, frame=f, animate=False).plain[0] for f in range(5)] - assert fills == [battery_cell(20, charging=True, frame=f).plain[0] for f in range(5)] - assert len(set(fills)) == 5 # it really climbs, rather than holding one frame - # The blink, being decoration over a charge the cell already shows, does hold still. - assert {str(battery_cell(5, frame=f, animate=False).style) for f in range(4)} == {"batt.low"} +def test_battery_cell_charging_keeps_the_bands_colour_while_the_fill_sweeps() -> None: + """The sweep is an animation, not a reading: colour still answers for the real charge.""" + assert {_glyph_style(battery_cell(20, charging=True, frame=f)) for f in range(5)} == {"batt.low"} + assert {_glyph_style(battery_cell(40, charging=True, frame=f)) for f in range(5)} == {"batt.mid"} + assert {_glyph_style(battery_cell(90, charging=True, frame=f)) for f in range(5)} == {"batt.full"} + + +def test_battery_cell_charging_never_alarms_however_empty_the_pack_is() -> None: + """A pack taking charge says so with the sweep; the alarm would only fight it.""" + for pct in (0, 3, 6, 10, 20): + styles = {_glyph_style(battery_cell(pct, charging=True, frame=f)) for f in range(10)} + assert styles == {"batt.low"} + + +def test_battery_cell_animates_off_the_frame_counter_alone() -> None: + """Both live states run on every platform: no effects flag, only the repaint cadence.""" + fills = [battery_cell(20, charging=True, frame=f).plain[0] for f in range(5)] + assert len(set(fills)) == 5 # the sweep really climbs, rather than holding one frame + assert len({_glyph_style(battery_cell(3, frame=f)) for f in range(2)}) == 2 # and alarms def test_battery_cell_at_full_rests_full_however_the_charging_flag_reads() -> None: